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

    const form = document.getElementById("search-form");
    const tableBody = document.querySelector("#result-table tbody");

    function fetchData(page = 1) {
        const formData = new FormData(form);
        formData.append("page", page);

        fetch("/search_contractor", {
            method: "POST",
            body: formData
        })
            .then(res => res.json())
            .then(res => {
                tableBody.innerHTML = "";

                res.data.forEach(row => {

                    const tr = document.createElement("tr");

                    tr.innerHTML = `
                    <td class="contractor-link" data-id="${row.Contractor_Id}">
                        ${row.Contractor_Name}
                    </td>
                    <td class="pmc-link" data-pmc="${row.PMC_No}">
                        ${row.PMC_No}
                    </td>
                    <td>${row.State_Name}</td>
                    <td>${row.District_Name}</td>
                    <td>${row.Block_Name}</td>
                    <td>${row.Village_Name}</td>
                `;

                    tableBody.appendChild(tr);
                });
            });
    }

    // Auto search
    form.addEventListener("input", () => fetchData());

    // Click Contractor
    document.addEventListener("click", function (e) {
        if (e.target.classList.contains("contractor-link")) {
            const id = e.target.dataset.id;
            window.location.href = `/contractor_report/${id}`;
        }

        if (e.target.classList.contains("pmc-link")) {
            const pmc = e.target.dataset.pmc;
            window.location.href = `/pmc_report/${pmc}`;
        }
    });

    fetchData();
});