<?php
include 'includes/db.php';

header('Content-Type: application/json');

$tipo = $_GET['tipo'] ?? '';
$q = $_GET['q'] ?? '';

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

$resultados = [];

try {
    if ($tipo == 'cliente') {
        // Buscar en tabla clientes
        $stmt = $pdo->prepare("SELECT id, nombres_apellido as text, celular, domicilio, ciudad FROM clientes WHERE nombres_apellido LIKE ? LIMIT 10");
        $stmt->execute(["%$q%"]);
        $resultados = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } elseif ($tipo == 'vehiculo') {
        // Buscar vehículos únicos en las tablas de ordenes
        // Usamos UNION para buscar en todas las categorías
        $sql = "SELECT DISTINCT vehiculo as text FROM (
                    SELECT vehiculo FROM ordenes_frenos WHERE vehiculo LIKE ?
                    UNION
                    SELECT vehiculo FROM ordenes_motor WHERE vehiculo LIKE ?
                    UNION
                    SELECT vehiculo FROM ordenes_suspension WHERE vehiculo LIKE ?
                    UNION
                    SELECT vehiculo FROM ordenes_otros WHERE vehiculo LIKE ?
                ) as t LIMIT 10";
        $stmt = $pdo->prepare($sql);
        $term = "%$q%";
        $stmt->execute([$term, $term, $term, $term]);
        $resultados = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } elseif ($tipo == 'patente') {
        // Buscar patentes únicas
        $sql = "SELECT DISTINCT patente as text FROM (
                    SELECT patente FROM ordenes_frenos WHERE patente LIKE ?
                    UNION
                    SELECT patente FROM ordenes_motor WHERE patente LIKE ?
                    UNION
                    SELECT patente FROM ordenes_suspension WHERE patente LIKE ?
                    UNION
                    SELECT patente FROM ordenes_otros WHERE patente LIKE ?
                ) as t LIMIT 10";
        $stmt = $pdo->prepare($sql);
        $term = "%$q%";
        $stmt->execute([$term, $term, $term, $term]);
        $resultados = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    // En caso de error, devolver array vacio para no romper el JS
    $resultados = [];
}

echo json_encode($resultados);
?>