{% extends "base_admin.html" %}
{% block title %}Data PS - CWN{% endblock %}
{% block content %}
{% load humanize %}
<style>
    .table {
        table-layout: collapse;
        width: 100%;
    }
    .table-responsive {
        overflow-x: auto;
    }
</style>

<main class="content" id="main-content">  
<div class="container-fluid my-4" style="max-width: 1300px; margin-left: auto; margin-right: auto;">
    <h1 class="text-center text-white p-3 rounded mb-4 mt-2 custom-bg">Data Digital Channel</h1>

    <!-- Form Filter -->
    <form method="GET" class="row g-3" id="filterForm">

        <!-- Area -->
        <div class="col-md-4">
            <label for="filterArea" class="form-label">Area</label>
            <select id="filterArea" name="area" class="form-control">
                <option value="" {% if not selected_area %}selected{% endif %}>Pilih Wilayah</option>
                <option value="1" {% if selected_area == '1' %}selected{% endif %}>AREA 1</option>
                <option value="2" {% if selected_area == '2' %}selected{% endif %}>AREA 2</option>
                <option value="3" {% if selected_area == '3' %}selected{% endif %}>AREA 3</option>
                <option value="4" {% if selected_area == '4' %}selected{% endif %}>AREA 4</option>
            </select>
        </div>

        <!-- Nama Agent (sebelumnya Team Leader) -->
        <div class="col-md-4"> 
            <label for="filterAgentName" class="form-label">Nama Agent</label>
            <select id="filterAgentName" name="agent" class="form-control">
                <option value="">-- Pilih Nama Agent --</option>
                {% for emp in agent_list %}
                    <option value="{{ emp }}" {% if request.GET.agent == emp %}selected{% endif %}>{{ emp }}</option>
                {% endfor %}
            </select>
        </div>

        <!-- Branch -->
        <div class="col-md-4">
            <label for="filterBranch" class="form-label">Branch</label>
            <input type="text" id="filterBranch" name="branch" class="form-control" value="{{ selected_branch|default:'' }}" placeholder="Masukkan nama branch">
        </div>

        <!-- Status Order -->
        <div class="col-md-4">
            <label for="filterStatusOrder" class="form-label">Status Order</label>
            <input type="text" id="filterStatusOrder" name="status_order" class="form-control" value="{{ selected_status_order|default:'' }}" placeholder="Masukkan status order">
        </div>

        <!-- Bulan -->
        <div class="col-md-4">
            <label for="filterMonth" class="form-label">Bulan (MM)</label>
            <select id="filterMonth" name="bulan" class="form-control">
                <option value="" {% if not selected_bulan %}selected{% endif %}>-- Pilih Bulan --</option>
                <option value="01" {% if selected_bulan == '01' %}selected{% endif %}>Januari</option>
                <option value="02" {% if selected_bulan == '02' %}selected{% endif %}>Februari</option>
                <option value="03" {% if selected_bulan == '03' %}selected{% endif %}>Maret</option>
                <option value="04" {% if selected_bulan == '04' %}selected{% endif %}>April</option>
                <option value="05" {% if selected_bulan == '05' %}selected{% endif %}>Mei</option>
                <option value="06" {% if selected_bulan == '06' %}selected{% endif %}>Juni</option>
                <option value="07" {% if selected_bulan == '07' %}selected{% endif %}>Juli</option>
                <option value="08" {% if selected_bulan == '08' %}selected{% endif %}>Agustus</option>
                <option value="09" {% if selected_bulan == '09' %}selected{% endif %}>September</option>
                <option value="10" {% if selected_bulan == '10' %}selected{% endif %}>Oktober</option>
                <option value="11" {% if selected_bulan == '11' %}selected{% endif %}>November</option>
                <option value="12" {% if selected_bulan == '12' %}selected{% endif %}>Desember</option>
            </select>
        </div>

        <!-- Status Case -->
        <div class="col-md-4">
            <label for="filterStatusCase" class="form-label">Status Case</label>
            <select id="filterStatusCase" name="status_case" class="form-control">
                <option value="" {% if not selected_status_case %}selected{% endif %}>-- Pilih Status --</option>
                <option value="Open" {% if selected_status_case == 'Open' %}selected{% endif %}>Open</option>
                <option value="Close" {% if selected_status_case == 'Close' %}selected{% endif %}>Close</option>
            </select>
        </div>

    </form>

   <!-- Cards Row -->
    <div class="row mt-3">
        <!-- Penjualan Per Status Order -->
        <div class="col-md-3 col-lg-3 mb-4 d-flex">
            <div class="card shadow w-100">
                <div class="card-header py-3 custom-bg text-white">
                    <h5 class="m-0 font-weight-bold">Penjualan</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive d-flex">
                        <table class="table table-bordered table-hover" id="statusOrderTotal" style="table-layout: fixed;">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Status Order</th>
                                    <th>Total Penjualan</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for data in status_sold %}
                                <tr>
                                    <td>{{ data.0 }}</td>
                                    <td>{{ data.1 }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <div id="statusOrderPagination" class="mt-3 text-center"></div>
                </div>
            </div>
        </div>

        <!-- Penjualan Per Area (1) -->
        <div class="col-md-3 col-lg-3 mb-4 d-flex">
            <div class="card shadow w-100">
                <div class="card-header py-3 custom-bg text-white">
                    <h5 class="m-0 font-weight-bold">Penjualan Per Area</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive d-flex">
                        <table class="table table-bordered table-hover" id="areaTotal">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Area</th>
                                    <th>Total Penjualan</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for data in area_sales %}
                                <tr>
                                    <td>{{ data.0 }}</td>
                                    <td>{{ data.1 }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <div id="areaPagination" class="mt-3 text-center"></div>
                </div>
            </div>
        </div>

        <!-- Penjualan Agen -->
        <div class="col-md-3 col-lg-3 mb-4 d-flex">
            <div class="card shadow w-100">
                <div class="card-header py-3 custom-bg text-white">
                    <h5 class="m-0 font-weight-bold">Penjualan Agen</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive d-flex">
                        <table class="table table-bordered table-hover" id="agenTotal">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Nama Agen</th>
                                    <th>Total Penjualan</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for data in agen_sales %}
                                <tr {% if forloop.counter > 9 %} class="extra-sales-row d-none" {% endif %}>
                                    <td>{{ data.0 }}</td>
                                    <td>{{ data.1 }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <div id="agenPagination" class="mt-3 text-center"></div>
                </div>
            </div>
        </div>

        <!-- Paket Terjual -->
        <div class="col-md-3 col-lg-3 mb-4 d-flex">
            <div class="card shadow w-100">
                <div class="card-header py-3 custom-bg text-white">
                    <h5 class="m-0 font-weight-bold">Paket Terjual</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive d-flex">
                        <table class="table table-bordered table-hover" id="paketTerjualTotal" style="table-layout: fixed;">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Paket</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for data in paket_terjual %}
                                <tr {% if forloop.counter > 9 %} class="extra-paket-row d-none" {% endif %}>
                                    <td>{{ data.0 }}</td>
                                    <td>{{ data.1 }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <div id="paketPagination" class="mt-3 text-center"></div>
                </div>
            </div>
        </div>
    </div>


    <!-- Record Penjualan COMPLETE -->
    <div class="card mb-3 shadow">
        <div class="card-header custom-bg text-white">
            <h5 class="card-title mb-0">Record Penjualan Closed</h5>
        </div>
        <div class="card-body">
            <input type="search" class="form-control mb-2" id="searchComplete" placeholder="Cari Track Order...">
            
            <div id="completeWrapper" class="table-responsive d-flex" style="max-height: 480px;">
                <table class="table table-bordered table-hover" id="completeTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>No</th>
                            <th>Bulan</th>
                            <th>Nama Sales</th>
                            <th>Nama Agent</th>
                            <th>Track Order</th>
                            <th>Channel</th>
                            <th>No Kontak Pelanggan</th>
                            <th>Status Order</th>
                            <th>Branch</th>
                            <th>Area</th>
                            <th>Status Case</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for item in data_ps_completed %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ item.tanggal_created_at|date:"F Y" }}</td>  <!-- Format Bulan -->
                            <td>{{ item.nama_sales }}</td>
                            <td>{{ item.nama_agent }}</td>
                            <td>{{ item.track_id }}</td>
                            <td>{{ item.channel }}</td>
                            <td>{{ item.kontak_pelanggan }}</td>
                            <td>{{ item.status_order }}</td>
                            <td>{{ item.nama_branch }}</td>
                            <td>{{ item.nama_area }}</td>
                            <td>{{ item.status_case }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

            <div id="completePagination" class="mt-3 text-center"></div>
        </div>
    </div>

    <!-- Record Penjualan Non Complete -->
    <div class="card mb-3 shadow">
        <div class="card-header custom-bg text-white">
            <h5 class="card-title mb-0">Record Penjualan OPEN</h5>
        </div>
        <div class="card-body">
            <input type="search" class="form-control mb-2" id="searchKendala" placeholder="Cari Track Order...">
            <div class="table-responsive d-flex" style="max-height: 480px;">
                <table class="table table-bordered table-hover" id="kendalaTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>No</th>
                            <th>Tanggal</th>
                            <th>Nama Sales</th>
                            <th>Nama Agent</th>
                            <th>Track Order</th>
                            <th>Channel</th>
                            <th>No Kontak</th>
                            <th>Status Order</th>
                            <th>Branch</th>
                            <th>Area</th>
                            <th>Status Case</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for item in data_ps_not_completed %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ item.tanggal_created_at|date:"d M Y" }}</td>
                            <td>{{ item.nama_sales }}</td>
                            <td>{{ item.nama_agent }}</td>
                            <td>{{ item.track_id }}</td>
                            <td>{{ item.channel }}</td>
                            <td>{{ item.kontak_pelanggan }}</td>
                            <td>{{ item.status_order }}</td>
                            <td>{{ item.nama_branch }}</td>
                            <td>{{ item.nama_area }}</td>
                            <td>{{ item.status_case }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            <div id="kendalaPagination" class="mt-3 text-center"></div>
        </div>
    </div>


    
</div>
</main>

<script>
    // Submit form on change for selects and inputs except search
    document.querySelectorAll('#filterForm select, #filterForm input:not([type="search"])').forEach(el => {
        el.addEventListener('change', () => {
            document.getElementById('filterForm').submit();
        });
    });

    // Filter table rows by Track ID input for COMPLETE
    document.getElementById('searchComplete').addEventListener('input', function() {
        const filter = this.value.toLowerCase();
        const rows = document.querySelectorAll('#completeTable tbody tr');
        rows.forEach(row => {
            const track_id = row.cells[4].textContent.toLowerCase();
            row.style.display = track_id.includes(filter) ? '' : 'none';
        });
    });

    // Filter table rows by Track ID input for KENDALA
    document.getElementById('searchKendala').addEventListener('input', function() {
        const filter = this.value.toLowerCase();
        const rows = document.querySelectorAll('#kendalaTable tbody tr');
        rows.forEach(row => {
            const track_id = row.cells[4].textContent.toLowerCase();
            row.style.display = track_id.includes(filter) ? '' : 'none';
        });
    });

    // pagination
    function applyPagination(tableId, paginationId, rowsPerPage = 10) {
        const table = document.getElementById(tableId);
        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 = "";

            // Previous button
            const prevBtn = document.createElement("button");
            prevBtn.textContent = "Prev";
            prevBtn.className = "btn btn-sm btn-outline-primary mx-1";
            prevBtn.disabled = currentPage === 1;
            prevBtn.addEventListener("click", () => showPage(currentPage - 1));
            pagination.appendChild(prevBtn);

            // Page buttons (max 5 at a time)
            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.addEventListener("click", () => showPage(i));
                pagination.appendChild(btn);
            }

            // Next button
            const nextBtn = document.createElement("button");
            nextBtn.textContent = "Next";
            nextBtn.className = "btn btn-sm btn-outline-primary mx-1";
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.addEventListener("click", () => showPage(currentPage + 1));
            pagination.appendChild(nextBtn);
        }

        if (totalRows > rowsPerPage) {
            showPage(1);
        }
    }

    // Terapkan untuk dua tabel
    document.addEventListener("DOMContentLoaded", function () {
        // applyPagination("completeTable", "completePagination");
        // applyPagination("kendalaTable", "kendalaPagination");
        // applyPagination("orderTotal", "orderPagination", 5);
        applyPagination("statusOrderTotal", "statusOrderPagination", 5);
        applyPagination("agenTotal", "agenPagination", 5);
        applyPagination("areaTotal", "areaPagination");
        applyPagination("paketTerjualTotal", "paketPagination", 5);
    });

    function setupSearchWithPagination(tableId, searchInputId, paginationId, columnIndex = 4, rowsPerPage = 10) {
        const table = document.getElementById(tableId);
        const tbody = table.querySelector("tbody");
        const searchInput = document.getElementById(searchInputId);
        const pagination = document.getElementById(paginationId);
        const allRows = Array.from(tbody.querySelectorAll("tr"));
        let filteredRows = [...allRows];
        let currentPage = 1;

        function showPage(page) {
            currentPage = page;
            const totalRows = filteredRows.length;
            const totalPages = Math.ceil(totalRows / rowsPerPage);
            const start = (page - 1) * rowsPerPage;
            const end = start + rowsPerPage;

            allRows.forEach(row => row.style.display = "none");
            filteredRows.slice(start, end).forEach(row => row.style.display = "");

            renderPagination(totalPages);
        }

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

            const prevBtn = document.createElement("button");
            prevBtn.textContent = "Prev";
            prevBtn.className = "btn btn-sm btn-outline-primary mx-1";
            prevBtn.disabled = currentPage === 1;
            prevBtn.onclick = () => showPage(currentPage - 1);
            pagination.appendChild(prevBtn);

            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);
            }

            const nextBtn = document.createElement("button");
            nextBtn.textContent = "Next";
            nextBtn.className = "btn btn-sm btn-outline-primary mx-1";
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.onclick = () => showPage(currentPage + 1);
            pagination.appendChild(nextBtn);
        }

        function filterRows() {
            const filter = searchInput.value.toLowerCase();
            filteredRows = allRows.filter(row => {
                const cellText = row.cells[columnIndex]?.textContent.toLowerCase() || "";
                return cellText.includes(filter);
            });
            currentPage = 1;
            showPage(currentPage);
        }

        searchInput.addEventListener("input", filterRows);

        // Inisialisasi awal
        filterRows();
    }

    // Panggil untuk masing-masing tabel
    document.addEventListener("DOMContentLoaded", () => {
        setupSearchWithPagination("completeTable", "searchComplete", "completePagination");
        setupSearchWithPagination("kendalaTable", "searchKendala", "kendalaPagination");
    });

</script>
{% endblock %}
