<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Auth;
use App\Core\Database;
use PDO;

class InterventionsController extends Controller
{
    // Affiche la vue live avec carte centrée sur la dernière position connue
    public function live(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        $user = Auth::user();
        $userId = (int)($_GET['user_id'] ?? ($user['id'] ?? 0));
        if ($userId <= 0) { $userId = (int)($user['id'] ?? 0); }
        $pdo = Database::pdo();
        // Assurer structure table/colonnes avant lecture
        $this->ensureEventsStructure($pdo);
        $pos = null;
        try {
            $stmt = $pdo->prepare('SELECT lat, lng, taken_at FROM user_takeover_events WHERE user_id=? AND lat IS NOT NULL AND lng IS NOT NULL ORDER BY id DESC LIMIT 1');
            $stmt->execute([$userId]);
            $pos = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        } catch (\Throwable $e) {
            // Si colonnes absentes malgré tentative création, ignorer et laisser carte sans position.
        }

        // Vérifier un takeover actif (affichage badge/infos)
        $tk = $pdo->prepare('SELECT takeover_at FROM users WHERE id=?');
        $tk->execute([$userId]);
        $takeoverAt = $tk->fetchColumn();

        // Si un incident est fourni, extraire sa dernière géolocalisation
        $incidentId = (int)($_GET['incident_id'] ?? 0);
        $incidentPos = null;
        $incidentTitle = null;
        $interventionPhotos = [];
        if ($incidentId > 0) {
            try {
                // Récupérer titre + coordonnées + statut
                $si = $pdo->prepare('SELECT r.id as report_id, r.gps_lat, r.gps_lng, r.submitted_at, r.updated_at, i.title, s.key_name AS status_key, s.color AS status_color
                                      FROM incident_reports r 
                                      JOIN incidents i ON i.id = r.incident_id 
                                      JOIN incident_statuses s ON s.id = i.status_id
                                      WHERE r.incident_id=? AND r.gps_lat IS NOT NULL AND r.gps_lng IS NOT NULL 
                                      ORDER BY r.id DESC LIMIT 1');
                $si->execute([$incidentId]);
                $row = $si->fetch(PDO::FETCH_ASSOC) ?: null;
                if ($row && $row['gps_lat'] !== null && $row['gps_lng'] !== null) {
                    $incidentPos = [ 'lat' => (float)$row['gps_lat'], 'lng' => (float)$row['gps_lng'] ];
                    $incidentAt  = $row['submitted_at'] ?: $row['updated_at'] ?: null;
                    $incidentTitle = $row['title'] ?? null;
                    $incidentStatusKey = $row['status_key'] ?? null;
                    $incidentStatusColor = $row['status_color'] ?? null;
                    
                    // Charger les photos d'intervention
                    $photos = $pdo->prepare('SELECT path, observation, lat, lng, taken_at, uploaded_at FROM incident_attachments WHERE report_id = ? AND type = "intervention_photo" ORDER BY uploaded_at DESC');
                    $photos->execute([(int)$row['report_id']]);
                    $interventionPhotos = $photos->fetchAll(PDO::FETCH_ASSOC) ?: [];
                }
            } catch (\Throwable $e) { /* ignore */ }
            // Fallback si pas de coordonnées dans rapport mais titre existant
            if (!$incidentPos) {
                try {
                    $ti = $pdo->prepare('SELECT i.title, s.key_name AS status_key, s.color AS status_color 
                                          FROM incidents i JOIN incident_statuses s ON s.id=i.status_id WHERE i.id=?');
                    $ti->execute([$incidentId]);
                    $tiRow = $ti->fetch(PDO::FETCH_ASSOC) ?: null;
                    if ($tiRow) {
                        $incidentTitle = $tiRow['title'] ?? $incidentTitle;
                        $incidentStatusKey = $tiRow['status_key'] ?? ($incidentStatusKey ?? null);
                        $incidentStatusColor = $tiRow['status_color'] ?? ($incidentStatusColor ?? null);
                    }
                } catch (\Throwable $e2) { /* ignore */ }
            }
        }

        $this->view('interventions/live', [
            'target_user_id' => $userId,
            'position' => $pos,
            'takeover_at' => $takeoverAt,
            'incident_id' => $incidentId,
            'incident_pos' => $incidentPos,
            'incident_title' => $incidentTitle,
            'incident_pos_at' => $incidentAt ?? null,
            'incident_status_key' => $incidentStatusKey ?? null,
            'incident_status_color' => $incidentStatusColor ?? null,
            'intervention_photos' => $interventionPhotos,
            'pageTitle' => 'Vue live intervention'
        ]);
    }

    // Retourne JSON {lat, lng, taken_at} pour polling
    public function location(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        $user = Auth::user();
        $userId = (int)($_GET['user_id'] ?? ($user['id'] ?? 0));
        if ($userId <= 0) { $userId = (int)($user['id'] ?? 0); }
        $pdo = Database::pdo();
        $this->ensureEventsStructure($pdo);
        $pos = null;
        try {
            $stmt = $pdo->prepare('SELECT lat, lng, taken_at FROM user_takeover_events WHERE user_id=? AND lat IS NOT NULL AND lng IS NOT NULL ORDER BY id DESC LIMIT 1');
            $stmt->execute([$userId]);
            $pos = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        } catch (\Throwable $e) {
            $pos = null;
        }

        header('Content-Type: application/json; charset=utf-8');
        if ($pos && $pos['lat'] !== null && $pos['lng'] !== null) {
            echo json_encode(['status'=>'ok','lat'=>(float)$pos['lat'],'lng'=>(float)$pos['lng'],'taken_at'=>$pos['taken_at']], JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode(['status'=>'not_found']);
        }
        exit;
    }

    // Garantit l'existence de la table user_takeover_events et des colonnes lat/lng/ip/user_agent
    private function ensureEventsStructure(PDO $pdo): void
    {
        try {
            // Créer la table si absente (mêmes colonnes que dans UsersController)
            $pdo->exec("CREATE TABLE IF NOT EXISTS user_takeover_events (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                taken_at DATETIME NOT NULL,
                ip_address VARCHAR(64) NULL,
                user_agent TEXT NULL,
                lat DECIMAL(10,7) NULL,
                lng DECIMAL(10,7) NULL,
                INDEX (user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

            // Vérifier colonnes
            $db = $pdo->query('SELECT DATABASE()')->fetchColumn();
            if (!$db) return;
            $need = [
                'ip_address' => 'ADD COLUMN `ip_address` VARCHAR(64) NULL',
                'user_agent' => 'ADD COLUMN `user_agent` TEXT NULL',
                'lat' => 'ADD COLUMN `lat` DECIMAL(10,7) NULL',
                'lng' => 'ADD COLUMN `lng` DECIMAL(10,7) NULL',
            ];
            foreach ($need as $col => $ddl) {
                $q = $pdo->prepare('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME="user_takeover_events" AND COLUMN_NAME=?');
                $q->execute([$db, $col]);
                if ((int)$q->fetchColumn() === 0) {
                    $pdo->exec('ALTER TABLE `user_takeover_events` ' . $ddl);
                }
            }
        } catch (\Throwable $e) { /* ignore */ }
    }
}
