<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    session_start(); 
    require_once '../core/api.php';

    $userId = $_SESSION['user_id'] ?? null; 
    $clientId = filter_var($_POST['client_id'] ?? null, FILTER_VALIDATE_INT);
    $routeId = filter_var($_POST['route_id'] ?? null, FILTER_VALIDATE_INT);
    $weekNumber = filter_var($_POST['week_number'] ?? null, FILTER_VALIDATE_INT);

    if ($clientId === false || $routeId === false || $weekNumber === false || !$clientId || !$routeId || !$weekNumber || empty($userId)) {
        throw new Exception('DATOS FALTANTES O ERROR DE SESION');
    }

    $stmt_check_ownership = $pdo->prepare("
        SELECT 1 
        FROM routes r 
        JOIN clients c ON c.id = ? 
        WHERE r.id = ? AND r.user_id = ? AND c.user_id = ?
    ");
    $stmt_check_ownership->execute([$clientId, $routeId, $userId, $userId]);
    if ($stmt_check_ownership->rowCount() == 0) {
        throw new Exception('ASIGNACION NO AUTORIZADA: RUTA O CLIENTE NO PERTENECE AL USUARIO');
    }
    
    // Verificar si ya está asignado
    $stmt_check_assigned = $pdo->prepare("SELECT COUNT(*) FROM route_clients WHERE client_id = ? AND route_id = ? AND week_number = ?");
    $stmt_check_assigned->execute([$clientId, $routeId, $weekNumber]);
    if ($stmt_check_assigned->fetchColumn() > 0) {
         $response = ['success' => true, 'message' => 'YA ASIGNADO']; 
         if (ob_get_level() > 0) ob_end_clean();
         echo json_encode($response);
         exit;
    }

    $stmt_max_order = $pdo->prepare("SELECT MAX(order_index) FROM route_clients WHERE route_id = ? AND week_number = ?");
    $stmt_max_order->execute([$routeId, $weekNumber]);
    $max_order = $stmt_max_order->fetchColumn();
    $new_order = ($max_order === null) ? 0 : $max_order + 1;

    $stmt = $pdo->prepare("INSERT IGNORE INTO route_clients (client_id, route_id, week_number, order_index) VALUES (?, ?, ?, ?)");
    $stmt->execute([$clientId, $routeId, $weekNumber, $new_order]);
    
    $response = ['success' => true, 'message' => 'CLIENTE ASIGNADO'];

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

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