var map, mapEdit;
var currentMarker = null;
var currentMarkerEdit = null;

var form = document.getElementById("add-form");
var formEdit = document.getElementById("edit-form");
var provinceField = form.querySelector("#province-field");
var provinceVal = new Choices(provinceField);

var regencyContainer = form.querySelector("#regency-container");
var regencyField = form.querySelector("#regency-field");
var regencyVal = new Choices(regencyField, {
    shouldSort: false,
});

var regencyEditContainer = formEdit.querySelector("#regency-edit-container");
var regencyEditField = formEdit.querySelector("#regency-edit-field");
var regencyEditVal = new Choices(regencyEditField, {
    shouldSort: false,
});

var districtContainer = form.querySelector("#district-container");
var districtField = form.querySelector("#district-field");
var districtVal = new Choices(districtField, {
    shouldSort: false,
});

var districtEditContainer = formEdit.querySelector("#district-edit-container");
var districtEditField = formEdit.querySelector("#district-edit-field");
var districtEditVal = new Choices(districtEditField, {
    shouldSort: false,
});

var addressContainer = form.querySelector("#address-container");
var addressField = form.querySelector("#address-field");

var addressEditContainer = formEdit.querySelector("#address-edit-container");
var addressEditField = formEdit.querySelector("#address-edit-field");

var mapContainer = form.querySelector("#map-container");
var latField = form.querySelector("#lat");
var lngField = form.querySelector("#lng");

var mapEditConatiner = formEdit.querySelector("#map-edit-container");
var latEditField = formEdit.querySelector("#lat-edit");
var lngEditField = formEdit.querySelector("#lng-edit");

var loading = form.querySelector("#loading");
var loadingEdit = formEdit.querySelector("#loading-edit");

var btnContainer = form.querySelector("#add-footer");
var btnEditContainer = formEdit.querySelector("#edit-footer");

document.addEventListener("DOMContentLoaded", function () {
    map = L.map("map", {
        attributionControl: false,
    }).setView([-8.157416852745705, 113.72281580436439], 16);

    mapEdit = L.map("map-edit", {
        attributionControl: false,
    }).setView([-8.157416852745705, 113.72281580436439], 16);

    L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 19,
    }).addTo(map);

    L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 19,
    }).addTo(mapEdit);

    var iconMarker = L.icon({
        iconUrl: "/assets/images/marker.png",
        iconSize: [50, 50],
        iconAnchor: [25, 50],
        popupAnchor: [0, -50],
    });

    currentMarker = L.marker([-8.157416852745705, 113.72281580436439], {
        icon: iconMarker,
        draggable: true,
    })
        .addTo(map)
        .bindPopup(
            `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan priksa lokasi petamu sudah benar.</div>`
        );

    currentMarkerEdit = L.marker([-8.157416852745705, 113.72281580436439], {
        icon: iconMarker,
        draggable: true,
    })
        .addTo(mapEdit)
        .bindPopup(
            `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan priksa lokasi petamu sudah benar.</div>`
        );

    $("#showModal").on("shown.bs.modal", function () {
        map.invalidateSize();
    });

    $("#editModal").on("shown.bs.modal", function () {
        mapEdit.invalidateSize();
    });

    map.on("click", onMapClick);
    mapEdit.on("click", onMapClick);
});

function getProvinces(provinceId) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "/location/get-province",
            type: "GET",
            success: function (response) {
                if (response.success) {
                    const province = response.data.find(
                        (province) => province.id == provinceId
                    );

                    resolve(province);
                } else {
                    reject(new Error("Terjadi kesalahan saat mengambil data"));
                }
            },
            error: function (xhr, status, error) {
                reject(new Error("Terjadi kesalahan saat mengambil data"));
            },
        });
    });
}

