{% extends "base.html" %}
{% block content %}

<div class="container mt-4">

    <div class="card shadow-sm p-4">
        <h5 class="mb-3">Assign {{ tenant.get_full_name }} to Unit</h5>

        <form method="POST">
            {% csrf_token %}

            <div class="mb-3">
                <label class="form-label">Select Building</label>
                <select id="buildingSelect" class="form-select">
                    <option value="">Choose Building</option>
                    {% for b in buildings %}
                        <option value="{{ b.id }}">{{ b.name }}</option>
                    {% endfor %}
                </select>
            </div>

            <div class="mb-3">
                <label class="form-label">Select Unit</label>
                <select name="unit" id="unitSelect" class="form-select" required>
                    <option value="">Select Unit</option>
                    {% for u in units %}
                        <option value="{{ u.id }}" data-building="{{ u.building.id }}">
                            {{ u.building.name }} - {{ u.unit_number }}
                            ({{ u.current_occupancy }}/{{ u.max_occupants }})
                        </option>
                    {% endfor %}
                </select>
            </div>

            <button class="btn btn-dark w-100">
                Continue to Inspection
            </button>

        </form>
    </div>

</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const buildingSelect = document.getElementById("buildingSelect");
    const unitSelect = document.getElementById("unitSelect");

    buildingSelect.addEventListener("change", function () {
        let buildingId = this.value;
        let units = unitSelect.querySelectorAll("option");

        units.forEach(option => {
            if (!option.value) return;

            if (option.dataset.building === buildingId || buildingId === "") {
                option.style.display = "";
            } else {
                option.style.display = "none";
            }
        });

        unitSelect.value = "";
    });
});
</script>

{% endblock %}