<?php
namespace App\Controllers;

use Core\Request;
use Core\Response;
use Core\Session;
use App\Models\Message;
use App\Models\Incident;
use App\Models\User;

class ChatController
{
    public function getMessages($id)
    {
        // Verify the incident exists
        $incident = Incident::find($id);
        if (!$incident) {
            return Response::json(['status' => 'error', 'message' => 'Incident not found.'], Response::NOT_FOUND);
        }

        // Fetch all messages for this specific emergency
        // Use the model method that joins the sender details (name, role)
        $messages = Message::getByIncident($id);

        return Response::json([
            'status' => 'success',
            'data' => $messages
        ]);
    }

    public function sendMessage($id)
    {
        $data = Request::json(); // Assume AJAX JSON post

        if (empty($data['message_text'])) {
            return Response::json(['status' => 'error', 'message' => 'Message text cannot be empty.'], Response::BAD_REQUEST);
        }

        // Identify the sender (can be the guest victim or an authenticated responder)
        Session::start();
        $senderId = Session::get('user_id') ?? Session::get('current_victim_id');

        if (!$senderId) {
            return Response::json(['status' => 'error', 'message' => 'Unauthorized sender.'], Response::UNAUTHORIZED);
        }

        $userExists = User::find($senderId);
        if (!$userExists) {
            // The session is stale (database was likely reset). Destroy it.
            Session::destroy();
            return Response::json(['status' => 'error', 'message' => 'Session expired. Please reload the page to reconnect.'], Response::UNAUTHORIZED);
        }

        // Create the message in the database
        $message = Message::create([
            'incident_id' => $id,
            'sender_id' => $senderId,
            'message_text' => htmlspecialchars($data['message_text'], ENT_QUOTES, 'UTF-8'),
            'is_read' => 0
        ]);

        if (!$message) {
             return Response::json(['status' => 'error', 'message' => 'Failed to send message.'], Response::INTERNAL_SERVER_ERROR);
        }

        return Response::json([
            'status' => 'success',
            'data' => $message
        ]);
    }
}