function getRegencies(provinceId) {
    regencyContainer.style.display = "none";
    regencyEditContainer.style.display = "none";
    districtContainer.style.display = "none";
    districtEditContainer.style.display = "none";
    addressContainer.style.display = "none";
    addressEditContainer.style.display = "none";
    loading.style.display = "block";
    loadingEdit.style.display = "block";
    mapContainer.style.display = "none";
    mapEditConatiner.style.display = "none";

    const url = "/location/get-regency/" + provinceId;
    $.ajax({
        url: url,
        type: "GET",
        success: function (response) {
            if (response.success) {
                loading.style.display = "none";
                loadingEdit.style.display = "none";
                const data = response.data;

                regencyVal.clearStore();
                regencyVal.clearChoices();

                regencyEditVal.clearStore();
                regencyEditVal.clearChoices();

                regencyVal.value = "";
                regencyVal.setChoices([
                    {
                        value: "",
                        label: "Pilih Kabupaten",
                        selected: true,
                        disabled: true,
                    },
                ]);

                regencyEditVal.value = "";
                regencyEditVal.setChoices([
                    {
                        value: "",
                        label: "Pilih Kabupaten",
                        selected: true,
                        disabled: true,
                    },
                ]);

                if (Array.isArray(data)) {
                    regencyVal.setChoices(
                        data.map((regency) => ({
                            value: regency.id,
                            label: regency.name,
                            selected: false,
                            disabled: false,
                        }))
                    );

                    regencyEditVal.setChoices(
                        data.map((regency) => ({
                            value: regency.id,
                            label: regency.name,
                            selected: false,
                            disabled: false,
                        }))
                    );
                    regencyContainer.style.display = "block";
                    regencyEditContainer.style.display = "block";
                } else {
                    mapContainer.style.display = "block";
                    mapContainer.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";

                    mapEditConatiner.style.display = "block";
                    mapEditConatiner.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                }
            }
        },
        error: function (xhr, status, error) {
            mapContainer.style.display = "block";
            mapContainer.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";

            mapEditConatiner.style.display = "block";
            mapEditConatiner.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
        },
    });
}

