<?php
declare(strict_types=1);
// db/search-routes.php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../core/api.php';
require_once __DIR__ . '/../core/security.php'; // Incluye la función sanitizeData

$user_id = $_SESSION['user_id'] ?? 1;
$q = $_GET['q'] ?? '';

// Sanitize input
$q = sanitizeData($q);

if (strlen($q) < 2) { echo json_encode([]); exit; }

$term = "%" . $q . "%";

$sql = "
    SELECT 
        r.id, 
        r.route_name, 
        r.route_day, 
        CONCAT(s.first_name, ' ', s.last_name) as staff_name,
        'route' as type 
    FROM routes r
    LEFT JOIN staff s ON r.staff_id = s.id
    WHERE r.user_id = :uid AND (
        r.route_name LIKE :t1 OR 
        r.route_day LIKE :t2 OR 
        s.first_name LIKE :t3 OR
        s.last_name LIKE :t4
    )
    LIMIT 20";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':uid' => $user_id, 
    ':t1' => $term, 
    ':t2' => $term, 
    ':t3' => $term, 
    ':t4' => $term
]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
?>