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

<div class="container mt-4">

    <div class="card shadow-sm p-4">

        <h5>Add Tenants to Unit {{ unit.unit_number }}</h5>

        <!-- UNIT STATUS -->
        <p class="text-muted">
            Occupancy: {{ unit.current_occupancy }} / {{ unit.max_occupants }} |
            Status: <strong>{{ unit.occupancy_status }}</strong>
        </p>

        {% if unit.is_full %}
            <div class="alert alert-warning">
                This unit is already full. No more tenants can be added.
            </div>
        {% endif %}

        <input type="text" id="searchInput" class="form-control mb-3"
               placeholder="Search tenants...">

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

            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Select</th>
                        <th>Name</th>
                        <th>Current Unit</th>
                        <th>Status</th>
                    </tr>
                </thead>

                <tbody id="tenantTable">

                {% for item in tenant_data %}
                <tr>

                    <td>
                        {% if item.is_ready and not unit.is_full %}
                            <input type="checkbox" name="tenants" value="{{ item.user.id }}">
                        {% else %}
                            <input type="checkbox" disabled>
                        {% endif %}
                    </td>

                    <td>{{ item.user.get_full_name }}</td>

                    <td>
                        {% if item.profile and item.profile.unit %}
                            {{ item.profile.unit }}
                        {% else %}
                            None
                        {% endif %}
                    </td>

                    <td>
                        {% if not item.is_ready %}
                            <span class="badge bg-warning">Not Onboarded</span>
                        {% elif item.profile and item.profile.unit %}
                            <span class="badge bg-info">Already Assigned</span>
                        {% else %}
                            <span class="badge bg-success">Ready</span>
                        {% endif %}
                    </td>

                </tr>
                {% endfor %}

                </tbody>
            </table>

            <button class="btn btn-dark w-100" {% if unit.is_full %}disabled{% endif %}>
                Assign Selected Tenants
            </button>

        </form>

    </div>

</div>

<script>
document.getElementById("searchInput").addEventListener("keyup", function () {
    let value = this.value.toLowerCase();
    let rows = document.querySelectorAll("#tenantTable tr");

    rows.forEach(row => {
        row.style.display = row.innerText.toLowerCase().includes(value) ? "" : "none";
    });
});
</script>

{% endblock %}