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

    $routeId = filter_var($_POST['route_id'] ?? null, FILTER_VALIDATE_INT);

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

    $pdo->beginTransaction();

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

    $stmt_delete = $pdo->prepare("DELETE FROM routes WHERE id = ?");
    $stmt_delete->execute([$routeId]);

    $pdo->commit();

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

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