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

try {
    session_start();
    require_once '../core/api.php'; 

    $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
    $routeName = isset($_POST['route_name']) ? filter_var(trim($_POST['route_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : '';
    $routeDay = isset($_POST['route_day']) ? filter_var(trim($_POST['route_day']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : '';
    $weekNumber = isset($_POST['week_number']) ? filter_var($_POST['week_number'], FILTER_VALIDATE_INT) : null;

    if (empty($userId)) {
        throw new Exception('ERROR DE SESION');
    }

    if (empty($routeName) || $weekNumber === false || is_null($weekNumber)) {
        throw new Exception('DATOS FALTANTES');
    }

    $stmt = $pdo->prepare("INSERT INTO routes (user_id, week_number, route_name, route_day) VALUES (?, ?, ?, ?)");
    $stmt->execute([$userId, $weekNumber, $routeName, $routeDay]);

    $newId = $pdo->lastInsertId();

    $response = [
        'success' => true,
        'message' => 'RUTA CREADA',
        'new_route' => [
            'id' => $newId,
            'user_id' => $userId,
            'week_number' => $weekNumber,
            'route_name' => $routeName,
            'route_day' => $routeDay
        ]
    ];

} catch (PDOException $e) {
    error_log("Error PDO en routes-create.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;
?>