document.addEventListener("DOMContentLoaded", function () {
    const district = document.getElementById("district");
    const block = document.getElementById("block");
    const village = document.getElementById("village");

    if (district) {
        district.addEventListener("change", function () {
            block.innerHTML = '<option value="">Loading...</option>';
            village.innerHTML = '<option value="">Select Village</option>';

            fetch("../api/location/get_blocks.php?district_id=" + this.value)
                .then(res => res.json())
                .then(data => {
                    block.innerHTML = '<option value="">Select Block</option>';
                    if (data.status) {
                        data.data.forEach(item => {
                            block.innerHTML += `<option value="${item.id}">${item.name}</option>`;
                        });
                    }
                });
        });
    }

    if (block) {
        block.addEventListener("change", function () {
            village.innerHTML = '<option value="">Loading...</option>';

            fetch("../api/location/get_villages.php?block_id=" + this.value)
                .then(res => res.json())
                .then(data => {
                    village.innerHTML = '<option value="">Select Village</option>';
                    if (data.status) {
                        data.data.forEach(item => {
                            village.innerHTML += `<option value="${item.id}">${item.village_name}</option>`;
                        });
                    }
                });
        });
    }
});