$(document).ready(function () {

    $("body").on("change", "#origin", getMainData);

    getMainData();

    let savedPage = 1; // keep track globally

    function getMainData() {
        var origin = $(".origin").val();

        if (origin != "") {
            $.post("get_shipmentstatus.php", { origin: origin }, function (data) {
                if (data != "") {
                    $(".dataDiv").html(data);

                    // reinitialize pagination but restore page safely
                    setTimeout(() => {
                        initPagination(savedPage);
                    }, 50);
                }
            });
        } else {
            $(".dataDiv").html("");
        }
    }



    function initPagination(page = 1) {
        const searchInput = document.getElementById("searchInput");
        const shipmentItems = document.querySelectorAll(".shipment-item");
        const prevBtn = document.getElementById("prevBtn");
        const nextBtn = document.getElementById("nextBtn");

        if (!shipmentItems.length) return;

        // clone buttons to remove old event listeners
        const newPrevBtn = prevBtn.cloneNode(true);
        prevBtn.parentNode.replaceChild(newPrevBtn, prevBtn);

        const newNextBtn = nextBtn.cloneNode(true);
        nextBtn.parentNode.replaceChild(newNextBtn, nextBtn);

        const newSearchInput = searchInput.cloneNode(true);
        searchInput.parentNode.replaceChild(newSearchInput, searchInput);

        let currentPage = page;
        const itemsPerPage = 3;
        let lastSearch = "";

        function getFilteredItems() {
            let filter = newSearchInput.value.toLowerCase().trim();
            return [...shipmentItems].filter(item =>
                item.innerText.toLowerCase().includes(filter)
            );
        }

        function renderPage() {
            const filteredItems = getFilteredItems();
            const totalPages = Math.max(1, Math.ceil(filteredItems.length / itemsPerPage));

            if (currentPage > totalPages) currentPage = totalPages;

            shipmentItems.forEach(item => {
                item.style.display = "none";
                item.classList.remove("show");
            });

            filteredItems.forEach((item, index) => {
                if (index >= (currentPage - 1) * itemsPerPage &&
                    index < currentPage * itemsPerPage) {
                    item.style.display = "";
                    setTimeout(() => item.classList.add("show"), 30);
                }
            });

            newPrevBtn.disabled = (currentPage <= 1);
            newNextBtn.disabled = (currentPage >= totalPages);

            savedPage = currentPage;
            console.log(`Current: ${currentPage}, TotalPages: ${totalPages}`);
        }

        newPrevBtn.addEventListener("click", () => {
            if (currentPage > 1) {
                currentPage--;
                renderPage();
            }
        });

        newNextBtn.addEventListener("click", () => {
            const filteredItems = getFilteredItems();
            const totalPages = Math.ceil(filteredItems.length / itemsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                renderPage();
            }
        });

        newSearchInput.addEventListener("input", function () {
            let currentSearch = this.value.toLowerCase().trim();
            if (currentSearch !== lastSearch) {
                currentPage = 1;
                lastSearch = currentSearch;
            }
            renderPage();
        });

        renderPage();
    }



});