function getDistricts(regencyId) {
    districtContainer.style.display = "none";
    districtEditContainer.style.display = "none";
    addressContainer.style.display = "none";
    addressEditContainer.style.display = "none";
    loading.style.display = "block";
    loadingEdit.style.display = "block";
    mapContainer.style.display = "none";
    mapEditConatiner.style.display = "none";

    const url = "/location/get-district/" + regencyId;
    $.ajax({
        url: url,
        type: "GET",
        success: function (response) {
            if (response.success) {
                loading.style.display = "none";
                loadingEdit.style.display = "none";
                const data = response.data;

                districtVal.clearStore();
                districtVal.clearChoices();

                districtEditVal.clearStore();
                districtEditVal.clearChoices();

                districtVal.value = "";
                districtVal.setChoices([
                    {
                        value: "",
                        label: "Pilih Kecamatan",
                        selected: true,
                        disabled: true,
                    },
                ]);

                districtEditVal.value = "";
                districtEditVal.setChoices([
                    {
                        value: "",
                        label: "Pilih Kecamatan",
                        selected: true,
                        disabled: true,
                    },
                ]);

                if (Array.isArray(data)) {
                    districtVal.setChoices(
                        data.map((district) => ({
                            value: district.id,
                            label: district.name,
                            selected: false,
                            disabled: false,
                        }))
                    );

                    districtEditVal.setChoices(
                        data.map((district) => ({
                            value: district.id,
                            label: district.name,
                            selected: false,
                            disabled: false,
                        }))
                    );
                    districtContainer.style.display = "block";
                    districtEditContainer.style.display = "block";
                } else {
                    mapContainer.style.display = "block";
                    mapContainer.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                    mapEditConatiner.style.display = "block";
                    mapEditConatiner.innerHTML =
                        "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                }
            }
        },
        error: function (xhr, status, error) {
            mapContainer.style.display = "block";
            mapContainer.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";

            mapEditConatiner.style.display = "block";
            mapEditConatiner.innerHTML =
                "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
        },
    });
}

function showmap(districtId) {
    loading.style.display = "block";
    loadingEdit.style.display = "block";
    if (!navigator.geolocation) {
        alert("Geolocation tidak didukung oleh browser ini.");
        return;
    }

    navigator.geolocation.getCurrentPosition(
        function (position) {
            loading.style.display = "none";
            loadingEdit.style.display = "none";

            mapContainer.style.display = "block";
            map.invalidateSize();

            addressContainer.style.display = "block";

            mapEditConatiner.style.display = "block";
            mapEdit.invalidateSize();

            addressEditContainer.style.display = "block";

            btnContainer.style.display = "block";
            btnEditContainer.style.display = "block";

            var lat = position.coords.latitude;
            var lng = position.coords.longitude;

            console.log(lat, lng);

            map.setView([lat, lng], 16);
            mapEdit.setView([lat, lng], 16);

            if (currentMarker) {
                map.removeLayer(currentMarker);
            }
            if (currentMarker || currentMarkerEdit) {
                map.removeLayer(currentMarker);
                mapEdit.removeLayer(currentMarkerEdit);
            }

            var iconMarker = L.icon({
                iconUrl: "/assets/images/marker.png",
                iconSize: [50, 50],
                iconAnchor: [25, 50],
                popupAnchor: [0, -50],
            });

            currentMarker = L.marker([lat, lng], {
                icon: iconMarker,
                draggable: true,
            }).addTo(map);

            currentMarkerEdit = L.marker([lat, lng], {
                icon: iconMarker,
                draggable: true,
            }).addTo(mapEdit);

            currentMarker.on("dragend", onPointerDragend);
            currentMarkerEdit.on("dragend", onPointerDragend);

            currentMarker
                .bindPopup(
                    `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan priksa lokasi petamu sudah benar.</div>`
                )
                .openPopup();

            currentMarkerEdit
                .bindPopup(
                    `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan priksa lokasi petamu sudah benar.</div>`
                )
                .openPopup();

            latField.value = lat;
            lngField.value = lng;

            latEditField.value = lat;
            lngEditField.value = lng;
        },
        function (error) {
            alert("Error: " + error.message);
        }
    );
}

async function updateData(data) {
    const land = data.land;
    const userRole = data.role;

    var ownerEditField = formEdit.querySelector("#owner-edit-field");
    var noHpEditField = formEdit.querySelector("#nohp-edit-field");
    var rentalPriceEditField = formEdit.querySelector(
        "#rentalprice-edit-field"
    );
    var rentalStartEditField = formEdit.querySelector(
        "#rentalstart-edit-field"
    );
    var rentalUntilEditField = formEdit.querySelector(
        "#rentaluntil-edit-field"
    );
    var landNameEditField = formEdit.querySelector("#landname-edit-field");
    var provinceEditField = formEdit.querySelector("#province-edit-field");
    var provinceEditVal = new Choices(provinceEditField);

    let rentalPrice = new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        minimumFractionDigits: 0,
    }).format(land.rental_price);

    ownerEditField.value = land.owner;
    noHpEditField.value = land.no_hp;
    rentalPriceEditField.value = rentalPrice.replace(/Rp\s?/g, "").trim();
    rentalStartEditField.value = land.rental_start;
    rentalUntilEditField.value = land.rental_until;
    landNameEditField.value = land.land_name;
    provinceEditField.value = land.province_code;
    try {
        const province = await getProvinces(land.province_code);
        provinceEditVal.setChoices([
            {
                value: province.id,
                label: province.name,
                selected: true,
                disabled: true,
            },
        ]);

        $.ajax({
            type: "GET",
            url: "/location/get-regency/" + land.province_code,
            success: function (response) {
                if (response.success) {
                    const dataRegencies = response.data;
                    const regencies = response.data.find(
                        (regency) => regency.id === parseInt(land.regency_code)
                    );

                    regencyEditVal.setChoices([
                        {
                            value: regencies.id,
                            label: regencies.name,
                            selected: true,
                            disabled: true,
                        },
                    ]);

                    if (Array.isArray(dataRegencies)) {
                        regencyEditVal.setChoices(
                            dataRegencies.map((regency) => ({
                                value: regency.id,
                                label: regency.name,
                                selected: false,
                                disabled: false,
                            }))
                        );
                    } else {
                        mapEditConatiner.style.display = "block";
                        mapEditConatiner.innerHTML =
                            "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                    }
                }
            },
        });

        $.ajax({
            type: "GET",
            url: "/location/get-district/" + land.regency_code,
            success: function (response) {
                if (response.success) {
                    const dataDistricts = response.data;
                    const districts = response.data.find(
                        (district) =>
                            district.id === parseInt(land.district_code)
                    );

                    districtEditVal.setChoices([
                        {
                            value: districts.id,
                            label: districts.name,
                            selected: true,
                            disabled: true,
                        },
                    ]);

                    if (Array.isArray(dataDistricts)) {
                        districtEditVal.setChoices(
                            dataDistricts.map((district) => ({
                                value: district.id,
                                label: district.name,
                                selected: false,
                                disabled: false,
                            }))
                        );
                    } else {
                        mapEditConatiner.style.display = "block";
                        mapEditConatiner.innerHTML =
                            "<p class='text-center text-muted'>Terjadi kesalaahan saat mengambil data, silahkan coba beberapa saat lagi</p>";
                    }
                }
            },
        });

        addressEditContainer.style.display = "block";
        addressEditField.value = land.address;

        mapEdit.setView([land.latitude, land.longitude], 16);
        currentMarkerEdit
            .setLatLng([land.latitude, land.longitude])
            .openPopup();

        latEditField.value = land.latitude;
        lngEditField.value = land.longitude;

        if (userRole === "admin") {
            formEdit.action = "/data-lahan/" + land.id;
        } else {
            formEdit.action = "/data-lahan-petugas/" + land.id;
        }
    } catch (error) {
        console.log(error);
    }
}

