{% extends "base_admin.html" %}

{% block title %}Manajemen Data Paket Internet - 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 Paket Internet</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">
        <input type="hidden" id="paket_id" name="paket_id">

        <div class="col-md-3">
            <label>Nama Paket</label>
            <input type="text" placeholder="Nama paket..." class="form-control" name="nama_paket" id="nama_paket" required>
        </div>
        <div class="col-md-2">
            <label>Branch</label>
            <select class="form-control" name="branch_id" id="branch_id" required>
                <option value="">Pilih Branch</option>
                {% for branch in branch_list %}
                    <option value="{{ branch.branch_id }}">{{ branch.nama_branch }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="col-md-2">
            <label>Harga / ARPU</label>
            <input type="number" placeholder="Harga/ARPU..." class="form-control" name="arpu" id="arpu" required>
        </div>
        <div class="col-md-2">
            <label>Fee Management</label>
            <input type="number" placeholder="Masukkan Fee..." class="form-control" name="fee" id="fee" required>
        </div>
        <div class="col-md-3" style="margin-top: 30px;">
            <button type="submit" class="btn btn-danger w-100">Simpan</button>
        </div> 
    </form>

    <hr>

    <div class="card shadow mb-4 mt-4">
        <div class="card-header py-3 custom-bg d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-white">Daftar Paket Internet</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover mt-2" id="paket-table">
                    <thead class="thead-dark">
                        <tr>
                            <th>Nama Paket</th>
                            <th>Branch</th>
                            <th>Harga/ARPU</th>
                            <th>Fee Management</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for paket in paket_list %}
                        <tr>
                            <td>{{ paket.nama_paket }}</td>
                            <td>{{ paket.nama_branch }}</td>
                            <td>{{ paket.arpu }}</td>
                            <td>{{ paket.fee }}</td>
                            <td>
                                <button class="btn btn-sm btn-warning"
                                    onclick="editForm('{{ paket.paket_id }}', '{{ paket.nama_paket }}', '{{ paket.branch_id }}', '{{ paket.arpu }}', '{{ paket.fee }}')">Edit</button>
                                <button class="btn btn-sm btn-danger" onclick="confirmDelete('{{ paket.paket_id }}')">Delete</button>
                            </td>
                        </tr>
                        {% empty %}
                        <tr><td colspan="5" class="text-center text-muted">Tidak ada data</td></tr>
                        {% endfor %}
                    </tbody>
                </table>
                <!-- Pagination Controls -->
                <div id="paketPagination" 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 editForm(paket_id, nama_paket, branch_id, arpu, fee) {
        document.getElementById("form_mode").value = "update";
        document.getElementById("paket_id").value = paket_id;
        document.getElementById("nama_paket").value = nama_paket;
        document.getElementById("branch_id").value = branch_id;
        document.getElementById("arpu").value = arpu;
        document.getElementById("fee").value = fee;
    }

    function confirmDelete(paket_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) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = "{% url 'managepaket' %}";

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

                form.appendChild(csrfToken);
                form.appendChild(formMode);
                form.appendChild(idField);

                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("paket-table", "paketPagination", 10);
    // Tambahkan ini kalau kamu mau pagination lain:
    // applyPagination("namaTabelLain", "paginationLain", 5);
});
</script>
{% endblock %}
