{% extends "base_admin.html" %}

{% block title %}Manajemen Data Sales Forces- 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 Sales Force</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 Sales Force</label>
            <input type="text" class="form-control" placeholder="ID Sales Force..." name="sf_id" id="sf_id" required>
        </div>
        <div class="col-md-3">
            <label>Nama</label>
            <input type="text" class="form-control" placeholder="Nama Sales..." name="nama_sales" id="nama_sales" required>
        </div>
        <div class="col-md-3">
            <label>Team Leader</label>
            <select class="form-control" name="tl_id" id="tl_id" required>
                <option value="">Pilih Team Leader</option>
                {% for tl in tl_list %}
                    <option value="{{ tl.tl_id }}">{{ tl.nama_tl }}</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 Sales Force</h6>
            <a href="{% url 'download_sales_force' %}" class="btn btn-success mt-2 mt-md-0">Download Data Sales Force (XLSX)</a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="sales-force-table">
                    <thead class="thead-dark">
                        <tr>
                            <th>SF ID</th>
                            <th>Nama</th>
                            <th>Team Leader</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for sf in sf_list %}
                        <tr>
                            <td>{{ sf.sf_id }}</td>
                            <td>{{ sf.nama_sales }}</td>
                            <td>{{ sf.nama_tl }}</td>
                            <td>
                                <button class="btn btn-sm btn-warning" onclick="editForm('{{ sf.sf_id }}', '{{ sf.nama_sales }}', '{{ sf.tl_id }}')">Edit</button>
                                <button class="btn btn-sm btn-danger" onclick="confirmDelete('{{ sf.sf_id }}')">Delete</button>
                            </td>
                        </tr>
                        {% empty %}
                        <tr><td colspan="4" class="text-center text-muted">Tidak ada data</td></tr>
                        {% endfor %}
                    </tbody>
                </table>
                <!-- Pagination Controls -->
                <div id="salesForcePagination" 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(sf_id, nama_sales, tl_id) {
        document.getElementById("form_mode").value = "update";  // Change mode to update
        document.getElementById("sf_id").value = sf_id;  // Set SF ID for the form
        document.getElementById("nama_sales").value = nama_sales;  // Set Name
        document.getElementById("tl_id").value = tl_id;  // Set WOK ID
    }

    // Function to confirm deletion of a Team Leader
    function confirmDelete(sf_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 'managesf' %}";

                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 sfIdField = document.createElement('input');
                sfIdField.type = 'hidden';
                sfIdField.name = 'sf_id';
                sfIdField.value = sf_id;

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

                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("sales-force-table", "salesForcePagination", 10);
    // Tambahkan ini kalau kamu mau pagination lain:
    // applyPagination("namaTabelLain", "paginationLain", 5);
});
</script>



{% endblock %}
