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

let gridInstance;
function loadDataPhSubDistrict() {
    const tableContainerPhSubDistrict = document.getElementById(
        "table-ph-sub-district"
    );

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

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

            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: TableDataPhSubDistrict,
                    })
                    .forceRender();
            } else {
                gridInstance = new gridjs.Grid({
                    columns: [
                        "No",
                        "Kecamatan",
                        "Latitude",
                        "Longitude",
                        "Action",
                    ],
                    data: TableDataPhSubDistrict,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerPhSubDistrict);
            }
        },
    });
}
