<?php
namespace App\Controllers\Responder;

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 IncidentController
{
    private function getResponder()
    {
        return Responder::where('user_id', Auth::user()['id']);
    }

    public function show($id)
    {
        $responder = $this->getResponder();
        $incident = Incident::getDetails($id);

        if (!$incident || $incident['assigned_responder_id'] != $responder['id']) {
            return Response::abort(403, 'Unauthorized', 'You are not assigned to this emergency.');
        }

        View::make('responder/incident_detail')
            ->setLayout('layout')
            ->with([
                'title' => 'Active Incident #' . str_pad($incident['id'], 5, '0', STR_PAD_LEFT),
                'incident' => $incident
            ])
            ->render();
    }

    public function accept($id)
    {
        $responder = $this->getResponder();
        $incident = Incident::find($id);

        if (!$incident || $incident['assigned_responder_id'] != $responder['id']) {
            return Response::json(['status' => 'error', 'message' => 'Unauthorized or incident not found.'], Response::FORBIDDEN);
        }

        if ($incident['status'] !== 'dispatched') {
            return Response::json(['status' => 'error', 'message' => 'This incident cannot be accepted at this time.'], Response::BAD_REQUEST);
        }

        // 1. Update the incident status
        Incident::update($id, ['status' => 'accepted']);

        // 2. Log the event in the human-readable timeline
        IncidentEvent::create([
            'incident_id' => $id,
            'actor_id' => Auth::user()['id'],
            'action_type' => 'RESPONDER_ACCEPTED',
            'action_details' => 'Responder accepted the dispatch and is preparing to move.'
        ]);

        return Response::json(['status' => 'success', 'message' => 'Dispatch accepted. Please proceed to the location.']);
    }

    public function updateStatus($id)
    {
        $data = Request::all();
        $responder = $this->getResponder();
        $incident = Incident::find($id);

        if (!$incident || $incident['assigned_responder_id'] != $responder['id']) {
            return Response::json(['status' => 'error', 'message' => 'Unauthorized'], Response::FORBIDDEN);
        }

        $newStatus = $data['status'] ?? '';
        $validStatuses = ['en_route', 'resolved'];

        if (!in_array($newStatus, $validStatuses)) {
            return Response::json(['status' => 'error', 'message' => 'Invalid status update.'], Response::BAD_REQUEST);
        }

        Incident::update($id, ['status' => $newStatus]);

        $details = $newStatus === 'en_route' ? 'Responder is currently en route to the scene.' : 'Responder has resolved the emergency on-site.';
        
        IncidentEvent::create([
            'incident_id' => $id,
            'actor_id' => Auth::user()['id'],
            'action_type' => strtoupper('STATUS_' . $newStatus),
            'action_details' => $details
        ]);

        return Response::json(['status' => 'success', 'message' => 'Status updated to ' . ucwords(str_replace('_', ' ', $newStatus))]);
    }
}