@{
    ViewData["Title"] = "Regulasi";
}

@section Style {
<link rel="stylesheet" href="~/css/Regulasi.css" asp-append-version="true" />
}

@await Html.PartialAsync("Section/_Hero", "Regulasi")

<div class="container">

    <div class="text-center mb-3">
        <button class="btn filter-btn active" data-kategori="peraturan">Peraturan</button>
        <button class="btn filter-btn" data-kategori="sop">SOP</button>
    </div>

    <div class="row mb-3">
        <div class="col-md-6">
            <input type="text" id="search" class="form-control" placeholder="Cari..." />
        </div>

        <div class="col-md-6">
            <select id="tahun" class="form-control">
                <option value="">Semua Tahun</option>
                <option value="2025">2025</option>
                <option value="2026">2026</option>
            </select>
        </div>
    </div>

    <div id="list-regulasi"></div>

    <div class="d-flex justify-content-between align-items-center mt-4 flex-wrap gap-2">
        <div id="pagination-info" class="text-muted small"></div>
        <div id="pagination" class="d-flex"></div>
    </div>

</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {

        let allData = [];
        let filteredData = [];
        let currentKategori = "peraturan";
        let currentPage = 1;
        const perPage = 10;

        function formatTanggal(dateStr) {
            return new Date(dateStr).toLocaleDateString("id-ID", {
                day: "numeric",
                month: "long",
                year: "numeric"
            });
        }

        function loadRegulasi() {
            fetch('/Regulasi/GetRegulasi')
                .then(res => res.json())
                .then(data => {
                    allData = data;
                    filterData();
                });
        }

        function filterData() {
            const keyword = document.getElementById("search").value.toLowerCase();
            const tahun = document.getElementById("tahun").value;

            filteredData = allData.filter(item => {
                const kategori = (item.kategori || "").trim().toLowerCase();
                const judul = (item.judul || "").toLowerCase();

                return (
                    kategori === currentKategori &&
                    judul.includes(keyword) &&
                    (tahun === "" || item.tahun == tahun)
                );
            });

            currentPage = 1;
            renderPagination();
        }

        function renderPagination() {
            const start = (currentPage - 1) * perPage;
            const end = start + perPage;

            const paginatedData = filteredData.slice(start, end);

            renderData(paginatedData);
            renderPaginationControls();
            renderPaginationInfo(start, end);
        }

        function renderData(data) {
            let html = "";

            if (data.length === 0) {
                html = "<p class='text-center text-muted'>Data tidak ditemukan</p>";
            }

            data.forEach(item => {
                html += `
            <div class="card p-3 mb-3 d-flex flex-row justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <div class="me-3">
                        <i class="bi bi-file-earmark-pdf fs-2 text-primary"></i>
                    </div>
                    <div>
                        <h6 class="mb-1">${item.judul}</h6>
                        <small class="text-muted">
                            ${formatTanggal(item.tanggal)} | Diunduh ${item.download} kali
                        </small>
                    </div>
                </div>
                <div>
                    <a href="${item.file}" target="_blank" class="btn btn-light btn-sm me-2">
                        Lihat
                    </a>
                    <a href="${item.file}" download class="btn btn-primary btn-sm">
                        Unduh
                    </a>
                </div>
            </div>
            `;
            });

            document.getElementById("list-regulasi").innerHTML = html;
        }

        function renderPaginationControls() {

            const totalPages = Math.ceil(filteredData.length / perPage);

            let html = "";

            if (totalPages === 0) {
                document.getElementById("pagination").innerHTML = "";
                return;
            }

            html += `
            <button class="btn btn-sm btn-outline-primary me-1"
                ${currentPage === 1 ? "disabled" : ""}
                onclick="changePage(${currentPage - 1})">
                «
            </button>
        `;

            for (let i = 1; i <= totalPages; i++) {
                html += `
                <button
                    class="btn btn-sm ${i === currentPage ? "btn-primary" : "btn-outline-primary"} mx-1"
                    onclick="changePage(${i})">
                    ${i}
                </button>
            `;
            }

            html += `
            <button class="btn btn-sm btn-outline-primary ms-1"
                ${currentPage === totalPages ? "disabled" : ""}
                onclick="changePage(${currentPage + 1})">
                »
            </button>
        `;

            document.getElementById("pagination").innerHTML = html;
        }

        function renderPaginationInfo(start, end) {
            const total = filteredData.length;

            if (total === 0) {
                document.getElementById("pagination-info").innerHTML = "";
                return;
            }

            const from = start + 1;
            const to = Math.min(end, total);

            document.getElementById("pagination-info").innerHTML =
                `Show ${from}–${to} of ${total} data`;
        }

        window.changePage = function (page) {
            currentPage = page;
            renderPagination();
            window.scrollTo({ top: 300, behavior: "smooth" });
        };

        document.querySelectorAll(".filter-btn").forEach(btn => {
            btn.addEventListener("click", function () {
                document.querySelectorAll(".filter-btn").forEach(b => b.classList.remove("active"));
                this.classList.add("active");
                currentKategori = this.dataset.kategori;
                filterData();
            });
        });

        document.getElementById("search").addEventListener("keyup", filterData);
        document.getElementById("tahun").addEventListener("change", filterData);

        loadRegulasi();

    });
</script>