<div class="grid gap-5 mx-auto w-full lg:gap-7.5">

    @foreach ($permohonan->documents as $dokumen)
        @if ($dokumen->jenisJaminan)
            @php
                $formKategori = json_decode($dokumen->jenisJaminan->form_kategori, true);
                $jenisAset = $dokumen->jenisJaminan->name;
            @endphp
            @if (isset($formKategori) && $formKategori)
                @php
                    $kategoriArray = is_array($formKategori) ? $formKategori : [$formKategori];
                    $kategoriUnik = array_unique($kategoriArray);
                @endphp
                <input type="hidden" name="action" value="{{ implode(',', $kategoriUnik) }}">
                <input type="hidden" name="type" value="{{ implode(',', $kategoriUnik) }}">


                @if (array_intersect($kategoriUnik, ['tanah', 'bangunan', 'apartemen-kantor']))
                    @include('lpj::surveyor.components.header')
                @endif

                @foreach ($kategoriUnik as $kategori)
                    {{-- Tampilkan komponen sesuai kategori --}}
                    @include('lpj::surveyor.components.' . str_replace('-', '-', $kategori), [
                        'dokumen' => $dokumen,
                    ])
                @endforeach
            @endif
        @endif
    @endforeach


    <div class="card">
        <div class="card-header bg-agi-50">
            <h3 class="uppercase card-title">
                Informasi dan pembanding
            </h3>
            <div class="card-tools">
                <a href="{{ route('penilai.showDataPembanding', ['id' => $permohonan->id]) }}?documentId={{ request()->documentId }}&jenis_jaminan={{ request()->jaminanId }}"
                    class="btn btn-primary" data-bs-toggle="modal">
                    Edit Data Pembanding
                </a>
            </div>
        </div>
        @include('lpj::penilai.components.informasi-pembanding')
    </div>

    <div class="card">
        <div class="card-header bg-agi-50">
            <h3 class="uppercase card-title">
                total nilai pasar wajar
            </h3>
        </div>
        <div class="gap-5 card-body">
            <div>
                <label for="total_nilai_pasar_wajar" class="form-label">Total Nilai Pasar Wajar</label>
                <div class="grid gap-2.5 card-body">

                    @php
                        $labelNilai = [
                            'bangunan' => 'Luas Bangunan',
                            'tanah' => 'Luas Tanah',
                            'apartemen-kantor' => 'Luas Unit',
                            'alat-berat' => 'Luas Alat Berat',
                            'mesin' => 'Luas Mesin',
                            'kendaraan' => 'Luas Kendaraan',
                            'pesawat' => 'Luas Pesawat',
                            'kapal' => 'Luas Kapal',
                        ];

                        if (strcasecmp($jenisAset, 'RUKO/RUKAN') === 0) {
                            $labelNilai['bangunan'] = 'Luas Unit';
                            unset($labelNilai['tanah']);
                        }
                    @endphp

                    @foreach ($kategoriUnik as $item)
                        @php
                            $luas = match ($item) {
                                'bangunan' => $forminspeksi['bangunan']['luas_tanah_bagunan']['tidak sesuai'] ??
                                            $forminspeksi['bangunan']['luas_tanah_bagunan']['sesuai'] ?? null,
                                'tanah'    => $forminspeksi['tanah']['luas_tanah']['tidak sesuai'] ??
                                            $forminspeksi['tanah']['luas_tanah']['sesuai'] ?? null,
                                'apartemen-kantor' => $forminspeksi['luas_unit']['sesuai'] ??
                                                    $forminspeksi['luas_unit']['tidak sesuai'] ?? null,
                                default    => null,
                            };

                            $luas = old('luas_' . $item, $lpjData['luas_' . $item] ?? $luas);
                            $luasKey = 'luas_' . $item;
                            $nilaiKey1 = 'nilai_' . $item . '_1';
                            $nilaiKey2 = 'nilai_' . $item . '_2';
                        @endphp
                        @if (isset($labelNilai[$item]))
                            <div class="flex gap-2.5 w-full grid-col-3">
                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="province" class="form-label max-w-56">
                                        {{ $labelNilai[$item] }}
                                    </label>
                                    <input type="text" id="{{ $luasKey }}" class="w-full input"
                                        name="{{ $luasKey }}"
                                        value="{{ old($luasKey, $lpjData[$luasKey] ?? null) }}"
                                        oninput="calculateTotal()">
                                </div>
                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="province" class="">X</label>
                                    <label class="input">
                                        <i class="">Rp</i>
                                        <input type="text" id="{{ $nilaiKey1 }}" class="w-full currency"
                                            name="{{ $nilaiKey1 }}"
                                            value="{{ old($nilaiKey1, $lpjData[$nilaiKey1] ?? null) }}"
                                            oninput="calculateTotal()">
                                    </label>
                                </div>
                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label class="input">
                                        <i class="">Rp</i>
                                        <input id="{{ $nilaiKey2 }}" type="text"
                                            class="w-full currency-format"
                                            name="{{ $nilaiKey2 }}"
                                            value="{{ old($nilaiKey2, $lpjData[$nilaiKey2] ?? null) }}">
                                    </label>
                                </div>
                            </div>
                        @endif
                    @endforeach

                    <div>
                        <div id="add_pasar_wajar" class="flex flex-wrap gap-2.5 w-full">
                        </div>
                    </div>

                    <div class="flex gap-2 justify-end">
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap grid-col-2">
                            <label class="form-label max-w-56" for="">Total Nilai</label>
                            <label for="province" class="input">
                                <i class="">Rp
                                </i>
                                <input type="text" class="w-full currency-format" id="total_nilai_pasar_wajar"
                                    name="total_nilai_pasar_wajar"
                                    value="{{ old('total_nilai_pasar_wajar', $lpjData['total_nilai_pasar_wajar'] ?? null) }}">
                            </label>
                        </div>
                    </div>
                </div>

            </div>

            <div class="mb-10 tambah" style="margin-bottom: 20px;">
                <button type="button" id="tambah-npw" class="btn btn-primary">
                    <i class="ki-filled ki-plus"></i>
                    Tambah NPW </button>
            </div>

            <div>
                <label for="total_nilai_pasar_wajar" class="uppercase form-label">TOTAL NILAI
                    LIKUIDASI</label>
                <div class="grid gap-2.5 w-full card-body">
                    <div class="flex gap-2.5 w-full grid-col-3">
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <div class="w-full">
                                <label class="input">

                                    <input type="text" id="likuidasi" name="likuidasi" class="w-full currency"
                                        value="{{ old('likuidasi', $lpjData['likuidasi'] ?? null) }}"
                                        oninput="calculateTotal()">
                                    <i class="">%
                                    </i>
                                </label>
                                <span class="text-xs"> <span class="text-xs text-danger">*</span> Masukkan Angka Saja
                                </span>
                            </div>
                        </div>
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="province" class="">X</label>
                            <label class="input">
                                <i class="">Rp
                                </i>
                                <input type="text" class="w-full currency-format" id="likuidasi_nilai_1"
                                    name="likuidasi_nilai_1"
                                    value="{{ old('likuidasi_nilai_1', $lpjData['likuidasi_nilai_1'] ?? null) }}"
                                    oninput="calculateTotal()">
                            </label>
                        </div>
                        <div class="grid gap-2.5 w-full">
                            <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">

                                <label class="input">
                                    <i class="">Rp
                                    </i>
                                    <input type="text" class="w-full currency-format" name="likuidasi_nilai_2"
                                        value="{{ old('likuidasi_nilai_2', $lpjData['likuidasi_nilai_2'] ?? null) }}">
                            </div>

                        </div>

                    </div>
                </div>
            </div>

            <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap" style="margin-top: 20px">

                <label class="form-label lg:form-label max-w-56">Catatan yang Perlu Diperhatikan
                </label>
                <div class="w-full">
                    <div id="keterangan_penilai-container" class="flex flex-wrap gap-2.5 items-baseline w-full">
                        @if (!empty($lpjData['keterangan_penilai']) && is_array($lpjData['keterangan_penilai']))
                            @foreach ($lpjData['keterangan_penilai'] as $index => $item)
                                <div class="flex gap-2 items-center mt-2 w-full keterangan_penilai textarea-group">
                                    <textarea name="keterangan_penilai[]" class="mt-2 textarea" placeholder="Masukkan catatan penting" rows="10">{{ old("keterangan_penilai.$index", $item) }}</textarea>
                                    <button class="btn btn-danger btn-sm remove-btn" type="button"
                                        style="display: none;">
                                        <i class="ki-outline ki-trash"></i>
                                    </button>
                                </div>
                            @endforeach
                        @else
                            <div class="flex gap-2 items-center mt-2 w-full keterangan_penilai textarea-group">
                                <textarea name="keterangan_penilai[]" class="mt-2 textarea" placeholder="Masukkan catatan penting" rows="10"></textarea>
                                <button class="btn btn-danger btn-sm remove-btn" type="button"
                                    style="display: none;">
                                    <i class="ki-outline ki-trash"></i>
                                </button>
                                <em id="error-keterangan_penilai" class="text-sm alert text-danger"></em>
                            </div>
                        @endif
                    </div>
                    <button type="button"
                        onclick="addClonableItem('keterangan_penilai-container', 'keterangan_penilai')"
                        class="mt-5 btn btn-primary btn-sm">
                        <i class="ki-outline ki-plus"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

