<?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 id_arrendatario, nombre, rut, direccion, celular, email, patente_vehiculo
    FROM arrendatarios
    WHERE nombre LIKE CONCAT('%', ?, '%') OR rut LIKE CONCAT('%', ?, '%')
    ORDER BY id_arrendatario DESC
    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'],
        'id'               => $row['id_arrendatario'],
        'rut'              => $row['rut'],
        'direccion'        => $row['direccion'],
        'celular'          => $row['celular'],
        'email'            => $row['email'],
        'patente_vehiculo' => $row['patente_vehiculo'],
    ];
}
echo json_encode($data);
