<?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;
    $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 O ERROR DE SESION');
    }
    
    $stmt_check_ownership = $pdo->prepare("SELECT 1 FROM routes WHERE id = ? AND user_id = ?");
    $stmt_check_ownership->execute([$routeId, $userId]);
    if ($stmt_check_ownership->rowCount() == 0) {
        throw new Exception('ACCION NO AUTORIZADA: RUTA NO PERTENECE AL USUARIO');
    }

    $pdo->beginTransaction();
    
    // Actualizar el order_index
    $stmt = $pdo->prepare("UPDATE route_clients SET order_index = ? WHERE route_id = ? AND client_id = ?");

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

        $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;
?>