<script>
    function showLoadingSwal(message, duration = 5000) {
        Swal.fire({
            title: message,
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            },
            timer: duration, // Durasi dalam milidetik
            timerProgressBar: true, // Menampilkan progres bar timer
        }).then((result) => {
            if (result.dismiss === Swal.DismissReason.timer) {
                console.log("Dialog loading otomatis ditutup.");
            }
        });
    }

    function hideLoadingSwal() {
        Swal.close();
    }

    function previewImage(input, imageId) {
        const preview = document.getElementById(imageId);
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.classList.remove('hidden');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }


    function formatNumber(input) {
        const cursorPosition = input.selectionStart;

        let value = input.value.replace(/[^0-9,]/g, '');

        if ((value.match(/,/g) || []).length > 1) {
            value = value.replace(/,/g, (match, offset) => (offset === value.indexOf(',') ? ',' : ''));
        }

        if (value.includes(',')) {
            const [beforeComma, afterComma] = value.split(',');
            value = `${beforeComma},${afterComma.substring(0, 2)}`;
        }

        input.value = value ? value + ' m²' : 'm²';


        input.setSelectionRange(cursorPosition, cursorPosition);
    }





    function formatCurrency(value, isDiskon = false) {
        // Ensure the value is a valid number
        const numericValue = parseFloat(value);
        if (isNaN(numericValue)) {
            return 0;
        }

        // Format the number with commas for thousands separators
        const formattedValue = numericValue.toLocaleString('id-ID', {
            style: 'currency',
            currency: 'IDR', // Indonesian Rupiah
            minimumFractionDigits: isDiskon ? 2 : 0, // Include decimals for discounts
            maximumFractionDigits: isDiskon ? 2 : 0,
        });

        return formattedValue;
    }

    function previewImage(input, previewId) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#' + previewId).attr('src', e.target.result).show();
            }
            reader.readAsDataURL(input.files[0]);
        } else {
            $('#' + previewId).hide();
        }
    }

    function addClonableItem(containerId, itemClass) {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`Container with ID "${containerId}" not found.`);
            return;
        }

        const template = container.querySelector(`.${itemClass}`);
        if (!template) {
            console.error(`Template with class "${itemClass}" not found in container "${containerId}".`);
            return;
        }

        // Clone the template element
        const newElement = template.cloneNode(true);

        // Reset all input fields comprehensively
        const inputs = newElement.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            // Reset based on input type
            switch (input.type) {
                case 'text':
                case 'number':
                case 'email':
                case 'tel':
                case 'password':
                case 'search':
                case 'url':
                case 'textarea':
                    input.value = '';
                    break;
                case 'checkbox':
                case 'radio':
                    input.checked = false;
                    break;
                case 'select-one':
                case 'select-multiple':
                    input.selectedIndex = 0;
                    break;
                case 'file':
                    input.value = '';
                    break;
            }

            // Remove any error classes or validation states
            input.classList.remove('is-invalid', 'error');

            // Reset any custom attributes if needed
            input.removeAttribute('data-previous-value');
        });

        // Reset select elements to their default state
        const selects = newElement.querySelectorAll('select');
        selects.forEach(select => {
            select.selectedIndex = 0;
        });

        // Make the delete button visible and bind the click event
        const deleteButton = newElement.querySelector('.remove-btn');
        if (deleteButton) {
            deleteButton.style.display = 'inline-block';
            deleteButton.addEventListener('click', () => {
                newElement.remove();
            });
        }

        // Reset any custom data attributes
        newElement.querySelectorAll('[data-clone-reset]').forEach(element => {
            const resetValue = element.getAttribute('data-clone-reset');
            if (resetValue) {
                if (element.tagName === 'INPUT' || element.tagName === 'SELECT' || element.tagName ===
                    'TEXTAREA') {
                    element.value = resetValue;
                } else {
                    element.textContent = resetValue;
                }
            }
        });

        // Optional: Regenerate unique IDs if needed
        const elementsWithId = newElement.querySelectorAll('[id]');
        elementsWithId.forEach(element => {
            const originalId = element.id;
            const newId = `${originalId}_${Date.now()}`;
            element.id = newId;

            // Update any labels or references
            const labels = newElement.querySelectorAll(`label[for="${originalId}"]`);
            labels.forEach(label => {
                label.setAttribute('for', newId);
            });
        });

        // Append the cloned element to the container
        container.appendChild(newElement);

        // Optional: Trigger any custom events or reinitialize plugins
        const event = new Event('cloneAdded', {
            bubbles: true
        });
        newElement.dispatchEvent(event);
    }

    async function loadSavedLocationData() {
        const provinceCode = '{{ $cekAlamat['province_code'] ?? '' }}';
        const cityCode = '{{ $cekAlamat['city_code'] ?? '' }}';
        const districtCode = '{{ $cekAlamat['district_code'] ?? '' }}';
        const villageCode = '{{ $cekAlamat['village_code'] ?? '' }}';

        // Set province
        const provinceSelect = document.getElementById('province_code');
        if (provinceCode && provinceSelect) {
            provinceSelect.value = provinceCode;
            await getCity(provinceCode);
        }

        // Set city
        const citySelect = document.getElementById('city_code');
        if (cityCode && citySelect) {
            citySelect.value = cityCode;
            await getDistrict(cityCode);
        }

        // Set district
        const districtSelect = document.getElementById('district_code');
        if (districtCode && districtSelect) {
            districtSelect.value = districtCode;
            await getVillage(districtCode);
        }

        // Set village
        const villageSelect = document.getElementById('village_code');
        if (villageCode && villageSelect) {
            villageSelect.value = villageCode;
        }
    }

    // Modifikasi fungsi existing
    async function getCity(provinceId) {
        try {
            const response = await fetch(`/locations/cities/province/${provinceId}`);
            const data = await response.json();

            const cityDropdown = document.getElementById('city_code');
            if (cityDropdown) {
                cityDropdown.innerHTML = '<option value="">Pilih Kota/Kabupaten</option>';
                data.forEach(city => {
                    const option = document.createElement('option');
                    option.value = city.code;
                    option.textContent = city.name;
                    @if (isset($debitur->city_code))
                        if (city.code === '{{ $debitur->city_code }}') {
                            option.selected = true;
                        }
                    @endif

                    cityDropdown.appendChild(option);
                });

                // Reset dropdown kecamatan dan desa
                document.getElementById('district_code').innerHTML = '<option value="">Pilih Kecamatan</option>';
                document.getElementById('village_code').innerHTML = '<option value="">Pilih Kelurahan</option>';
            }
        } catch (error) {
            console.error('Error fetching cities:', error);
        }
    }

    // Lakukan hal serupa untuk getDistrict dan getVillage
    async function getDistrict(cityId) {
        try {
            const response = await fetch(`/locations/districts/city/${cityId}`);
            const data = await response.json();

            const districtDropdown = document.getElementById('district_code');
            if (districtDropdown) {
                districtDropdown.innerHTML = '<option value="">Pilih Kecamatan</option>';
                data.forEach(district => {
                    const option = document.createElement('option');
                    option.value = district.code;
                    option.textContent = district.name;

                    // Cek apakah ini adalah kecamatan yang sebelumnya dipilih
                    @if (isset($debitur->district_code))
                        if (district.code === '{{ $debitur->district_code }}') {
                            option.selected = true;
                        }
                    @endif

                    districtDropdown.appendChild(option);
                });

                // Reset dropdown desa
                document.getElementById('village_code').innerHTML = '<option value="">Pilih Kelurahan</option>';
            }
        } catch (error) {
            console.error('Error fetching districts:', error);
        }
    }

    async function getVillage(districtId) {
        try {
            const response = await fetch(`/locations/villages/district/${districtId}`);
            const data = await response.json();

            const villageDropdown = document.getElementById('village_code');
            if (villageDropdown) {
                villageDropdown.innerHTML = '<option value="">Pilih Desa/Kelurahan</option>';
                data.forEach(village => {
                    const option = document.createElement('option');
                    option.value = village.code;
                    option.textContent = village.name;

                    // Cek apakah ini adalah desa yang sebelumnya dipilih
                    @if (isset($debitur->village_code))
                        if (village.code === '{{ $debitur->village_code }}') {
                            option.selected = true;
                        }
                    @endif

                    villageDropdown.appendChild(option);
                });
            }
        } catch (error) {
            console.error('Error fetching villages:', error);
        }
    }


    function checkLaporan(permohonanId, documentId, inspeksiId, statusLpj) {
        // showLoadingSwal('Tunggu...');
        fetch(
                `{{ url('/penilai/check-laporan') }}?permohonanId=${permohonanId}&documentId=${documentId}&inspeksiId=${inspeksiId}`
            )
            .then(response => response.json())
            .then(data => {
                if (data.status) {
                    window.location.href =
                        `{{ route('penilai.print-out') }}?permohonanId=${permohonanId}&documentId=${documentId}&inspeksiId=${inspeksiId}&statusLpj=${statusLpj}&type=${data.status}`;
                } else {
                    // Jika laporan belum ada, tampilkan pesan peringatan
                    Swal.fire({
                        title: 'Laporan Belum Ada',
                        text: data.message,
                        icon: 'warning',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#3085d6',
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    title: 'Terjadi Kesalahan',
                    text: 'Tidak dapat memproses permintaan. Silakan coba lagi nanti.',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#d33',
                });
            });
    }

    function updateAnalisa(params) {
        const inputMap = {
            jenis_asset: 'jenis_asset_tidak_sesuai',
            analisa_tanah: 'analisa_tanah_tidak_sesuai',
            analisa_unit: 'analisa_luas_unit_tidak_sesuai',
            analisa_bangunan: 'analisa_bangunan_tidak_sesuai',
        };

        // Pastikan elemen ID ada di inputMap
        if (!inputMap[params]) {
            console.error('Parameter tidak valid:', params);
            return;
        }

        // Ambil nilai berdasarkan parameter
        const inputValue = document.getElementById(inputMap[params]).value;
        const data = {
            [params === 'jenis_asset' ? 'jenis_asset' : params.replace('analisa_', 'luas_')]: inputValue,
            types: params,
            ...(document.getElementById('jenis_legalistas_jaminan_bangunan_id') && {
                jenis_legalistas_jaminan_bangunan_id: document.getElementById(
                    'jenis_legalistas_jaminan_bangunan_id').value
            }),
            ...(document.getElementById('jenis_legalistas_jaminan_tanah_id') && {
                jenis_legalistas_jaminan_tanah_id: document.getElementById('jenis_legalistas_jaminan_tanah_id')
                    .value
            }),
            ...(document.getElementById('jenis_legalistas_jaminan_unit_id') && {
                jenis_legalistas_jaminan_unit_id: document.getElementById('jenis_legalistas_jaminan_unit_id')
                    .value
            })
        };

        console.log(data);


        $.ajax({
            url: '{{ route('surveyor.update_analisa', ['id' => $permohonan->id]) }}',
            type: 'POST',
            data: data,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            success: function(response) {
                console.log(response);
                if (response.success) {
                    // window.location.href =
                    //     '{{ route('surveyor.show', ['id' => $permohonan->id]) }}';
                    toastrSuccessBuild(response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error('Terjadi error:', error);
                console.log('Status:', status);
                console.log('Response:', xhr.responseText);
                if (xhr.responseJSON.message) {
                    toastrErrorBuild(xhr.responseJSON.message);
                } else {
                    toastrErrorBuild('Terjadi kesalahan');
                }
            }
        });
    }

    function updateAlamatFields(status) {
        // Ambil elemen formulir
        const addressForm = document.getElementById('alamat_form');
        const inputs = addressForm.querySelectorAll('input, select');
        const addressInput = document.getElementById('address');

        if (status === 'sesuai') {
            addressInput.value = {!! json_encode($dokumen->address ?? '') !!};

            inputs.forEach(element => {
                if (element.tagName === 'INPUT') {
                    element.setAttribute('readonly', true);
                } else if (element.tagName === 'SELECT') {
                    element.setAttribute('disabled', true);
                    element.classList.add('disabled-input')
                }
            });

            addressForm.style.display = 'grid';
            addressForm.disabled = true;
            addressForm.classList.add('disabled-input')


        } else if (status === 'tidak sesuai') {
            addressForm.style.display = 'grid';

            addressForm.removeAttribute('disabled');
            addressForm.classList.remove('disabled-input')
            const formInspeksi = @json($forminspeksi ?? '');
            const addressInput = document.getElementById('address');

            if (formInspeksi && formInspeksi.asset && formInspeksi.asset.alamat) {
                if (formInspeksi.asset.alamat['tidak sesuai'] && formInspeksi.asset.alamat['tidak sesuai'].address) {
                    addressInput.value = formInspeksi.asset.alamat['tidak sesuai'].address;
                } else if (formInspeksi.asset.alamat['sesuai'] && formInspeksi.asset.alamat['sesuai'].address) {
                    addressInput.value = formInspeksi.asset.alamat['sesuai'].address;
                } else {
                    addressInput.value = "";
                }
            }

            inputs.forEach(element => {
                if (element.tagName === 'INPUT') {
                    element.removeAttribute('readonly');
                } else if (element.tagName === 'SELECT') {
                    element.removeAttribute('disabled');
                    element.classList.remove('disabled-input')
                }
            });
        }
    }

    function toggleFieldVisibility(fieldName, inputId, visibleValues = []) {
        const selectedValue = $(`[name="${fieldName}"]:checked`).val();
        const inputField = $(`#${inputId}`);

        if (visibleValues.includes(selectedValue)) {
            inputField.show();
        } else {
            inputField.hide().val('');
        }
    }


    function toggleCheckboxVisibility(fieldName, inputId, visibleValues = []) {
        const selectedValues = $(`[name="${fieldName}[]"]:checked`)
            .map(function() {
                return $(this).val().toLowerCase(); // Konversi nilai ke huruf kecil
            })
            .get();

        const inputField = $(`#${inputId}`);

        // Cek apakah salah satu nilai yang dipilih cocok dengan visibleValues
        const shouldShow = visibleValues.some(value => selectedValues.includes(value.toLowerCase()));

        if (shouldShow) {
            inputField.show();
        } else {
            inputField.hide().val('');
        }
    }


    function toggleMultipleFields(fieldName, mappings) {
        // Ambil semua nilai checkbox yang dicentang
        const selectedValues = $(`[name="${fieldName}[]"]:checked`)
            .map(function() {
                return $(this).val().toLowerCase(); // Konversi nilai ke huruf kecil
            })
            .get();

        // Iterasi melalui setiap mapping
        for (const [key, inputId] of Object.entries(mappings)) {
            const inputField = $(`#${inputId}`);

            // Tampilkan input jika nilai yang relevan dipilih
            if (selectedValues.includes(key.toLowerCase())) {
                inputField.show();
            } else {
                inputField.hide().val(''); // Sembunyikan dan reset nilai
            }
        }
    }


    function toggleAlamatVisibility(idSesuai, idTidakSesuai, selectedValue) {
        // Ambil elemen berdasarkan ID
        const alamatSesuai = document.getElementById(idSesuai);
        const alamatTidakSesuai = document.getElementById(idTidakSesuai);

        // Periksa nilai yang dipilih dan tampilkan elemen yang sesuai
        if (selectedValue === 'sesuai') {
            alamatSesuai.style.display = 'grid'; // Tampilkan "Alamat Sesuai"
            alamatTidakSesuai.style.display = 'none'; // Sembunyikan "Alamat Tidak Sesuai"
        } else if (selectedValue === 'tidak sesuai') {
            alamatSesuai.style.display = 'none'; // Sembunyikan "Alamat Sesuai"
            alamatTidakSesuai.style.display = 'grid'; // Tampilkan "Alamat Tidak Sesuai"
        }
    }


    function handleCurrencyInput(input) {
        const value = input.value.replace(/[^\d]/g, '');
        input.value = formatCurrency(value);
    }

    function cleanCurrencyValue(value) {
        return value.replace(/[^\d]/g, '');
    }
</script>
