@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render(request()->route()->getName()) }}
@endsection

@section('content')
    <style>
        .list-decimal {
            list-style-type: decimal;
            margin: 0;
            padding-left: 1.25rem;
            line-height: 1.6;
            font-family: Arial, sans-serif;
            font-size: 16px;
            color: #333333;
        }

        .list-decimal li {
            margin-bottom: 0.5rem;
        }
    </style>
    @include('lpj::assetsku.includenya')
    @php
        $paparan = $permohonan->status === 'proses-paparan' ? 'Paparan' : 'Pelaporan';
    @endphp
    <div class="grid gap-5 mx-auto w-full lg:gap-7.5">

        <form id="formResume" method="POST" class="grid gap-5 w-full">
            @csrf

            @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) }}">
                    @endif
                @endif
            @endforeach
            <div class="card">
                <div class="card-header bg-agi-50">
                    <h3 class="uppercase card-title">
                        Data Jaminan
                    </h3>
                    @php
                        use Illuminate\Support\Facades\Route;
                    @endphp
                    <div class="flex gap-2 items-center">

                        @if (Auth::user()->hasAnyRole(['administrator', 'senior-officer', 'EO Appraisal', 'DD Appraisal']) &&
                                Route::currentRouteName('otorisator.show'))
                            <a href="{{ route('otorisator.show', ['id' => $permohonan->id, 'type' => request('header') ?? 'index']) }}"
                                class="btn btn-xs btn-info">
                                <i class="ki-filled ki-exit-left"></i> Back
                            </a>
                        @elseif (Auth::user()->hasAnyRole(['administrator', 'surveyor','penilai']) && Route::currentRouteName('penilai.show'))
                            <a href="{{ route('penilai.show', $permohonan->id) }}" class="btn btn-xs btn-info">
                                <i class="ki-filled ki-exit-left"></i> Back
                            </a>
                        @endif

                    </div>
                </div>
                <div class="grid grid-cols-2 gap-5 card-body">
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Nama Debitur</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            @if (isset($permohonan->debiture))
                                <p class="text-gray-700 text-2sm">{{ $permohonan->debiture->name }}</p>
                            @endif
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Alamat Object</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            @foreach ($permohonan->documents as $dokumen)
                                <span class="text-gray-700 text-2sm">
                                    {{ formatAlamat($dokumen) }}
                                </span>
                            @endforeach
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Nomor Registrasi</label>
                        <div class="flex flex-wrap w-full items-base line">
                            <p class="text-gray-700 text-2sm">{{ $permohonan->nomor_registrasi }}</p>
                        </div>
                    </div>



                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Cab/Direktorat</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            @if (isset($permohonan->branch))
                                <p class="text-gray-700 text-2sm">{{ $permohonan->branch->name }}</p>
                            @endif
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Nomor Laporan</label>
                        <div class="flex flex-wrap w-full items-base line">
                            <p class="text-gray-700 text-2sm">{{ $nomorLaporan ?? '' }}</p>
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">AO</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            @if (isset($permohonan->user))
                                <p class="text-gray-700 text-2sm">{{ $permohonan->user->name }}</p>
                            @endif
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Tanggal Resume</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="date" name="tanggal_resume" class="w-full input" placeholder="Masukkan..."
                                value="{{ $resumeData['tanggal_resume'] ?? '' }}">
                        </div>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header bg-agi-50">
                    <h3 class="uppercase card-title">
                        faktor
                    </h3>
                </div>
                <div class="grid gap-5 card-body">
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Faktor Positif</label>
                        <div id="fakta-positif-container" class="flex flex-wrap items-baseline w-full">
                            @if (!empty($forminspeksi['fakta']['fakta_positif']))
                                @foreach ($forminspeksi['fakta']['fakta_positif'] as $index => $positif)
                                    <div class="flex gap-2 items-center mt-2 w-full fakta_positif textarea-group">
                                        <textarea class="mt-2 textarea" name="fakta_positif[]" rows="10">{{ old("fakta_positif.$index", $positif) }}</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 fakta_positif textarea-group">
                                    <textarea class="mt-2 textarea" name="fakta_positif[]" rows="10">{{ old('fakta_positif.0', '') }}</textarea>
                                    <button class="btn btn-danger btn-sm remove-btn" type="button" style="display: none;">
                                        <i class="ki-outline ki-trash"></i>
                                    </button>
                                </div>
                            @endif
                            <button type="button" class="mt-5 btn btn-primary btn-sm"
                                onclick="addClonableItem('fakta-positif-container', 'fakta_positif')">
                                <i class="ki-outline ki-plus"></i>
                            </button>
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Faktor Negatif</label>
                        <div id="fakta-negatif-container" class="flex flex-wrap items-baseline w-full">
                            @if (!empty($forminspeksi['fakta']['fakta_negatif']))
                                @foreach ($forminspeksi['fakta']['fakta_negatif'] as $index => $negatif)
                                    <div class="flex gap-2 items-center mt-2 w-full fakta_negatif textarea-group">
                                        <textarea class="mt-2 textarea" name="fakta_negatif[]" rows="10">{{ old("fakta_negatif.$index", $negatif) }}</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 fakta_negatif textarea-group">
                                    <textarea class="mt-2 textarea" name="fakta_negatif[]" rows="10">{{ old('fakta_negatif.0', $forminspeksi['fakta']['fakta_negatif'][0] ?? '') }}</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-fakta_negatif" class="text-sm alert text-danger"></em>
                                </div>
                            @endif
                            <button type="button" class="mt-5 btn btn-primary btn-sm"
                                onclick="addClonableItem('fakta-negatif-container', 'fakta_negatif')">
                                <i class="ki-outline ki-plus"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>


            <div class="min-w-full border card border-agi-100">
                <div class="card-header bg-agi-50">
                    <h3 class="uppercase card-title">
                        KESIMPULAN NILAI PASAR WAJAR
                    </h3>
                </div>
                <div class="grid gap-5 card-body">

                    <div class="gap-5 gird">
                        <label class="form-label max-w-56">SESUAI FISIK</label>
                        <div class="flex flex-wrap items-baseline mt-5 w-full">
                            <table class="table text-sm font-medium text-gray-700 align-middle table-auto table-border">
                                <thead>
                                    <tr>
                                        <th class="text-center">Sertipikat</th>
                                        <th class="text-center">Luas Tanah</th>
                                        <th class="text-center">Luas Bangunan</th>
                                        <th class="text-center">Nilai Pasar Wajar</th>

                                    </tr>
                                </thead>
                                </thead>
                                <tbody>
                                    @if (!empty($resumeData['fisik']))
                                        @foreach ($resumeData['fisik'] as $item)
                                            <tr>
                                                <td class="text-center">
                                                    <input type="text" name="fisik_sertifikat[]"
                                                        class="input number-format" value="{{ $item['sertifikat'] }}">
                                                </td>
                                                <td class="text-center">
                                                    <input type="text" name="fisik_luas_tanah[]"
                                                        class="input number-format" value="{{ $item['luas_tanah'] }}">
                                                </td>
                                                <td class="text-center"> <input type="text"
                                                        name="fisik_luas_bangunan[]" value="{{ $item['luas_bangunan'] }}"
                                                        class="input number-format"></td>
                                                <td class="text-center">
                                                    <input type="text" name="fisik_nilai[]"
                                                        class="input currency-format nilai-pasar"
                                                        value="{{ $item['nilai'] }}">
                                                </td>

                                            </tr>
                                        @endforeach
                                    @else
                                        <tr>
                                            <td class="text-center">
                                                <input type="text" name="fisik_sertifikat[]"
                                                    class="input number-format">
                                            </td>

                                            @if (isset($permohonan->documents))
                                                @foreach ($permohonan->documents as $item)
                                                    @php
                                                        $luas_tanah = '';
                                                        $luas_bangunan = '';
                                                        if ($item->detail) {
                                                            foreach ($item->detail as $luas) {
                                                                if (
                                                                    isset($luas->name) &&
                                                                    $luas->name === 'Sertifikat'
                                                                ) {
                                                                    $details = json_decode($luas->details, true);
                                                                    $luas_tanah = isset($details['luas_tanah'])
                                                                        ? $details['luas_tanah']
                                                                        : '';
                                                                    break;
                                                                }

                                                                if (isset($luas->name) && $luas->name === 'IMB') {
                                                                    $details = json_decode($luas->details, true);
                                                                    $luas_bangunan = isset($details['luas_bangunan'])
                                                                        ? $details['luas_bangunan']
                                                                        : '';
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    @endphp
                                                @endforeach
                                            @endif
                                            <td class="text-center">
                                                <input type="text" name="fisik_luas_tanah[]"
                                                    class="input number-format" value="{{ $luas_tanah }}">
                                            </td>
                                            <td class="text-center"> <input type="text" name="fisik_luas_bangunan[]"
                                                    class="input number-format" value="{{ $luas_bangunan }}"></td>
                                            <td class="text-center">
                                                <input type="text" name="fisik_nilai[]"
                                                    class="input currency-format nilai-pasar">
                                            </td>

                                        </tr>
                                    @endif
                                </tbody>
                            </table>
                        </div>
                    </div>

                    @if (!empty($resumeData['tambahan']))
                        @foreach ($resumeData['tambahan'] as $counter => $item)
                            <div id="kesimpulan" class="gap-5 gird">

                                <div class="flex flex-wrap items-baseline w-full">

                                    <table
                                        class="table mt-5 text-sm font-medium text-gray-700 align-middle table-auto table-border">
                                        <input class="input" name="tambahan_nama_kesimpulan[]"
                                            placeholder="Masukkan Nama Kesimpulan" type="text"
                                            value="{{ $item['tambahan_nama_kesimpulan'] ?? '' }}">


                                        <thead>

                                            <tr>
                                                <th class="text-center">Sertipikat</th>
                                                <th class="text-center">Luas Tanah</th>
                                                <th class="text-center">Luas Bangunan</th>
                                                <th class="text-center">Nilai Pasar Wajar</th>

                                            </tr>
                                        </thead>
                                        </thead>
                                        <tbody>

                                            <tr>
                                                <td class="text-center">
                                                    <input type="text" name="tambahan_sertifikat[]"
                                                        class="input number-format" value="{{ $item['sertifikat'] }}">
                                                </td>
                                                <td class="text-center">
                                                    <input type="text" name="tambahan_luas_tanah[]"
                                                        class="input number-format" value="{{ $item['luas_tanah'] }}">
                                                </td>
                                                <td class="text-center">
                                                    <input type="text" name="tambahan_luas_bangunan[]"
                                                        class="input number-format" value="{{ $item['luas_bangunan'] }}">
                                                </td>
                                                <td class="text-center">
                                                    <input type="text" name="tambahan_nilai[]"
                                                        class="input currency-format nilai-pasar"
                                                        value="{{ $item['nilai'] }}">
                                                </td>

                                            </tr>

                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        @endforeach
                    @endif
                    <div id="kesimpulan" class="grid gap-5 w-full"></div>
                    <div class="">
                        <button type="button" class="mt-5 btn btn-primary btn-sm" onclick="tambahKesimpulanNilai()">
                            <i class="ki-outline ki-plus"></i>
                            Kesimpulan Nilai
                        </button>
                    </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-container" class="flex flex-wrap gap-2.5 items-baseline w-full">
                                @if (!empty($forminspeksi['fakta']['keterangan']) && is_array($forminspeksi['fakta']['keterangan']))
                                    @foreach ($forminspeksi['fakta']['keterangan'] as $index => $item)
                                        <div class="flex gap-2 items-center mt-2 w-full keterangan textarea-group">
                                            <textarea name="keterangan[]" class="mt-2 textarea" placeholder="Masukkan catatan penting" rows="10">{{ old("keterangan.$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 textarea-group">
                                        <textarea name="keterangan[]" 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" class="text-sm alert text-danger"></em>
                                    </div>
                                @endif
                            </div>
                            <button type="button" onclick="addClonableItem('keterangan-container', 'keterangan')"
                                class="mt-5 btn btn-primary btn-sm">
                                <i class="ki-outline ki-plus"></i>
                            </button>
                        </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">DISCLAIMER
                        </label>
                        <div class="flex gap-2 w-full input-group">
                            <ol class="pl-5 space-y-2 list-decimal">
                                <li>LAPORAN RESUME INI DIKELUARKAN DIKARENAKAN BELUM DILAKUKANNYA PEMBAYARAN BIAYA PENILAIAN
                                    JAMINAN
                                </li>
                                <li>LAPORAN RESUME INI TIDAK BISA DIJADIKAN SEBAGAI DASAR PENGAJUAN DAN ATAU PENCAIRAN
                                    KREDIT, LAPORAN YANG
                                    DIGUNAKAN TETAP WAJIB BERUPA LAPORAN PENILAIAN JAMINAN (LPJ)
                                </li>
                                <li>DETAIL PER METER TANAH DAN BANGUNAN, SARANA PELENGKAP DLL AKAN TERCATAT DI LAPORAN
                                    PENILAIAN JAMINAN
                                    (LPJ) NANTI
                                </li>
                                <li>LAPORAN RESUME INI HANYA DIGUNAKAN UNTUK KEPENTINGAN INTERNAL BAGI
                                </li>
                                <li>LAPORAN RESUME INI HANYA BERLAKU 14 HARI KALENDER TERHITUNG DARI TANGGAL RESUME INI
                                    DIBUAT SESUAI ATURAN
                                    YANG BERLAKU, APABILA LEWAT MAKA HARUS DILAKUKAN ORDER ULANG SESUAI PROSEDUR YANG
                                    BERLAKU
                                </li>
                                <li class="uppercase">Apabila sudah melewati 6 bulan, maka harus penilaian ulang kembali
                                </li>
                            </ol>
                        </div>
                    </div>

                    <div class="flex gap-5 justify-end card-footer">

                        @if (Auth::user()->hasAnyRole(['senior-officer', 'surveyor', 'penilai', 'administrator']))
                            <button type="button" class="btn btn-primary" onclick="saveResume()"
                                {{ $permohonan->status == 'proses-paparan' || ($permohonan->status == 'proses-laporan' && Auth::user()->hasAnyRole(['surveyor','penilai'])) ? 'disabled' : '' }}>
                                <i class="ki-filled ki-save-2"></i>
                                Simpan</button>
                        @endif

                        @if (Auth::user()->hasAnyRole(['senior-officer', 'EO Appraisal', 'DD Appraisal', 'administrator']))
                            <a class="btn btn-info"
                                href="{{ route('penilai.lampiran') }}?permohonanId={{ request('permohonanId') }}&documentId={{ request('documentId') }}&jaminanId={{ request('jaminanId') }}&statusLp
j=1&statusLpj=1&header={{ request('header') }}">Lampiran
                                Foto dan Dokumen
                            </a>
                            <a href="{{ route('surveyor.print_out_inspeksi', ['permohonan_id' => $permohonan->id, 'dokument_id' => request('documentId'), 'jenis_jaminan_id' => request('jaminanId')]) }}"
                                class="btn btn-light">
                                <i class="ki-filled ki-printer"></i>Cetak Hasil Inspeksi
                            </a>
                            <a class="btn btn-success"
                                onclick="checkLaporan('{{ $permohonan->id }}', '{{ request('documentId') }}', {{ request('jaminanId') }}, )">
                                <i class="ki-filled ki-printer"></i> Cetak Laporan
                            </a>
                        @endif
                    </div>
                </div>
        </form>

    </div>
@endsection
@include('lpj::surveyor.js.utils')
<script type="text/javascript">
    let data = @json($resumeData ?? 0);
    console.log(data);
    let counter = 3;

    function tambahKesimpulanNilai() {
        const kesimpulan = document.getElementById('kesimpulan');

        kesimpulan.innerHTML += `
        <div class="grid gap-5 mt-5 w-full" id="kesimpulan-${counter}">


            <div class="flex flex-wrap items-baseline w-full">
                <div class="w-full tabel-container">
                    <table class="table mt-5 text-sm font-medium text-gray-700 align-middle table-auto table-border">

                                    <input type="text" name="tambahan_nama_kesimpulan[]"
                                        class="input number-format"
                                        placeholder="Masukkan Nama Kesimpulan.."
                                        >

                        <thead>

                            <tr>
                                <th class="text-center">Sertipikat</th>
                                <th class="text-center">Luas Tanah</th>
                                <th class="text-center">Luas Bangunan</th>
                                <th class="text-center">Nilai Pasar Wajar</th>

                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>

                                <td class="text-center">
                                    <input type="text" name="tambahan_sertifikat[]"
                                        class="input number-format">
                                </td>
                                <td class="text-center">
                                    <input type="text" name="tambahan_luas_tanah[]"
                                        class="input number-format">
                                </td>
                                <td class="text-center">
                                    <input type="text" name="tambahan_luas_bangunan[]"
                                        class="input number-format">
                                </td>
                                <td class="text-center">
                                    <input type="text" name="tambahan_nilai[]"
                                        class="input currency-format nilai-pasar">
                                </td>


                                <td class="text-center">
                                    <button type="button" class="btn btn-danger" onclick="deleteRow(this)">Delete</button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

        const newCurrencyInputs = kesimpulan.querySelectorAll(`#kesimpulan-${counter} .currency-format`);
        newCurrencyInputs.forEach(input => {
            input.addEventListener('input', function() {
                handleCurrencyInput(this);
            });

            // Format initial value jika ada
            if (input.value) {
                input.value = formatCurrency(input.value);
            }
        });
        counter++;
    }

    function deleteRow(button) {
        const rowContainer = button.closest('.grid');
        rowContainer.remove();
        updateLabelNumbers();
    }

    function updateLabelNumbers() {
        const labels = document.querySelectorAll('.kesimpulan');
        labels.forEach((label, index) => {
            // Update setiap label dengan nomor yang benar
            label.textContent = `${index + 1}. SESUAI IMB`;
        });
    }

    function saveResume() {
        showLoadingSwal('Mengirim data keserver ...');

        const formElement = document.querySelector('form');
        const jsonData = formToJson(formElement);
        console.log('Data dalam format JSON:', JSON.stringify(jsonData, null, 2));

        const urlParams = new URLSearchParams(window.location.search); // Mengambil query parameters dari URL
        const permohonanId = urlParams.get('permohonanId');
        const documentId = urlParams.get('documentId');
        const faktaPositif = Array.from(document.querySelectorAll('[name="fakta_positif[]"]'))
            .map(textarea => textarea.value.trim())
            .filter(value => value !== '');

        const faktaNegatif = Array.from(document.querySelectorAll('[name="fakta_negatif[]"]'))
            .map(textarea => textarea.value.trim())
            .filter(value => value !== '');
        const keterangan = Array.from(document.querySelectorAll('[name="keterangan[]"]'))
            .map(textarea => textarea.value.trim())
            .filter(value => value !== '');

        const action = Array.from(document.querySelectorAll('input[name="action"]'))
            .map(input => input.value)
            .join(',') || "";
        const type = Array.from(document.querySelectorAll('input[name="type"]'))
            .map(input => input.value)
            .join(',') || "";

        const requestUrl =
            `{{ route('penilai.storeResume') }}`;


        $.ajax({
            url: requestUrl,
            type: 'POST',
            data: JSON.stringify({
                permohonan_id: permohonanId,
                dokument_id: documentId,
                resume: jsonData,
                fakta_positif: faktaPositif,
                fakta_negatif: faktaNegatif,
                action: action,
                type: type,
                keterangan: keterangan

            }),
            contentType: 'application/json',


            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]);
                    });
                    // toastrErrorBuild(error);
                }
                hideLoadingSwal();
                console.log(errors);
            }
        });
    }

    function formToJson(formElement) {
        const formData = new FormData(formElement);
        const jsonData = {
            tanggal_resume: "",
            fisik: [],
            tambahan: []
        };


        // Ambil data fisik
        document.querySelectorAll('table tbody tr').forEach(row => {
            const fisikData = {
                sertifikat: row.querySelector('input[name="fisik_sertifikat[]"]')?.value || "",
                luas_tanah: row.querySelector('input[name="fisik_luas_tanah[]"]')?.value || "",
                luas_bangunan: row.querySelector('input[name="fisik_luas_bangunan[]"]')?.value || "",
                nilai: cleanCurrencyValue(row.querySelector('input[name="fisik_nilai[]"]')?.value || "")
            };
            if (fisikData.sertifikat) {
                jsonData.fisik.push(fisikData);
            }
        });



        document.querySelectorAll('#kesimpulan > div').forEach(row => {
            const imbData = {
                tambahan_nama_kesimpulan: row.querySelector('input[name="tambahan_nama_kesimpulan[]"]')
                    ?.value || "",
                sertifikat: row.querySelector('input[name="tambahan_sertifikat[]"]')?.value || "",
                luas_tanah: row.querySelector('input[name="tambahan_luas_tanah[]"]')?.value || "",
                luas_bangunan: row.querySelector('input[name="tambahan_luas_bangunan[]"]')?.value || "",
                nilai: cleanCurrencyValue(row.querySelector('input[name="tambahan_nilai[]"]')?.value || "")
            };
            console.log(imbData);
            if (imbData.sertifikat) {
                jsonData.tambahan.push(imbData);
            }
        });

        const tanggal_resume = formElement.querySelector('input[name="tanggal_resume"]')?.value || "";
        jsonData.tanggal_resume = tanggal_resume;

        return jsonData;
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Initialize currency format for existing inputs
        document.querySelectorAll('.currency-format').forEach(input => {
            input.addEventListener('input', function() {
                handleCurrencyInput(this);
            });

            // Format initial values if they exist
            if (input.value) {
                input.value = formatCurrency(input.value);
            }
        });
    });
</script>
