<?php
ob_start();
header('Content-Type: application/json');
$response = [
    'status' => 'error',
    'routes' => [],
    'workspace_clients' => [],
    'master_client_list' => [],
    'assignments' => [],
    'message' => 'ERROR DESCONOCIDO'
];

try {
    session_start();
    require_once '../core/api.php';
    
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    error_reporting(E_ALL);

    $userId = $_SESSION['user_id'] ?? null;
    $weekNumber = filter_var($_GET['week'] ?? 1, FILTER_VALIDATE_INT);

    if (empty($userId)) {
        throw new Exception('ERROR DE SESION');
    }
    if ($weekNumber === false) {
         throw new Exception('SEMANA INVALIDA');
    }

    // 1. Obtener Rutas
    $stmt_routes = $pdo->prepare("SELECT * FROM routes WHERE user_id = ? AND week_number = ? ORDER BY sort_order ASC");
    $stmt_routes->execute([$userId, $weekNumber]);
    $response['routes'] = $stmt_routes->fetchAll(PDO::FETCH_ASSOC);

    // 2. Clientes en el Workspace (Tabla route_workspace)
    $stmt_workspace = $pdo->prepare("
        SELECT c.*, CONCAT(c.first_name, ' ', c.last_name) as name, c.street_address as address, c.service_details as service
        FROM clients c
        JOIN route_workspace rw ON c.id = rw.client_id
        WHERE rw.user_id = ?
        ORDER BY name ASC
    ");
    $stmt_workspace->execute([$userId]);
    $response['workspace_clients'] = $stmt_workspace->fetchAll(PDO::FETCH_ASSOC);

    // 3. Lista Maestra de Clientes
    $stmt_master = $pdo->prepare("
        SELECT id, CONCAT(first_name, ' ', last_name) as name, street_address as address, service_details as service, service_time, service_value
        FROM clients
        WHERE user_id = ?
    ");
    $stmt_master->execute([$userId]);
    $response['master_client_list'] = $stmt_master->fetchAll(PDO::FETCH_ASSOC);

    // 4. Asignaciones de Clientes a Rutas (Tabla route_clients)
    $stmt_assignments = $pdo->prepare("
        SELECT rc.route_id, rc.client_id, rc.week_number 
        FROM route_clients rc
        JOIN routes r ON rc.route_id = r.id
        WHERE r.user_id = ? AND rc.week_number = ?
    ");
    $stmt_assignments->execute([$userId, $weekNumber]);
    $response['assignments'] = $stmt_assignments->fetchAll(PDO::FETCH_ASSOC);

    $response['status'] = 'success';
    unset($response['message']); 

} catch (PDOException $e) {
    error_log("Error PDO en routes-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    $response['message'] = strtoupper($e->getMessage());
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
?>