<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../core/api.php'; 
require_once __DIR__ . '/../core/security.php'; // Incluye la función sanitizeData

$user_id = $_SESSION['user_id'] ?? 1;

// Validación estricta del ID como entero
$id = filter_var($_GET['id'] ?? null, FILTER_VALIDATE_INT);
if ($id === false || $id === null) { 
    echo json_encode(['error' => 'ID de ruta no válido']); 
    exit; 
}

$response = [];

try {
    // Consulta de la ruta y el staff asignado
    $sqlRoute = "
        SELECT 
            r.*, 
            s.first_name, s.last_name, s.profile_photo_url, s.schedule_config, s.hourly_rate
        FROM routes r
        LEFT JOIN staff s ON r.staff_id = s.id
        WHERE r.id = :id AND r.user_id = :user_id
    ";
    $stmt = $pdo->prepare($sqlRoute);
    $stmt->execute([':id' => $id, ':user_id' => $user_id]);
    $route = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$route) { echo json_encode(['error' => 'Ruta no encontrada']); exit; }

    // Consulta de los clientes de la ruta
    $sqlClients = "
        SELECT 
            c.id, c.first_name, c.last_name, c.company, c.street_address, 
            c.service_time, c.service_value, c.city
        FROM route_clients rc
        JOIN clients c ON rc.client_id = c.id
        WHERE rc.route_id = :rid
        ORDER BY rc.order_index ASC
    ";
    $stmtC = $pdo->prepare($sqlClients);
    $stmtC->execute([':rid' => $id]);
    $clients = $stmtC->fetchAll(PDO::FETCH_ASSOC);

    $totalValue = 0;
    $totalMinutes = 0;
    $clientCount = count($clients);

    foreach ($clients as $c) {
        $totalValue += floatval($c['service_value'] ?? 0);
        $totalMinutes += intval($c['service_time'] ?? 0);
    }

    $capacityAnalysis = [
        'status' => 'OK',
        'staff_minutes' => 0,
        'occupation_percent' => 0,
        'message' => 'Carga de trabajo óptima'
    ];

    if (!empty($route['schedule_config'])) {
        $dayMap = [
            'lunes' => 'Mon', 'martes' => 'Tue', 'miércoles' => 'Wed', 'miercoles' => 'Wed',
            'jueves' => 'Thu', 'viernes' => 'Fri', 'sábado' => 'Sat', 'sabado' => 'Sat', 'domingo' => 'Sun'
        ];
        
        // Manteniendo la lógica de limpieza de caracteres para mapeo de días
        $rDay = strtolower(trim(strip_tags($route['route_day'])));
        $rDay = str_replace(['&aacute;','&eacute;','&iacute;','&oacute;','&uacute;'], ['a','e','i','o','u'], $rDay);
        
        $jsonKey = $dayMap[$rDay] ?? null;
        $schedule = json_decode($route['schedule_config'], true);

        if ($jsonKey && isset($schedule[$jsonKey]) && $schedule[$jsonKey]['active']) {
            $start = strtotime($schedule[$jsonKey]['start']);
            $end = strtotime($schedule[$jsonKey]['end']);
            $availableMinutes = ($end - $start) / 60;
            
            $capacityAnalysis['staff_minutes'] = $availableMinutes;
            
            if ($availableMinutes > 0) {
                $percent = ($totalMinutes / $availableMinutes) * 100;
                $capacityAnalysis['occupation_percent'] = round($percent, 1);

                if ($percent > 100) {
                    $capacityAnalysis['status'] = 'OVERLOAD';
                    $capacityAnalysis['message'] = '¡ALERTA! Ruta excede horario. Considera dividir ruta.';
                } elseif ($percent > 85) {
                    $capacityAnalysis['status'] = 'WARNING';
                    $capacityAnalysis['message'] = 'Ruta cerca del límite de capacidad.';
                }
            }
        }
    }

    $response = [
        'route' => $route,
        'clients' => $clients,
        'metrics' => [
            'total_value' => number_format($totalValue, 2),
            'total_clients' => $clientCount,
            'total_time_hours' => floor($totalMinutes / 60),
            'total_time_minutes' => $totalMinutes % 60,
            'raw_minutes' => $totalMinutes
        ],
        'capacity' => $capacityAnalysis
    ];

    echo json_encode($response);

} catch (Exception $e) {
    error_log($e->getMessage());
    echo json_encode(['error' => 'Error interno calculando ruta']);
}
?>