@{
    ViewData["Title"] = "Detail Layanan";
}


<style>
    .service-btn.active {
        background-color: #0d6efd;
        color: white;
    }
</style>

<div class="container mt-5">

    <div class="service-card mb-5">
        <div class="row align-items-center g-4">

            <div class="col-md-7">
                <h3 id="judul"></h3>
                <p id="deskripsi-singkat"></p>
                <ul id="deskripsi"></ul>
            </div>

            <div class="col-md-5 text-center">
                <img id="gambar" />
            </div>

        </div>
    </div>

    <div class="table-card mb-4">
        <div class="table-header">
            <h5>Info Harga Baku Mutu Air</h5>
            <div>
                <button onclick="exportTableToExcel('table1')" class="btn-export">
                    Download Excel
                </button>

                <input type="text" id="searchTable-harga" placeholder="Cari...">
            </div>
        </div>

        <div class="table-responsive">
            <table class="table custom-table" id="table1">
                <thead></thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <div id="pagination" class="pagination-wrapper"></div>


    <div class="table-card">
        <div class="table-header">
            <h5>Info Harga Per Parameter Air</h5>
            <div>
                <button onclick="exportTableToExcel('table2')" class="btn-export">
                    Download Excel
                </button>

                <input type="text" id="searchTable-harga" placeholder="Cari...">
            </div>
        </div>

        <div class="table-responsive">
            <table class="table custom-table" id="table2">
                <thead></thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <div id="pagination" class="pagination-wrapper"></div>

</div>


<script>

    let currentPage = {};
    const rowsPerPage = 5;

    function getQueryParam(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    function changeService(btn, jenis) {
        window.history.pushState({}, "", `/Layanan?jenis=${jenis}`);

        document.querySelectorAll('.service-btn').forEach(b => b.classList.remove('active'));
        if (btn) btn.classList.add('active');

        loadData(jenis);
    }

    function loadData(jenis) {

        if (!jenis) jenis = "air";

        document.getElementById("judul").innerText = "Loading...";

        fetch(`/Layanan/GetData?jenis=${encodeURIComponent(jenis)}`)
            .then(res => res.json())
            .then(data => {

                document.getElementById("judul").innerText = data.judul || "-";
                document.getElementById("gambar").src = data.gambar || "";
                document.getElementById("deskripsi-singkat").innerText = data["deskripsi-singkat"] || "";

                let desc = "";
                (data.deskripsi || []).forEach(d => {
                    desc += `<li>${d}</li>`;
                });

                document.getElementById("deskripsi").innerHTML = desc;

                renderTable("table1", data.table1);
                renderTable("table2", data.table2);

                setupPagination("table1");
                setupPagination("table2");

            })
            .catch(() => {
                document.getElementById("judul").innerText = "Data tidak ditemukan";
            });
    }

    document.addEventListener("DOMContentLoaded", function () {

        let jenis = getQueryParam("jenis") || "air";

        loadData(jenis);

        document.querySelectorAll('.service-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.jenis === jenis);
        });

        setupSearch("searchTable-harga", "table1");
        setupSearch("searchTable-parameter", "table2");
    });

    function renderTable(tableId, tableData) {

        if (!tableData) return;

        let thead = "<tr>";
        (tableData.columns || []).forEach(col => {
            thead += `<th>${col}</th>`;
        });
        thead += "</tr>";

        document.querySelector(`#${tableId} thead`).innerHTML = thead;

        let tbody = "";

        (tableData.data || []).forEach(row => {
            tbody += "<tr>";

            (tableData.fields || []).forEach(field => {
                let value = row[field] ?? "-";

                if (typeof value === "number" && field.toLowerCase().includes("harga")) {
                    value = "Rp " + value.toLocaleString();
                }

                if (field === "aksi") {
                    value = `
                        <a href="/DetailItem?kode=${row.kode}"
                           class="btn btn-sm btn-primary rounded-pill">
                           Detail
                        </a>
                    `;
                }

                tbody += `<td>${value}</td>`;
            });

            tbody += "</tr>";
        });

        document.querySelector(`#${tableId} tbody`).innerHTML = tbody;
    }

    function setupPagination(tableId) {

        const rows = Array.from(document.querySelectorAll(`#${tableId} tbody tr`))
            .filter(row => row.style.display !== "none");

        let container = document.getElementById(`pagination-${tableId}`);

        if (!container) {
            container = document.createElement("div");
            container.id = `pagination-${tableId}`;
            container.className = "pagination-wrapper";

            document.querySelector(`#${tableId}`).parentElement.appendChild(container);
        }

        const totalRows = rows.length;
        const totalPages = Math.ceil(totalRows / rowsPerPage) || 1;

        let page = 1;

        function showPage(p) {
            page = p;

            rows.forEach((row, i) => {
                row.style.display =
                    i >= (p - 1) * rowsPerPage &&
                        i < p * rowsPerPage
                        ? ""
                        : "none";
            });

            render();
        }

        function render() {
            container.innerHTML = "";

            const start = (page - 1) * rowsPerPage + 1;
            const end = Math.min(page * rowsPerPage, totalRows);

            const info = document.createElement("div");
            info.className = "pagination-info";
            info.innerText = `Showing ${start}–${end} of ${totalRows}`;

            const controls = document.createElement("div");
            controls.className = "pagination-controls";

            const prev = document.createElement("button");
            prev.innerText = "‹";
            prev.className = "page-btn" + (page === 1 ? " disabled" : "");
            prev.onclick = () => showPage(page - 1);
            controls.appendChild(prev);

            let pages = [];

            if (totalPages <= 5) {
                pages = [...Array(totalPages).keys()].map(i => i + 1);
            } else {
                pages = [1];

                if (page > 3) pages.push("...");

                for (let i = Math.max(2, page - 1); i <= Math.min(totalPages - 1, page + 1); i++) {
                    pages.push(i);
                }

                if (page < totalPages - 2) pages.push("...");

                pages.push(totalPages);
            }

            pages.forEach(p => {
                const btn = document.createElement("button");

                if (p === "...") {
                    btn.innerText = "...";
                    btn.className = "page-btn disabled";
                } else {
                    btn.innerText = p;
                    btn.className = "page-btn" + (p === page ? " active" : "");
                    btn.onclick = () => showPage(p);
                }

                controls.appendChild(btn);
            });

            const next = document.createElement("button");
            next.innerText = "›";
            next.className = "page-btn" + (page === totalPages ? " disabled" : "");
            next.onclick = () => showPage(page + 1);
            controls.appendChild(next);

            container.appendChild(info);
            container.appendChild(controls);
        }

        showPage(1);
    }

    function setupSearch(inputId, tableId) {

        const input = document.getElementById(inputId);

        input.addEventListener("keyup", function () {
            const keyword = input.value.toLowerCase();
            const rows = document.querySelectorAll(`#${tableId} tbody tr`);

            rows.forEach(row => {
                const text = row.innerText.toLowerCase();
                row.style.display = text.includes(keyword) ? "" : "none";
            });

            setupPagination(tableId);
        });
    }

    function exportTableToExcel(tableId) {

        const table = document.getElementById(tableId);

        if (!table || typeof XLSX === "undefined") {
            alert("Export gagal");
            return;
        }

        let jenis = getQueryParam("jenis") || "data";
        const tahun = new Date().getFullYear();

        jenis = jenis.toLowerCase().replace(/\s+/g, "-");

        const fileName = `${jenis}-${tableId}-${tahun}.xlsx`;

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.table_to_sheet(table);

        XLSX.utils.book_append_sheet(wb, ws, "Data");

        XLSX.writeFile(wb, fileName);
    }

</script>

