document.addEventListener("DOMContentLoaded", function () {
    loadDataPhVillage();
});

let gridInstance;
function loadDataPhVillage() {
    const tableContainerPhVillage = document.getElementById("table-ph-village");

    if (tableContainerPhVillage) {
        tableContainerPhVillage.innerHTML = "";
    }

    $.ajax({
        url: `/parameter-ph-desa/getDataPhVillage`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const TableDataPhVillage = data["allVillage"].map((item, index) => [
                index + 1,
                item["sub_district"],
                item["village"],
                item["latitude"],
                item["longitude"],
                gridjs.html(
                    `<a href="/parameter-ph-desa/${item["latitude"]}/${item["longitude"]}" class="btn btn-excel btn-success waves-effect waves-light">Excel</a>`
                ),
            ]);

            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: TableDataPhVillage, // Update data
                    })
                    .forceRender(); // Paksa render ulang
            } else {
                gridInstance = new gridjs.Grid({
                    columns: [
                        "No",
                        "Kecamatan",
                        "Desa / Kelurahan",
                        "Latitude",
                        "Longitude",
                        "Action",
                    ],
                    data: TableDataPhVillage,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerPhVillage);
            }
        },
    });
}
