<?php
require_once 'includes/auth.php';
exigir_rol('propietario', 'admin');
require_once 'conexion.php';
header('Content-Type: application/json; charset=UTF-8');

$term = $_GET['term'] ?? '';

$stmt = $conn->prepare("
    SELECT DISTINCT rut, nombre FROM (
        SELECT rut, nombre FROM arrendatarios
        UNION
        SELECT rut, nombre FROM acompanantes
    ) t
    WHERE t.rut LIKE CONCAT('%', ?, '%') OR t.nombre LIKE CONCAT('%', ?, '%')
    LIMIT 10");
$stmt->bind_param('ss', $term, $term);
$stmt->execute();
$res = $stmt->get_result();

$data = [];
while ($row = $res->fetch_assoc()) {
    $data[] = [
        'label'  => $row['nombre'] . ' — ' . $row['rut'],
        'value'  => $row['nombre'],
        'nombre' => $row['nombre'],
        'rut'    => $row['rut'],
    ];
}
echo json_encode($data);
