{% extends "base_admin.html" %}

{% block title %}Manajemen Team Leader - CWN{% endblock %}

{% block content %}
<div class="container-fluid mt-4">
    <h2 class="text-center text-white p-3 rounded mb-4 mt-2 custom-bg">Manage Team Leader</h2>

    {% if success %}
    <script>
        Swal.fire({
            icon: 'success',
            title: 'Berhasil',
            text: '{{ success }}',
        });
    </script>
    {% elif error %}
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: '{{ error }}',
        });
    </script>
    {% endif %}

    <form method="POST" class="row g-3">
        {% csrf_token %}
        <input type="hidden" id="form_mode" name="form_mode" value="create">
        <div class="col-md-3">
            <label>Kode Team Leader</label>
            <input type="text" class="form-control" placeholder="ID Team Leader..." name="tl_id" id="tl_id" required>
        </div>
        <div class="col-md-3">
            <label>Nama</label>
            <input type="text" class="form-control" placeholder="Nama Team Leader..." name="nama_tl" id="nama_tl" required>
        </div>
        <div class="col-md-3">
            <label>WOK</label>
            <select class="form-control" name="wok_id" id="wok_id" required>
                <option value="">Pilih WOK</option>
                {% for wok in wok_list %}
                    <option value="{{ wok.wok_id }}">{{ wok.nama_wok }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="col-md-3 mt-4">
            <button type="submit" class="btn btn-danger w-100">Simpan</button>
        </div>
    </form>

    <hr>

    <div class="card shadow mb-4">
        <div class="card-header py-3 custom-bg d-flex flex-column flex-md-row justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-white">Daftar Team Leader</h6>
            <a href="{% url 'download_team_leader' %}" class="btn btn-success mt-2 mt-md-0">Download Data Team Leader (XLSX)</a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="team-leader-table">
                    <thead class="thead-dark">
                        <tr>
                            <th>TL ID</th>
                            <th>Nama</th>
                            <th>WOK</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for tl in tl_list %}
                        <tr>
                            <td>{{ tl.tl_id }}</td>
                            <td>{{ tl.nama_tl }}</td>
                            <td>{{ tl.nama_wok }}</td>
                            <td>
                                <button class="btn btn-sm btn-warning" onclick="editForm('{{ tl.tl_id }}', '{{ tl.nama_tl }}', '{{ tl.wok_id }}')">Edit</button>
                                <button class="btn btn-sm btn-danger" onclick="confirmDelete('{{ tl.tl_id }}')">Delete</button>
                            </td>
                        </tr>
                        {% empty %}
                        <tr><td colspan="4" class="text-center text-muted">Tidak ada data</td></tr>
                        {% endfor %}
                    </tbody>
                </table>
                <!-- Pagination -->
                <div id="teamLeaderPagination" class="d-flex justify-content-center mt-3"></div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // Function to fill the form with data for editing
    function editForm(tl_id, nama_tl, wok_id) {
        document.getElementById("form_mode").value = "update";  // Change mode to update
        document.getElementById("tl_id").value = tl_id;  // Set TL ID for the form
        document.getElementById("nama_tl").value = nama_tl;  // Set Name
        document.getElementById("wok_id").value = wok_id;  // Set WOK ID
    }

    // Function to confirm deletion of a Team Leader
    function confirmDelete(tl_id) {
        Swal.fire({
            title: 'Apakah Anda yakin?',
            text: "Data ini akan dihapus secara permanen!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Ya, hapus!',
        }).then((result) => {
            if (result.isConfirmed) {
                // Create the form dynamically and submit it for deletion
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = "{% url 'managetl' %}";

                const csrfToken = document.createElement('input');
                csrfToken.type = 'hidden';
                csrfToken.name = 'csrfmiddlewaretoken';
                csrfToken.value = '{{ csrf_token }}';

                const formMode = document.createElement('input');
                formMode.type = 'hidden';
                formMode.name = 'form_mode';
                formMode.value = 'delete';

                const methodField = document.createElement('input');
                methodField.type = 'hidden';
                methodField.name = '_method';
                methodField.value = 'DELETE';

                const tlIdField = document.createElement('input');
                tlIdField.type = 'hidden';
                tlIdField.name = 'tl_id';
                tlIdField.value = tl_id;

                form.appendChild(csrfToken);
                form.appendChild(formMode);
                form.appendChild(methodField);
                form.appendChild(tlIdField);

                document.body.appendChild(form);
                form.submit();
            }
        });
    }
</script>
<script>
function applyPagination(tableId, paginationId, rowsPerPage = 5) {
    const table = document.getElementById(tableId);
    if (!table) return;

    const tbody = table.querySelector("tbody");
    const rows = Array.from(tbody.querySelectorAll("tr"));
    const totalRows = rows.length;
    const totalPages = Math.ceil(totalRows / rowsPerPage);
    const pagination = document.getElementById(paginationId);
    let currentPage = 1;

    function showPage(page) {
        currentPage = page;
        rows.forEach((row, index) => {
            row.style.display = (index >= (page - 1) * rowsPerPage && index < page * rowsPerPage) ? "" : "none";
        });
        renderPagination();
    }

    function renderPagination() {
        pagination.innerHTML = "";

        const createBtn = (label, disabled, onClick, icon = false) => {
            const btn = document.createElement("button");
            btn.innerHTML = icon ? `&${label};` : label;
            btn.className = `btn btn-sm mx-1 ${disabled ? 'btn-secondary' : 'btn-outline-primary'}`;
            btn.disabled = disabled;
            btn.onclick = onClick;
            return btn;
        };

        // pagination.appendChild(createBtn('laquo', currentPage === 1, () => showPage(1), true));
        pagination.appendChild(createBtn('laquo', currentPage === 1, () => showPage(currentPage - 1), true)); // « Prev

        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }

        for (let i = startPage; i <= endPage; i++) {
            const btn = document.createElement("button");
            btn.textContent = i;
            btn.className = `btn btn-sm mx-1 ${i === currentPage ? 'btn-primary' : 'btn-outline-primary'}`;
            btn.onclick = () => showPage(i);
            pagination.appendChild(btn);
        }

        pagination.appendChild(createBtn('raquo', currentPage === totalPages, () => showPage(currentPage + 1), true)); // Next »
        // pagination.appendChild(createBtn('raquo', currentPage === totalPages, () => showPage(totalPages), true));
    }

    if (rows.length > rowsPerPage) {
        showPage(1);
    }
}

document.addEventListener("DOMContentLoaded", () => {
    applyPagination("team-leader-table", "teamLeaderPagination", 10);
    // Tambahkan ini kalau kamu mau pagination lain:
    // applyPagination("namaTabelLain", "paginationLain", 5);
});
</script>

{% endblock %}
