document.addEventListener("DOMContentLoaded", function () {
    loadDataHeightVillage("2021");

    const btnSpanExcel = document.getElementById("btn-span-excel");
    $("#choiceYear").on("change", function () {
        year = $(this).val();

        $("#span-year").text(year);
        loadDataHeightVillage(year);
    });

    btnSpanExcel.addEventListener("click", function () {
        const year = $("#choiceYear").val();
        var url = "/parameter-ketinggian-desa/" + year;

        window.open(url, "_self");
    });
});

let gridInstance;
function loadDataHeightVillage(years) {
    const tableContainerHeightVillage = document.getElementById(
        "table-height-village"
    );

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

    $.ajax({
        url: `/parameter-ketinggian-desa/getDataHeightVillage`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const TableDataHeightVillage = data["allVillage"].map(
                (item, index) => [
                    index + 1,
                    item["sub_district"],
                    item["village"],
                    item["latitude"],
                    item["longitude"],
                ]
            );

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