<?php
session_start();
if (!isset($_SESSION['rol']) || $_SESSION['rol'] !== 'propietario') {
    header("Location: login.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Registrar Arrendatario</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<style>
.ui-autocomplete {
    z-index: 1050;
    max-height: 200px;
    overflow-y: auto;
}
</style>
</head>

<body class="bg-light">

<div class="container mt-5">
<div class="card shadow">

<div class="card-header bg-primary text-white">
<h4>Registrar Arrendatario</h4>
</div>

<div class="card-body">

<form method="POST" action="registrar_arrendatario_guardar.php" enctype="multipart/form-data">

<!-- ================= DATOS ================= -->
<div class="row">
    <div class="col-md-6 mb-3">
        <label>Nombre</label>
        <input id="nombre" name="nombre" class="form-control" required autocomplete="off">
    </div>
    <div class="col-md-6 mb-3">
        <label>RUT</label>
        <input id="rut" name="rut" class="form-control" required>
    </div>
</div>

<div class="mb-3">
    <label>Dirección</label>
    <input id="direccion" name="direccion" class="form-control">
</div>

<div class="row">
    <div class="col-md-4 mb-3">
        <label>Celular</label>
        <input id="celular" name="celular" class="form-control">
    </div>
    <div class="col-md-4 mb-3">
        <label>Email</label>
        <input id="email" type="email" name="email" class="form-control">
    </div>
    <div class="col-md-4 mb-3">
        <label>Patente</label>
        <input id="patente_vehiculo" name="patente_vehiculo" class="form-control">
    </div>
</div>

<!-- ================= FECHAS ================= -->
<div class="row">
    <div class="col-md-3 mb-3">
        <label>Fecha Inicio</label>
        <input type="date" name="fecha_inicio" class="form-control" required>
    </div>
    <div class="col-md-3 mb-3">
        <label>Hora Ingreso</label>
        <input type="time" name="hora_ingreso" class="form-control" required>
    </div>
    <div class="col-md-3 mb-3">
        <label>Fecha Salida</label>
        <input type="date" name="fecha_salida" class="form-control" required>
    </div>
    <div class="col-md-3 mb-3">
        <label>Hora Salida</label>
        <input type="time" name="hora_salida" class="form-control" required>
    </div>
</div>

<!-- ================= VISITAS ================= -->
<div class="mb-3">
    <label>Autorizado Visitas</label>
    <select name="autorizado_visitas" class="form-select" required>
        <option value="">Seleccione</option>
        <option value="SI">SI</option>
        <option value="NO">NO</option>
    </select>
</div>

<!-- ================= ARCHIVOS ================= -->
<div class="mb-3">
    <label>Imagen (opcional)</label>
    <input type="file" name="imagen" class="form-control" accept="image/*">
</div>

<div class="mb-3">
    <label>URL externa (opcional)</label>
    <input type="url" name="url_externa" class="form-control" placeholder="https://">
</div>

<hr>

<!-- ================= ACOMPAÑANTES ================= -->
<h5>Acompañantes</h5>
<div id="acompanantes"></div>

<button type="button" class="btn btn-secondary btn-sm" onclick="agregarAcomp()">+ Agregar acompañante</button>

<hr>

<div class="text-end">
    <button class="btn btn-success">Registrar</button>
    <a href="propietario_dashboard.php" class="btn btn-secondary">Volver</a>
</div>

</form>
</div>
</div>
</div>

<script>
let i = 0;

/* 🔥 AUTOCOMPLETE ARRENDATARIO */
$("#nombre").autocomplete({
    minLength: 2,
    source: "buscar_arrendatarios.php",

    select: function (event, ui) {

        $("#rut").val(ui.item.rut);
        $("#direccion").val(ui.item.direccion);
        $("#celular").val(ui.item.celular);
        $("#email").val(ui.item.email);
        $("#patente_vehiculo").val(ui.item.patente_vehiculo);

        // LIMPIAR
        $("#acompanantes").html('');
        i = 0;

        // 🔥 CARGAR ACOMPAÑANTES AUTOMÁTICAMENTE
        $.ajax({
            url: "buscar_acompanantes.php",
            type: "GET",
            data: { id_arrendatario: ui.item.id },
            dataType: "json",

            success: function(data) {

                console.log("ACOMPAÑANTES:", data);

                if (!data || data.length === 0) return;

                data.forEach(function(acomp) {
                    agregarAcomp(acomp.nombre, acomp.rut);
                });
            }
        });
    }
});

/* 🔥 AGREGAR ACOMPAÑANTE */
function agregarAcomp(nombre = "", rut = "") {
    i++;

    let html = `
        <div class="row mt-2">
            <div class="col-md-6">
                <input class="form-control" 
                       name="acompanantes[${i}][nombre]" 
                       value="${nombre}" 
                       placeholder="Nombre">
            </div>
            <div class="col-md-6">
                <input class="form-control" 
                       name="acompanantes[${i}][rut]" 
                       value="${rut}" 
                       placeholder="RUT">
            </div>
        </div>
    `;

    $("#acompanantes").append(html);
}
</script>

</body>
</html>