function deleteData(data) {
    const landId = data.landId;
    const userRole = data.role;

    var form = document.getElementById("delete-form");

    if (userRole === "admin") {
        form.action = "/data-lahan/" + landId;
    } else {
        form.action = "/data-lahan-petugas/" + landId;
    }
}

function onMapClick(e) {
    var lat = e.latlng.lat;
    var lng = e.latlng.lng;

    if (!currentMarker || !currentMarkerEdit) {
        currentMarker = L.marker(e.latlng).addTo(map);
        currentMarkerEdit = L.marker(e.latlng).addTo(mapEdit);
    } else {
        currentMarker.setLatLng(e.latlng);
        currentMarkerEdit.setLatLng(e.latlng);
    }

    currentMarker.on("dragend", onPointerDragend);
    currentMarkerEdit.on("dragend", onPointerDragend);

    currentMarker
        .bindPopup(
            `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan priksa lokasi petamu sudah benar.</div>`
        )
        .openPopup();

    currentMarkerEdit
        .bindPopup(
            `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan priksa lokasi petamu sudah benar.</div>`
        )
        .openPopup();

    latField.value = lat;
    lngField.value = lng;
}

function onPointerDragend() {
    if (!currentMarker) return;
    var coordinates = currentMarker.getLatLng();
    currentMarker
        .setLatLng(coordinates)
        .bindPopup(
            `<div class="text-center"><b>Anda berada di sini</b><br />Silahkan priksa lokasi petamu sudah benar.</div>`
        )
        .openPopup();

    latField.value = coordinates.lat;
    lngField.value = coordinates.lng;
}

function validatePhoneNumber(input) {
    input.value = input.value.replace(/\D/g, "");

    if (input.value.length < 10 || input.value.length > 13) {
        input.setCustomValidity("Nomor telepon tidak valid");
    } else {
        input.setCustomValidity("");
    }
}

function validatePrice(input) {
    let value = input.value.replace(/\D/g, "");
    let formatted = new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        minimumFractionDigits: 0,
    }).format(value);

    input.value = formatted.replace("Rp", "").trim();
}

var checkAll = document.getElementById("checkAll");
checkAll &&
    (checkAll.onclick = function () {
        for (
            var e = document.querySelectorAll(
                    '.form-check-all input[type="checkbox"]'
                ),
                t = 0;
            t < e.length;
            t++
        )
            (e[t].checked = this.checked),
                e[t].checked
                    ? e[t].closest("tr").classList.add("table-active")
                    : e[t].closest("tr").classList.remove("table-active");
    });
var perPage = 10,
    options = {
        valueNames: ["id", "land_name", "owner", "rental_price", "status"],
        page: perPage,
        pagination: !0,
        plugins: [ListPagination({ left: 2, right: 2 })],
    },
    customerList = new List("customerList", options).on(
        "updated",
        function (e) {
            0 == e.matchingItems.length
                ? (document.getElementsByClassName(
                      "noresult"
                  )[0].style.display = "block")
                : (document.getElementsByClassName(
                      "noresult"
                  )[0].style.display = "none");
            var t = 1 == e.i,
                a = e.i > e.matchingItems.length - e.page;
            document.querySelector(".pagination-prev.disabled") &&
                document
                    .querySelector(".pagination-prev.disabled")
                    .classList.remove("disabled"),
                document.querySelector(".pagination-next.disabled") &&
                    document
                        .querySelector(".pagination-next.disabled")
                        .classList.remove("disabled"),
                t &&
                    document
                        .querySelector(".pagination-prev")
                        .classList.add("disabled"),
                a &&
                    document
                        .querySelector(".pagination-next")
                        .classList.add("disabled"),
                e.matchingItems.length <= perPage
                    ? (document.querySelector(
                          ".pagination-wrap"
                      ).style.display = "none")
                    : (document.querySelector(
                          ".pagination-wrap"
                      ).style.display = "flex"),
                e.matchingItems.length == perPage &&
                    document
                        .querySelector(".pagination.listjs-pagination")
                        .firstElementChild.children[0].click(),
                0 < e.matchingItems.length
                    ? (document.getElementsByClassName(
                          "noresult"
                      )[0].style.display = "none")
                    : (document.getElementsByClassName(
                          "noresult"
                      )[0].style.display = "block");
        }
    );
