<?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';
    session_start();

    $userId = $_SESSION['user_id'] ?? null;
    $routeId = filter_var($_POST['route_id'] ?? null, FILTER_VALIDATE_INT);
    $clientIds = $_POST['client_ids'] ?? [];

    if (empty($userId) || $routeId === false || !is_array($clientIds)) {
        throw new Exception('DATOS INVALIDOS');
    }

    $pdo->beginTransaction();
    
    foreach ($clientIds as $index => $clientId) {
        $clientId = filter_var($clientId, FILTER_VALIDATE_INT);
        if ($clientId === false) { continue; }

        $stmt = $pdo->prepare("UPDATE route_clients SET order_index = ? WHERE route_id = ? AND client_id = ?");
        $stmt->execute([$index, $routeId, $clientId]);
    }
    
    $pdo->commit();
    $response = ['success' => true, 'message' => 'ORDEN GUARDADA'];

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error PDO en routes-clients-update-order.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;
?>