<?php
namespace App\Controllers\Responder;

use Core\Auth;
use Core\View;
use App\Models\Responder;
use App\Models\Incident;

class DashboardController
{
    public function index()
    {
        $user = Auth::user();
        
        // Fetch the specific responder profile linked to this user account
        $responder = Responder::where('user_id', $user['id']);

        if (!$responder) {
            // Safety fallback in case the admin hasn't finished setting up their profile
            die("Your responder profile has not been fully configured by the Admin yet.");
        }

        // Custom query to fetch all incidents assigned to this responder, including victim details
        $sql = "
            SELECT 
                i.*, 
                c.name as category_name, 
                v.full_name as victim_name, 
                v.phone_number as victim_phone
            FROM 
                incidents i
            LEFT JOIN categories c ON i.category_id = c.id
            LEFT JOIN users v ON i.victim_id = v.id
            WHERE 
                i.assigned_responder_id = ?
            ORDER BY 
                CASE 
                    WHEN i.status IN ('dispatched', 'accepted', 'en_route') THEN 1
                    WHEN i.status = 'pending' THEN 2
                    ELSE 3
                END, 
                i.created_at DESC
        ";
        
        $incidents = Incident::fetchAll($sql, [$responder['id']]);

        View::make('responder/dashboard')
            ->setLayout('layout')
            ->with([
                'title' => 'Responder Dispatch Board - ERCS',
                'incidents' => $incidents,
                'responder' => $responder
            ])
            ->render();
    }
}