<?php
namespace App\Controllers;

use Core\View;
use Core\Request;
use Core\Response;
use Core\Validator;
use Core\Session;
use Core\Auth;
use App\Models\Incident;
use App\Models\Category;
use App\Models\User;

class IncidentController
{
    public function reportPage()
    {
        // Fetch categories (Police, Medical, Fire) to populate the dropdown
        $categories = Category::all();

        // Check if user is already logged in to pre-fill the form
        $user = Auth::check() ? Auth::user() : null;

        View::make('emergency/report')
            ->setLayout('layout')
            ->with([
                'title' => 'Report an Emergency',
                'categories' => $categories,
                'user' => $user
            ])
            ->render();
    }

    public function submitReport()
    {
        // 1. Validate incoming data including exact GPS coordinates
        $validator = Validator::validate($_POST)
            ->empty(['full_name', 'phone_number', 'category_id', 'description', 'latitude', 'longitude']);

        if (!$validator->passes()) {
            return Response::json(['status' => 'error', 'errors' => $validator->errors()], Response::BAD_REQUEST);
        }

        $data = Request::all();

        // 2. Handle Guest Victim Account Creation
        // We need a user ID for the database. If this phone number exists, use it. Otherwise, create a temporary one.
        $user = User::where('phone_number', $data['phone_number']);
        
        if (!$user) {
            $user = User::create([
                'full_name' => $data['full_name'],
                'phone_number' => $data['phone_number'],
                'email' => 'victim_' . time() . '@emergency.local', // Auto-generated fallback email
                'password' => password_hash(bin2hex(random_bytes(8)), PASSWORD_DEFAULT),
                'role' => 'victim'
            ]);
        }

        $imagePath = null;
        if (Request::hasFile('image')) {
            $file = Request::file('image');
            
            // Ensure the directory exists
            $uploadDir = FS_PUBLIC_PATH . '/media/incidents/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            // Generate secure unique filename
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $fileName = time() . '_' . uniqid() . '.' . $ext;
            $destination = $uploadDir . $fileName;
            
            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $imagePath = 'incidents/' . $fileName;
            }
        }

        // 3. Create the emergency record
        $incident = Incident::create([
            'victim_id' => $user['id'] ?? $user['id'],
            'category_id' => $data['category_id'],
            'description' => $data['description'],
            'latitude' => $data['latitude'],
            'longitude' => $data['longitude'],
            'image_url' => $imagePath,
            'status' => 'pending' // Ready for Admin verification
        ]);

        // 4. Authenticate the victim implicitly for this session so they can track the responder
        Session::start();
        Session::set('current_victim_id', $user['id'] ?? $user['id']);

        // Redirect to the live tracking view
        return Response::json([
            'status' => 'success',
            'redirect' => '/emergency/track/' . ($incident['id'] ?? $incident['id'])
        ], Response::OK);
    }

    public function show($id)
    {
        $incident = Incident::find($id);

        if (!$incident) {
            return Response::abort(404, 'Not Found', 'The requested emergency record does not exist.');
        }

        // Security Check: Ensure the person viewing is the victim who reported it, or an authorized responder/admin.
        Session::start();
        $currentVictimId = Session::get('current_victim_id');
        $loggedInUserId = Session::get('user_id');

        if ($incident['victim_id'] != $currentVictimId && !$loggedInUserId) {
            return Response::abort(403, 'Forbidden', 'You are not authorized to view this incident.');
        }

        View::make('emergency/track')
            ->setLayout('layout')
            ->with([
                'title' => 'Live Emergency Status',
                'incident' => $incident
            ])
            ->render();
    }
}