<?php
ob_start();
header('Content-Type: application/json');
$response = ['status' => 'error', '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);
    $routeName = filter_var(trim($_POST['route_name'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $routeDay = filter_var(trim($_POST['route_day'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if (empty($userId) || empty($routeId) || empty($routeName)) {
        throw new Exception('DATOS FALTANTES O ERROR DE SESION');
    }

    $stmt = $pdo->prepare("UPDATE routes SET route_name = ?, route_day = ? WHERE id = ? AND user_id = ?");
    $stmt->execute([$routeName, $routeDay, $routeId, $userId]);

    $response = ['status' => 'success', 'message' => 'RUTA ACTUALIZADA'];

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

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