</div>
<script type="text/javascript">
    const datas = @json($lpjData);
    console.log(datas);

    document.addEventListener('DOMContentLoaded', function() {
        const tambahNPWButton = document.getElementById('tambah-npw');
        const addPasarWajarContainer = document.getElementById('add_pasar_wajar');
        let npwCounter = 0;

        tambahNPWButton.addEventListener('click', function() {
            npwCounter++;

            const newNPWRow = document.createElement('div');
            newNPWRow.className = 'flex grid-col-3 gap-2.5 w-full npw-row';
            newNPWRow.innerHTML = `
                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                    <input type="text"
                        id="name_npw_${npwCounter}"
                        class="w-full input"
                        name="name_npw_${npwCounter}"
                        placeholder="Nama NPW">

                    <input type="text"
                        id="ls_npw_${npwCounter}"
                        class="w-full input"
                        name="luas_npw_${npwCounter}"
                        placeholder="Luas NPW"
                        oninput="calculateTotal()">
                </div>
                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                    <label for="province" class="">X</label>
                     <label class="input">
                                <i class="">Rp
                                </i>
                    <input type="text"
                        id="nilai_npw_${npwCounter}_1"
                        class="w-full currency"
                        name="nilai_npw_${npwCounter}_1"
                        placeholder="Harga per meter"
                        oninput="calculateTotal()">
                        </label>
                </div>
                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                     <label class="input">
                                <i class="">Rp
                                </i>
                    <input type="text"
                        id="nilai_npw_${npwCounter}_2"
                        class="w-full input currency-format"
                        name="nilai_npw_${npwCounter}_2"
                        placeholder="Total Nilai"
                        readonly>
                        </label>
                    <button type="button" class="btn btn-danger remove-npw">
                        <i class="ki-filled ki-minus"></i>
                    </button>
                </div>
            `;

            // Tambahkan event listener untuk remove button
            newNPWRow.querySelector('.remove-npw').addEventListener('click', function() {
                newNPWRow.remove();
                calculateTotal();
            });

            // Tambahkan event listener untuk currency format
            newNPWRow.querySelectorAll('.currency').forEach(input => {
                input.addEventListener('change', function() {
                    window.IMask(this, {
                        mask: Number, // enable number mask
                        // other options are optional with defaults below
                        scale: 0, // digits after point, 0 for integers
                        thousandsSeparator: ".", // any single char
                        padFractionalZeros: false, // if true, then pads zeros at end to the length of scale
                        normalizeZeros: true, // appends or removes zeros at ends
                        radix: ",", // fractional delimiter
                        mapToRadix: ["."], // symbols to process as radix

                        autofix: true,
                    });
                });
            });

            addPasarWajarContainer.appendChild(newNPWRow);
        });

        function loadSavedNPW() {
            // Cek apakah ada data LPJ yang sudah tersimpan
            const lpjDataElement = document.getElementById('lpj-data');
            if (lpjDataElement) {
                const lpjData = JSON.parse(lpjDataElement.value);

                // Periksa apakah ada NPW tambahan
                if (lpjData.npw_tambahan && lpjData.npw_tambahan.length > 0) {
                    lpjData.npw_tambahan.forEach((npw, index) => {
                        // Increment counter
                        npwCounter++;

                        // Buat row baru
                        const newNPWRow = document.createElement('div');
                        newNPWRow.className = 'flex grid-col-3 gap-2.5 w-full npw-row mb-3';
                        newNPWRow.innerHTML = `

                            <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                <input type="text"
                                    id="name_npw_${npwCounter}"
                                    class="w-full input"
                                    name="name_npw_${npwCounter}"
                                    placeholder="Nama NPW"
                                    value="${npw.name || ''}">
                                <input type="text"
                                    id="ls_npw_${npwCounter}"
                                    class="w-full input currency-format"
                                    name="luas_npw_${npwCounter}"
                                    placeholder="Luas NPW"
                                    value="${npw.luas || ''}"
                                    oninput="calculateTotal()">
                            </div>


                            <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                <label for="province" class="">X</label>
                                 <label class="input">
                                <i class="">Rp
                                </i>
                                <input type="text"
                                    id="nilai_npw_${npwCounter}_1"
                                    class="w-full currency"
                                    name="nilai_npw_${npwCounter}_1"
                                    placeholder="Harga per meter"
                                    value="${npw.nilai_1 || '0'}"
                                    oninput="calculateTotal()">
                                    </label>
                            </div>
                            <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                 <label class="input">
                                <i class="">Rp
                                </i>
                                <input type="text"
                                    id="nilai_npw_${npwCounter}_2"
                                    class="w-full currency-format"
                                    name="nilai_npw_${npwCounter}_2"
                                    placeholder="Total Nilai"
                                    value="${npw.nilai_2 || ''}"
                                    readonly>
                                    </label>
                                    <div>
                                <button type="button" class="h-full btn btn-danger remove-npw">
                                    <i class="ki-filled ki-minus"></i>
                                </button>
                            </div>
                            </div>


                    `;

                        // Tambahkan event listener untuk remove button
                        newNPWRow.querySelector('.remove-npw').addEventListener('click', function() {
                            newNPWRow.remove();
                            calculateTotal();
                        });

                        // Initialize currency formatting for existing values
                        newNPWRow.querySelectorAll('.currency').forEach(input => {
                            // Apply IMask immediately for existing values
                            if (input.value && input.value !== '0') {
                                window.IMask(input, {
                                    mask: Number,
                                    scale: 0,
                                    thousandsSeparator: ".",
                                    padFractionalZeros: false,
                                    normalizeZeros: true,
                                    radix: ",",
                                    mapToRadix: ["."],
                                    autofix: true,
                                });
                            }

                            // Also add blur event for future editing
                            input.addEventListener('blur', function() {
                                if (!this.imask) {
                                    window.IMask(this, {
                                        mask: Number,
                                        scale: 0,
                                        thousandsSeparator: ".",
                                        padFractionalZeros: false,
                                        normalizeZeros: true,
                                        radix: ",",
                                        mapToRadix: ["."],
                                        autofix: true,
                                    });
                                }
                            });
                        });

                        // Tambahkan row baru di bagian bawah
                        addPasarWajarContainer.appendChild(newNPWRow);
                    });

                    // Hitung total setelah memuat data
                    calculateTotal();
                }
            }
        }

        // Panggil fungsi load NPW saat halaman dimuat
        loadSavedNPW();
        document.querySelectorAll('.currency').forEach(input => {
            input.addEventListener('input', function() {
                formatCurrency(this);
            });
        });

    });

    function formatPercentage(value) {
        // Hapus semua karakter kecuali angka dan koma
        let numericValue = value.replace(/[^0-9,]/g, '');

        // Pastikan hanya satu koma yang ada
        let parts = numericValue.split(',');
        if (parts.length > 2) {
            numericValue = parts[0] + ',' + parts[1]; // Pertahankan hanya bagian pertama dan kedua
        }

        // Jika nilai melebihi 100, batasi menjadi 100
        let numericFloat = parseFloat(numericValue.replace(',', '.')) || 0;
        if (numericFloat > 100) {
            numericFloat = 100;
            numericValue = '100';
        }

        // Kembalikan nilai dengan simbol %
        return numericValue;
    }

    function calculateTotal() {
        const parseInput = (value) => {
            if (!value) return 0;
            // keep the dot as decimal separator, remove thousand separators
            const cleaned = value.replace(/[^0-9.,]/g, '').replace(/\./g, '').replace(/,/g, '.');
            return parseFloat(cleaned) || 0;
        };

        // Function to format currency
        function formatCurrency(value) {
            // Ensure we have a valid number to format
            //const num = parseFloat(value.replace(/[^0-9]/g, '')) || 0;
            //return num.toLocaleString('id-ID');
            let num = value.replace(/[^0-9.,]/g, '').replace(/\./g, '').replace(/,/g, '.');
            num = parseFloat(num) || 0;
            return num.toLocaleString('id-ID');
        }

        // Function to format percentage
        function formatPercentage(value) {
            if (!value) return '';
            const num = parseFloat(value.replace(/[^0-9.]/g, '')) || 0;
            return num.toString();
        }

        // Calculate total nilai pasar wajar
        let totalNilaiPasarWajar = 0;

        // Get all kategori unik elements dynamically
        const kategoriItems = document.querySelectorAll('[id^="luas_"]');



        kategoriItems.forEach(item => {
            const kategori = item.id.replace('luas_', '');
            const luasInput = document.getElementById(`luas_${kategori}`);
            const nilaiInput = document.querySelector(`input[name="nilai_${kategori}_1"]`);
            const outputElement = document.querySelector(`input[name="nilai_${kategori}_2"]`);

            if (luasInput && nilaiInput && outputElement) {
                const luas = parseFloat(luasInput.value.replace(/[^0-9.]/g, '')) || 0;
                const nilai = parseInput(nilaiInput.value);
                const hasil = luas * nilai;

                outputElement.value = formatCurrency(hasil.toString());
                totalNilaiPasarWajar += hasil;
            }
        });

        // Tambahkan perhitungan untuk NPW tambahan
        const npwRows = document.querySelectorAll('.npw-row');
        npwRows.forEach(row => {
            const luasInput = row.querySelector('input[id^="ls_npw_"]');
            const nilaiInput = row.querySelector('input[id^="nilai_npw_"][id$="_1"]');
            const outputElement = row.querySelector('input[id^="nilai_npw_"][id$="_2"]');

            if (luasInput && nilaiInput && outputElement) {
                const luas = parseFloat(luasInput.value.replace(/[^0-9.]/g, '')) || 0;
                const nilai = parseInput(nilaiInput.value);
                const hasil = luas * nilai;

                outputElement.value = formatCurrency(hasil.toString());
                totalNilaiPasarWajar += hasil;
            }
        });

        // Update total nilai pasar wajar
        const totalElement = document.getElementById('total_nilai_pasar_wajar');
        if (totalElement) {

            totalElement.value = formatCurrency(totalNilaiPasarWajar.toString());
        }

        // Bagian Likuidasi
        const persentaseLikuidasiInput = document.getElementById('likuidasi');
        if (persentaseLikuidasiInput) {
            let persentaseLikuidasi = parseInput(persentaseLikuidasiInput.value);
            persentaseLikuidasiInput.value = formatPercentage(persentaseLikuidasiInput.value);

            const totalNilaiPasarLikuidasi = document.querySelector('input[name="likuidasi_nilai_1"]');
            const totalLikuidasi = document.querySelector('input[name="likuidasi_nilai_2"]');

            if (totalNilaiPasarLikuidasi && totalLikuidasi) {
                totalNilaiPasarLikuidasi.value = formatCurrency(totalNilaiPasarWajar.toString());

                // Perhitungan Likuidasi
                const hasilLikuidasi = Math.ceil((persentaseLikuidasi / 100) * totalNilaiPasarWajar / 10) * 10;

                console.log('hasilLikuidasi', hasilLikuidasi);

                totalLikuidasi.value = formatCurrency(hasilLikuidasi.toString());
            }
        }

        // Bagian Asuransi (jika ada)
        const luasBangunanAsuransi = document.getElementById('asuransi_luas_bangunan');
        const hargaPerMeterAsuransi = document.querySelector('input[name="asuransi_nilai_1"]');
        const totalNilaiAsuransi = document.querySelector('input[name="asuransi_nilai_2"]');

        if (luasBangunanAsuransi && hargaPerMeterAsuransi && totalNilaiAsuransi) {
            const luas = parseInput(luasBangunanAsuransi.value);
            const nilai = parseInput(hargaPerMeterAsuransi.value);
            const hasilAsuransi = luas * nilai;

            totalNilaiAsuransi.value = formatCurrency(hasilAsuransi.toString());
        }
    }


    function saveLpjSederhanadanStandard() {
        const form = document.getElementById('form-lpj');
        const formData = new FormData(form);
        showLoadingSwal('Mengirim data ke server...');

        const urlParams = new URLSearchParams(window.location.search);
        const permohonanId = {{ $permohonan->id }};
        const documentId = urlParams.get('dokument');
        const inspeksiId = urlParams.get('inspeksiId');

        const requestUrl =
            `{{ route('penilai.storeLpjSederhanadanStandard') }}?permohonanId=${permohonanId}&inspeksiId=${inspeksiId}&documentId=${documentId}`;
        $.ajax({
            url: requestUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            success: function(response) {
                hideLoadingSwal();
                if (response.success) {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: response.message,
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then((response) => {
                        if (response.isConfirmed) {
                            window.location.reload();
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'Terjadi kesalahan',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
                console.log(response);
            },
            error: function(xhr, status, error) {
                let errors = xhr.responseJSON?.errors;
                $('.alert').text('');
                if (errors) {
                    $.each(errors, function(key, value) {
                        $(`#error-${key}`).text(value[0]);
                        toastrErrorBuild(value[0]);
                    });
                }
                hideLoadingSwal();
                console.log(errors);
            }
        });
    }

    function formatCurrencyInput(input) {
        const value = input.value.replace(/[^0-9]/g, ''); // Hapus karakter non-angka
        if (!value) {
            input.value = ''; // Kosongkan jika tidak ada angka
            return;
        }

        // Format ke mata uang
        const formattedValue = new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR'
        }).format(value);

        input.value = formattedValue;
    }
</script>