isCount = new DOMParser().parseFromString(
    customerList.items.slice(-1)[0]._values.id,
    "text/html"
);
var isValue = isCount.body.firstElementChild.innerHTML,
    idField = document.getElementById("id-field"),
    customerNameField = document.getElementById("customername-field"),
    emailField = document.getElementById("email-field"),
    dateField = document.getElementById("date-field"),
    phoneField = document.getElementById("phone-field"),
    statusField = document.getElementById("status-field"),
    addBtn = document.getElementById("add-btn"),
    editBtn = document.getElementById("edit-btn"),
    removeBtns = document.getElementsByClassName("remove-item-btn"),
    editBtns = document.getElementsByClassName("edit-item-btn");
function filterContact(e) {
    var t = e;
    customerList.filter(function (e) {
        matchData = new DOMParser().parseFromString(
            e.values().status,
            "text/html"
        );
        e = matchData.body.firstElementChild.innerHTML;
        return "All" == e || "All" == t || e == t;
    }),
        customerList.update();
}
function updateList() {
    var a = document.querySelector("input[name=status]:checked").value;
    (data = userList.filter(function (e) {
        var t = !1;
        return (
            "All" == a
                ? (t = !0)
                : ((t = e.values().sts == a), console.log(t, "statusFilter")),
            t
        );
    })),
        userList.update();
}
filterContact("All"),
    ischeckboxcheck(),
    document
        .getElementById("showModal")
        .addEventListener("hidden.bs.modal", function () {
            clearFields();
        }),
    document
        .querySelector("#customerList")
        .addEventListener("click", function () {
            ischeckboxcheck();
        });
var table = document.getElementById("customerTable"),
    tr = table.getElementsByTagName("tr"),
    trlist = table.querySelectorAll(".list tr"),
    count = Number(isValue.replace(/[^0-9]/g, "")) + 1;
addBtn.addEventListener("click", function (e) {
    "" !== customerNameField.value &&
        "" !== emailField.value &&
        "" !== dateField.value &&
        "" !== phoneField.value &&
        (customerList.add({
            id:
                '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ' +
                count +
                "</a>",
            customer_name: customerNameField.value,
            email: emailField.value,
            date: dateField.value,
            phone: phoneField.value,
            status: isStatus(statusField.value),
        }),
        document.getElementById("close-modal").click(),
        clearFields(),
        filterContact("All"),
        count++);
}),
    editBtn.addEventListener("click", function (e) {
        (document.getElementById("exampleModalLabel").innerHTML =
            "Edit Customer"),
            customerList.get({ id: idField.value }).forEach(function (e) {
                (isid = new DOMParser().parseFromString(
                    e._values.id,
                    "text/html"
                )),
                    isid.body.firstElementChild.innerHTML == itemId &&
                        e.values({
                            id:
                                '<a href="javascript:void(0);" class="fw-medium link-primary">' +
                                idField.value +
                                "</a>",
                            customer_name: customerNameField.value,
                            email: emailField.value,
                            date: dateField.value,
                            phone: phoneField.value,
                            status: isStatus(statusField.value),
                        });
            }),
            document.getElementById("close-modal").click(),
            clearFields();
    });
