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

    if ($routeId === false || empty($routeId) || empty($userId)) {
        throw new Exception('ID DE RUTA REQUERIDO O ERROR DE SESION');
    }

    $pdo->beginTransaction();

    // Eliminar asignaciones primero (route_clients)
    $stmt_unassign = $pdo->prepare("DELETE FROM route_clients WHERE route_id = ?");
    $stmt_unassign->execute([$routeId]);

    // Eliminar la ruta (Validación IDOR implícita con user_id)
    $stmt_delete = $pdo->prepare("DELETE FROM routes WHERE id = ? AND user_id = ?");
    $stmt_delete->execute([$routeId, $userId]);

    $pdo->commit();

    if ($stmt_delete->rowCount() > 0) {
        $response = ['status' => 'success', 'message' => 'RUTA ELIMINADA'];
    } else {
        $response = ['status' => 'error', 'message' => 'RUTA NO ENCONTRADA O NO AUTORIZADA']; 
    }

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