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

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

    $userId = $_SESSION['user_id'] ?? null;
    $routeIds = $_POST['route_ids'] ?? null;

    if (empty($userId) || !is_array($routeIds)) {
        throw new Exception('DATOS INVALIDOS');
    }

    $pdo->beginTransaction();

    foreach ($routeIds as $index => $routeId) {
        $routeId = filter_var($routeId, FILTER_VALIDATE_INT);
        if ($routeId === false) continue;
        
        $stmt = $pdo->prepare("UPDATE routes SET sort_order = ? WHERE id = ? AND user_id = ?");
        $stmt->execute([$index, $routeId, $userId]);
    }

    $pdo->commit();
    $response = ['success' => true, 'message' => 'ORDEN GUARDADA'];

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