function isStatus(e) {
    switch (e) {
        case "Active":
            return (
                '<span class="badge badge-soft-success text-uppercase">' +
                e +
                "</span>"
            );
        case "Block":
            return (
                '<span class="badge badge-soft-danger text-uppercase">' +
                e +
                "</span>"
            );
    }
}
function ischeckboxcheck() {
    document.getElementsByName("checkAll").forEach(function (e) {
        e.addEventListener("click", function (e) {
            e.target.checked
                ? e.target.closest("tr").classList.add("table-active")
                : e.target.closest("tr").classList.remove("table-active");
        });
    });
}
// function refreshCallbacks() {
//     removeBtns.forEach(function (e) {
//         e.addEventListener("click", function (e) {
//             e.target.closest("tr").children[1].innerText,
//                 (itemId = e.target.closest("tr").children[1].innerText),
//                 customerList.get({ id: itemId }).forEach(function (e) {
//                     deleteid = new DOMParser().parseFromString(
//                         e._values.id,
//                         "text/html"
//                     );
//                     var t = deleteid.body.firstElementChild;
//                     deleteid.body.firstElementChild.innerHTML == itemId &&
//                         document
//                             .getElementById("delete-record")
//                             .addEventListener("click", function () {
//                                 customerList.remove("id", t.outerHTML),
//                                     document
//                                         .getElementById("deleteRecordModal")
//                                         .click();
//                             });
//                 });
//         });
//     });
//     // editBtns.forEach(function (e) {
//     //     e.addEventListener("click", function (e) {
//     //         e.target.closest("tr").children[1].innerText,
//     //             (itemId = e.target.closest("tr").children[1].innerText),
//     //             customerList.get({ id: itemId }).forEach(function (e) {
//     //                 isid = new DOMParser().parseFromString(
//     //                     e._values.id,
//     //                     "text/html"
//     //                 );
//     //                 var t = isid.body.firstElementChild.innerHTML;
//     //                 t == itemId &&
//     //                     ((idField.value = t),
//     //                     (customerNameField.value = e._values.customer_name),
//     //                     (emailField.value = e._values.email),
//     //                     (dateField.value = e._values.date),
//     //                     (phoneField.value = e._values.phone),
//     //                     statusVal && statusVal.destroy(),
//     //                     (statusVal = new Choices(statusField)),
//     //                     (val = new DOMParser().parseFromString(
//     //                         e._values.status,
//     //                         "text/html"
//     //                     )),
//     //                     (t = val.body.firstElementChild.innerHTML),
//     //                     statusVal.setChoiceByValue(t),
//     //                     flatpickr("#date-field", {
//     //                         dateFormat: "d M, Y",
//     //                         defaultDate: e._values.date,
//     //                     }));
//     //             });
//     //     });
//     // });
// }
function clearFields() {
    var ownerField = form.querySelector("#owner-field");
    var noHpField = form.querySelector("#nohp-field");
    var rentalPriceField = form.querySelector("#rentalprice-field");
    var rentalStartField = form.querySelector("#rentalstart-field");
    var rentalEndField = form.querySelector("#rentaluntil-field");
    var landNameField = form.querySelector("#landname-field");
    var addressField = form.querySelector("#address-field");

    (ownerField.value = ""),
        (noHpField.value = ""),
        (rentalPriceField.value = ""),
        (rentalStartField.value = ""),
        (rentalEndField.value = ""),
        (landNameField.value = ""),
        (addressField.value = "");

    provinceVal.setChoices([
        {
            value: "",
            label: "Pilih Provinsi",
            selected: true,
            disabled: true,
        },
    ]);

    regencyVal.clearStore();
    districtVal.clearStore();
    latField.value = "";
    lngField.value = "";

    regencyContainer.style.display = "none";
    districtContainer.style.display = "none";
    addressContainer.style.display = "none";
    mapContainer.style.display = "none";
    btnContainer.style.display = "none";
}
document
    .querySelector(".pagination-next")
    .addEventListener("click", function () {
        !document.querySelector(".pagination.listjs-pagination") ||
            (document
                .querySelector(".pagination.listjs-pagination")
                .querySelector(".active") &&
                document
                    .querySelector(".pagination.listjs-pagination")
                    .querySelector(".active")
                    .nextElementSibling.children[0].click());
    }),
    document
        .querySelector(".pagination-prev")
        .addEventListener("click", function () {
            !document.querySelector(".pagination.listjs-pagination") ||
                (document
                    .querySelector(".pagination.listjs-pagination")
                    .querySelector(".active") &&
                    document
                        .querySelector(".pagination.listjs-pagination")
                        .querySelector(".active")
                        .previousSibling.children[0].click());
        });
