<?php
namespace App\Controllers\Admin;

use Core\Auth;
use Core\Request;
use Core\Response;
use Core\View;
use App\Models\Incident;
use App\Models\Responder;
use App\Models\IncidentEvent;

class DispatchController
{
    public function pending()
    {
        $sql = "
            SELECT i.*, c.name as category_name, v.full_name as victim_name, v.phone_number 
            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.status IN ('pending', 'verified')
            ORDER BY i.created_at DESC
        ";
        $incidents = Incident::fetchAll($sql);

        View::make('admin/incidents_pending')
            ->setLayout('admin_layout')
            ->with(['title' => 'Pending Dispatches', 'incidents' => $incidents])
            ->render();
    }

    public function review($id)
    {
        $incident = Incident::getDetails($id);
        
        if (!$incident) {
            return Response::abort(404, 'Not Found', 'Incident not found.');
        }

        // MAGIC HAPPENS HERE: Ask the database for the 5 nearest available responders 
        // using the Haversine formula based on the victim's exact GPS coordinates.
        $nearestResponders = Responder::getNearest(
            $incident['latitude'], 
            $incident['longitude'], 
            $incident['category_id'], 
            5
        );

        View::make('admin/incident_review')
            ->setLayout('admin_layout')
            ->with([
                'title' => 'Review Incident #' . $id,
                'incident' => $incident,
                'nearestResponders' => $nearestResponders,
                'timeline' => IncidentEvent::getIncidentTimeline($id)
            ])
            ->render();
    }

    public function verify($id)
    {
        Incident::update($id, ['status' => 'verified']);
        
        IncidentEvent::create([
            'incident_id' => $id,
            'actor_id' => Auth::user()['id'],
            'action_type' => 'ADMIN_VERIFIED',
            'action_details' => 'Admin verified the emergency as legitimate.'
        ]);

        return Response::json(['status' => 'success', 'message' => 'Incident verified. Ready for dispatch.']);
    }

    public function dispatchResponder($id)
    {
        $data = Request::all();
        
        if (empty($data['responder_id'])) {
            return Response::json(['status' => 'error', 'message' => 'Please select a responder.'], Response::BAD_REQUEST);
        }

        // Update the incident with the assigned responder
        Incident::update($id, [
            'assigned_responder_id' => $data['responder_id'],
            'status' => 'dispatched'
        ]);

        // Log the dispatch event
        IncidentEvent::create([
            'incident_id' => $id,
            'actor_id' => Auth::user()['id'],
            'action_type' => 'ADMIN_DISPATCHED',
            'action_details' => 'Admin assigned Responder Unit #' . $data['responder_id'] . ' to the scene.'
        ]);

        return Response::json(['status' => 'success', 'message' => 'Responder has been successfully dispatched!']);
    }
}