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

try {
    require_once('db_connection.php');
    require_once '../files/guardiankey.php';

    $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);
    $action = filter_var($_POST['action'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if (empty($clientId) || empty($routeId) || empty($weekNumber) || empty($action)) {
        throw new Exception('DATOS FALTANTES');
    }

    if ($action === 'add') {
        $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM route_clients WHERE client_id = ? AND route_id = ? AND week_number = ?");
        $stmt_check->execute([$clientId, $routeId, $weekNumber]);
        if ($stmt_check->fetchColumn() > 0) {
             throw new Exception('CLIENTE YA ASIGNADO');
        }

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

    } elseif ($action === 'remove') {
        $stmt = $pdo->prepare("DELETE FROM route_clients WHERE client_id = ? AND route_id = ? AND week_number = ?");
        $stmt->execute([$clientId, $routeId, $weekNumber]);
        
        if ($stmt->rowCount() > 0) {
            $response = ['success' => true, 'message' => 'CLIENTE QUITADO'];
        } else {
            $response = ['success' => true, 'message' => 'NO ENCONTRADO'];
        }

    } else {
        throw new Exception('ACCION INVALIDA');
    }

} catch (PDOException $e) {
    error_log("Error PDO en route-client-assignment.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;
?>