@extends('layouts.main')

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

@section('content')
    <div class="grid gap-5 mx-auto w-full lg:gap-7.5">
        @php
            $senior_officer = null;
            $jenisJaminan = null;
            $tanggalPenilaian = null;
            if ($permohonan->debiture && $permohonan->documents) {
                foreach ($permohonan->documents as $dokumen) {
                    $penilai = $permohonan->penilaian->userPenilai->where('role', 'penilai')->first();
                    $teams = $permohonan->region->teams;

                    $tanggalPenilaian = $permohonan->penilaian->waktu_penilaian;
                    $jenisJaminan = $dokumen->jenisJaminan->name;
                    if ($teams) {
                        foreach ($teams as $team) {
                            $team_users = $team->teamsUsers;
                            // print_r($team_users);
                            if ($team_users) {
                                foreach ($team_users as $team_user) {
                                    $user = $team_user->user;

                                    if ($user && $user->hasRole('senior-officer')) {
                                        $senior_officer = $user;
                                        break 3;
                                    }
                                }
                            }
                        }
                    }
                }
            }

        @endphp
        <form id="formInspeksi" method="POST" enctype="multipart/form-data" class="grid gap-5">
            @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

            <input type="hidden" name="nomor_registrasi" value="{{ $permohonan->nomor_registrasi ?? '' }}">
            <input type="hidden" name="permohonan_id" value="{{ $permohonan->id ?? '' }}">
            <input type="hidden" name="dokument_id" value="{{ request('documentId') }}">

            @include('lpj::assetsku.includenya')
            {{-- @include('lpj::surveyor.components.header')
            @include('lpj::surveyor.components.callReport') --}}
            @php
                $paparan = $permohonan->status === 'proses-paparan' ? 'Paparan' : 'Pelaporan';
            @endphp
            <div class="card">
                <div class="card-header bg-agi-50">
                    <h3 class="uppercase card-title">
                        CALL Report
                    </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' => $paparan]) }}"
                                class="btn btn-xs btn-info">
                                <i class="ki-filled ki-exit-left"></i> Back
                            </a>
                        @elseif (Auth::user()->hasAnyRole(['administrator', 'surveyor']) && 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 gap-5 card-body">
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Kepada</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="text" name="kepada" class="w-full input" placeholder="Masukkan..."
                                value="{{ $callReport['kepada'] ?? old('kepada') }}">
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Dari</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="text" name="dari" class="w-full input" placeholder="Masukkan..."
                                value="{{ $callReport['dari'] ?? ($permohonan->branch->name ?? old('dari')) }}">
                        </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">
                            <input type="text" name="nomor_laporan" class="w-full cursor-not-allowed input"
                                placeholder="Masukkan..." value="{{ $nomorLaporan ?? '' }}" @readonly(true)>
                        </div>
                    </div>
                    {{-- 250109828129/ --}}

                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Tanggal</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="date" name="tanggal" class="w-full input" placeholder="Masukkan..."
                                value="{{ $callReport['tanggal'] ?? '' }}">
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Perihal</label>
                        <div class="flex flex-wrap w-full items-base line">
                            <input type="text" name="perihal" class="w-full input" placeholder="Masukkan..."
                                value="{{ $callReport['perihal'] ?? '' }}">
                        </div>
                    </div>
                </div>
            </div>



            <div class="w-full bg-white rounded-lg border shadow-md card border-agi-100">
                <div class="card-header bg-agi-50">
                    <h1 class="font-medium text-gray-900 uppercase text-md">Menindak lanjuti permintaan <b>
                            {{ $permohonan->tujuanPenilaian->name ?? '' }}</b>, BAG CABang
                        <b>{{ $permohonan->branch->name }}</b>
                        disampaikan hal sebagai berikut:
                    </h1>
                </div>
                <div class="card-body">
                    <div class="grid gap-5 w-full">
                        <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                            <div class="grid gap-2.5 w-full">
                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="nama_debiture" class="form-label max-w-56">Nama Debitur</label>
                                    <div class="flex flex-wrap items-baseline w-full">
                                        <input type="text" id="nama_debiture" name="nama_debiture"
                                            class="w-full cursor-not-allowed input" placeholder="Nama Debiture"
                                            value="{{ $permohonan->debiture->name ?? old('nama_debiture') }}"
                                            @readonly(true)>
                                    </div>
                                </div>


                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="kjjp" class="form-label max-w-56">KJPP</label>
                                    <div class="flex flex-wrap items-baseline w-full">
                                        <input type="text" id="kjjp" name="kjjp"
                                            class="w-full cursor-not-allowed input" placeholder="Masukkan kjjp"
                                            value="{{ preg_replace('/^K\\d+ - /', '', $permohonan->penawaran->nama_kjpp_sebelumnya ?? old('kjjp')) }}
"
                                            @readonly(true)>
                                    </div>
                                </div>
                                <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                                    <label class="form-label max-w-56">Jenis Aset</label>

                                    <div class="flex flex-wrap items-baseline w-full">
                                        <input type="text" id="jenis_asset" name="jenis_asset"
                                            class="w-full cursor-not-allowed input" placeholder="Masukkan jenis_asset"
                                            value="{{ $jenisJaminan ?? old('jenis_asset') }}" @readonly(true)>
                                    </div>
                                </div>


                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="penilai" class="form-label max-w-56">Tanggal Penilaian </label>
                                    <div class="flex flex-wrap items-baseline w-full">
                                        <input type="datetime" id="tanggal_penilaian" name="tanggal_penilaian"
                                            class="w-full cursor-not-allowed input" placeholder="Masukkan Tanggal Penilai"
                                            value="{{ $tanggalPenilaian ?? old('penilai') }}" @readonly(true)>
                                    </div>
                                </div>



                            </div>
                        </div>


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

            <div class="w-full bg-white rounded-lg border shadow-md card border-agi-100">
                <div class="card-header bg-agi-50">
                    <h1 class="font-medium text-gray-900 uppercase text-md">lokasi objek

                    </h1>
                </div>

                <div class="grid gap-2.5 w-full card-body">

                    <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                        <label for="province" class="form-label max-w-56">Provinsi</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="text" id="province" class="w-full cursor-not-allowed input" readonly
                                value="{{ isset($permohonan->debiture->province) ? $permohonan->debiture->province->name : '' }}">
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                        <label for="city" class="form-label max-w-56">Kabupaten/Kota</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="text" id="city" class="w-full cursor-not-allowed input" readonly
                                value="{{ isset($permohonan->debiture->city) ? $permohonan->debiture->city->name : '' }}">
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                        <label for="district" class="form-label max-w-56">Kecamatan</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="text" id="district" class="w-full cursor-not-allowed input" readonly
                                value="{{ isset($permohonan->debiture->district) ? $permohonan->debiture->district->name : '' }}">
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                        <label for="village" class="form-label max-w-56">Desa/Kelurahan</label>
                        <div class="flex flex-wrap items-baseline w-full">
                            <input type="text" id="village" class="w-full cursor-not-allowed input" readonly
                                value="{{ isset($permohonan->debiture->village) ? $permohonan->debiture->village->name : '' }}">
                        </div>
                    </div>
                </div>

            </div>

            <div class="w-full bg-white rounded-lg border shadow-md card border-agi-100">
                <div class="card-header bg-agi-50">
                    <h1 class="font-medium text-gray-900 uppercase text-md">Dokument</h1>
                </div>

                <div class="card-body">
                    @include('lpj::component.detail-jaminan', ['status' => true])
                </div>
            </div>

            <div class="grid grid-cols-1 gap-4 w-full lg:grid-cols-1">

                <!-- Bagian Nilai KJPP -->
                <div class="w-full bg-white rounded-lg border shadow-md card border-agi-100">
                    <div class="card-header bg-agi-50">
                        <h1 class="font-medium text-gray-900 uppercase text-md">Nilai KJPP</h1>
                    </div>
                    <div class="grid gap-5 w-full card-body">
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="lelang-1" class="form-label max-w-56">Lelang ke </label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="lelang-1" name="lelang_kjpp" class="w-full input"
                                    placeholder="Masukkan Lelang" value="{{ $callReport['lelang_kjpp'] ?? '' }}">
                            </div>
                        </div>
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="nilai-pasar-1" class="form-label max-w-56">Nilai Pasar Wajar (NPW)</label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="nilai-pasar-1" name="nilai_pasar_kjpp"
                                    class="w-full input nilai-pasar currency-format" placeholder="Masukkan likuidasi" value="{{ $callReport['nilai_pasar_kjpp'] ?? '' }}">
                            </div>
                        </div>
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="likuidasi-1" class="form-label max-w-56">Nilai Likuidasi(%)</label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="likuidasi-1" name="persentase_likuidasi_kjpp" class="w-full input likuidasi"
                                    placeholder="Masukkan likuidasi dalam bentuk persen" onkeyup="calculateTotal(this)"
                                    data-group="1" value="{{ $callReport['persentase_likuidasi_kjpp'] ?? '' }}">
                            </div>
                        </div>
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="total-likuidasi-1" class="form-label max-w-56">Total Nilai Likuidasi (NL)</label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="total-likuidasi-1" name="hasil_nilai_likuidasi_kjpp"
                                    class="w-full input total-likuidasi currency-format" placeholder="Hasil perhitungan" value="{{ $callReport['hasil_nilai_likuidasi_kjpp'] ?? '' }}">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bagian Nilai Internal -->
                <div class="hidden w-full bg-white rounded-lg border shadow-md card border-agi-100">
                    <div class="card-header bg-agi-50">
                        <h1 class="font-medium text-gray-900 uppercase text-md">Nilai Internal</h1>
                    </div>
                    <div class="grid gap-5 w-full card-body">
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="lelang-2" class="form-label max-w-56">Lelang ke </label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="lelang-2" name="lelang_internal" class="w-full input"
                                    placeholder="Masukkan Lelang" value="{{ $callReport['lelang_internal'] ?? '' }}">
                            </div>
                        </div>
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="nilai-pasar-2" class="form-label max-w-56">Nilai Pasar Wajar (NPW)</label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="nilai-pasar-2" name="nilai_pasar_internal"
                                    class="w-full input nilai-pasar currency-format" placeholder="Masukkan likuidasi" value="{{ $callReport['nilai_pasar_internal'] ?? '' }}">
                            </div>
                        </div>
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="likuidasi-2" class="form-label max-w-56">Nilai Likuidasi(%)</label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="likuidasi-2" name="persentase_likuidasi_internal" class="w-full input likuidasi"
                                    placeholder="Masukkan likuidasi dalam bentuk persen" onkeyup="calculateTotal(this)"
                                    data-group="2" value="{{ $callReport['persentase_likuidasi_internal'] ?? '' }}">
                            </div>
                        </div>
                        <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                            <label for="total-likuidasi-2" class="form-label max-w-56">Total Nilai Likuidasi (NL)</label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input type="text" id="total-likuidasi-2" name="hasil_nilai_likuidasi_internal"
                                    class="w-full input total-likuidasi currency-format" placeholder="Hasil perhitungan" value="{{ $callReport['hasil_nilai_likuidasi_internal'] ?? '' }}">
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            <div class="w-full bg-white rounded-lg border shadow-md card border-agi-100">
                <div class="card-header bg-agi-50">
                    <h1 class="font-medium text-gray-900 uppercase text-md">Penilaian ke lokasi objek telah dilakukan oleh
                        :
                    </h1>
                </div>
                <div class="card-body">
                    <div class="grid gap-5 w-full">

                        <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                            <div class="grid gap-2.5 w-full">
                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="staf" class="form-label max-w-56">Staf Subdit Appraisal </label>
                                    <div class="flex flex-wrap items-baseline w-full">
                                        <input type="text" id="staf" name="staf"
                                            class="w-full cursor-not-allowed input" placeholder="Masukkan Nama Staff"
                                            value="{{ $penilai->userPenilaiTeam->name ?? '' }}" @readonly(true)>
                                    </div>
                                </div>


                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="penilai" class="form-label max-w-56">Pihak KJPP</label>
                                    <div class="flex flex-wrap items-baseline w-full">
                                        <input type="text" id="penilai" name="pihak_kjjpp" class="w-full input"
                                            value="{{  $callReport['pihak_kjjpp'] ?? ($forminspeksi['signature']['kjjp']['name'] ?? '') }}"
                                            placeholder="Masukkan Nama KJPP">
                                    </div>
                                </div>
                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="pihak_bag" class="form-label max-w-56">Pihak BAGI Cab </label>
                                    <div class="flex flex-wrap items-baseline w-full">

                                        <input type="text" id="pihak_bag" name="pihak_bag"
                                            class="w-full cursor-not-allowed input" placeholder="Masukkan Pihak Bag"
                                            value="{{ $permohonan->user->name ?? '' }} || {{ $permohonan->branch->name }}"
                                            @readonly(true)>
                                    </div>
                                </div>

                                <div class="flex flex-wrap gap-2.5 items-baseline w-full lg:flex-nowrap">
                                    <label for="debitur_perwakilan" class="form-label max-w-56">Debitur/perwakilan debitur
                                    </label>

                                    @if (isset($forminspeksi['asset']['debitur_perwakilan']))
                                        @foreach ($forminspeksi['asset']['debitur_perwakilan'] as $item)
                                            <div class="flex flex-wrap items-baseline w-full">
                                                <input type="text" id="debitur_perwakilan" name="debitur_perwakilan"
                                                    class="w-full cursor-not-allowed input" placeholder="Masukkan Penilai"
                                                    value="{{ $item ?? '' }}" @readonly(true)>
                                            </div>
                                        @endforeach
                                    @else
                                        <div class="flex flex-wrap items-baseline w-full">
                                            <input type="text" id="debitur_perwakilan" name="debitur_perwakilan"
                                                class="w-full cursor-not-allowed input" placeholder="Masukkan Penilai"
                                                value="{{ $permohonan->debiture->name ?? '' }}" @readonly(true)>
                                        </div>
                                    @endif

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

            <div class="card">
                <div class="card-header bg-agi-50">
                    <h3 class="uppercase card-title">
                        Informasi yang didapatkan sebagai berikut :
                    </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 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>
            </div>

            <div class="flex gap-2 justify-end" style="margin-right: 20px; margin-top: 20px">
                @if (Auth::user()->hasAnyRole(['senior-officer', 'surveyor', 'administrator','EO Appraisal']))
                    <button type="button" class="btn btn-primary" id="saveButton" onclick="submitData()" {{ $permohonan->status == 'proses-paparan' || $permohonan->status == 'proses-laporan' && Auth::user()->hasAnyRole(['surveyor'])  ? 'disabled' : '' }}>
                        <i class="ki-filled ki-save-2"></i>
                        <span id="saveButtonText">Simpan</span>
                    </button>
                @endif
                @if (Auth::user()->hasAnyRole(['senior-officer', 'EO Appraisal', 'DD Appraisal']))
                    <a class="btn btn-info"
                        href="{{ route('penilai.lampiran') }}?permohonanId={{ request('permohonanId') }}&documentId={{ request('documentId') }}&jaminanId={{ request('jaminanId') }}&statusLpj=1">
                        Lampiran Foto dan Dokument
                    </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-primary"
                        onclick="checkLaporan('{{ $permohonan->id }}', '{{ request('documentId') }}',{{ request('jaminanId') }}, )">
                        <i class="ki-filled ki-printer"></i> Cetak Laporan
                    </a>
                @endif
            </div>
        </form>
    </div>
@endsection
@push('scripts')
    <script type="text/javascript">
        const callReports = @json($forminspeksi);
        console.log('callReport', callReports)


        function formatJson(formElement) {
            const formData = new FormData(formElement);
            const jsonData = {
                kepada: "",
                tanggal: "",
                nomor_laporan: "",
                perihal: "",
                pihak_kjjpp: "",
                dari: "",
                lelang_kjpp: "",
                nilai_pasar_kjpp: "",
                persentase_likuidasi_kjpp: "",
                hasil_nilai_likuidasi_kjpp: "",
                lelang_internal: "",
                nilai_pasar_internal: "",
                persentase_likuidasi_internal: "",
                hasil_nilai_likuidasi_internal: "",

            };


            jsonData.perihal = document.querySelector('input[name="perihal"]')?.value.trim() || "";
            jsonData.pihak_kjjpp = document.querySelector('input[name="pihak_kjjpp"]')?.value.trim() || "";
            jsonData.dari = document.querySelector('input[name="dari"]')?.value.trim() || "";
            jsonData.tanggal = document.querySelector('input[name="tanggal"]')?.value.trim() || "";
            jsonData.kepada = document.querySelector('input[name="kepada"]')?.value.trim() || "";
            jsonData.nomor_laporan = document.querySelector('input[name="nomor_laporan"]')?.value.trim() || "";
            jsonData.lelang_kjpp = document.querySelector('input[name="lelang_kjpp"]')?.value.trim() || "";

            // Ambil nilai lainnya
            jsonData.nilai_pasar_kjpp = cleanCurrencyValue(document.querySelector('input[name="nilai_pasar_kjpp"]')?.value.trim() ||
                "");
            jsonData.persentase_likuidasi_kjpp = cleanCurrencyValue(document.querySelector('input[name="persentase_likuidasi_kjpp"]')?.value
                .trim() || "");
            jsonData.hasil_nilai_likuidasi_kjpp = cleanCurrencyValue(document.querySelector('input[name="hasil_nilai_likuidasi_kjpp"]')
                ?.value.trim() || "");

            jsonData.lelang_internal = document.querySelector('input[name="lelang_internal"]')?.value.trim() || "";
            jsonData.nilai_pasar_internal = cleanCurrencyValue(document.querySelector('input[name="nilai_pasar_internal"]')?.value.trim() ||
                "");
            jsonData.persentase_likuidasi_internal = cleanCurrencyValue(document.querySelector('input[name="persentase_likuidasi_internal"]')?.value
                .trim() || "");
            jsonData.hasil_nilai_likuidasi_internal = cleanCurrencyValue(document.querySelector('input[name="hasil_nilai_likuidasi_internal"]')
                ?.value.trim() || "");

            return jsonData;
        }

        function submitData() {
            showLoadingSwal('Mengirim data ke server...');
            const formElement = document.querySelector('form');
            // console.log('Form data entries:', Array.from(formData.entries()));
            const urlParams = new URLSearchParams(window.location.search);
            const permohonanId = {{ $permohonan->id }};
            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.storeCallReport') }}?permohonan_id=${permohonanId}&dokument_id=${documentId}`;


            const jsonData = formatJson(formElement);
            $.ajax({
                url: requestUrl,
                type: 'POST',
                data: JSON.stringify({
                    permohonan_id: permohonanId,
                    dokument_id: documentId,

                    data: 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);
                }
            });
        }
    </script>
    <script>
        function calculateTotal(event) {
            const group = event.dataset.group;

            // Ambil elemen-elemen terkait berdasarkan group
            const nilaiPasarInput = document.querySelector(`#nilai-pasar-${group}`);
            const nilaiLikuidasi = document.querySelector(`#likuidasi-${group}`);
            const totalLikuidasi = document.querySelector(`#total-likuidasi-${group}`);

            const cleanNilaiPasar = cleanCurrencyValue(nilaiPasarInput.value);
            let cleanLikuidasi = cleanCurrencyValue(nilaiLikuidasi.value);

            // Batasi likuidasi maksimal hingga 100
            cleanLikuidasi = Math.min(parseFloat(cleanLikuidasi) || 0, 100);

            // Format nilai likuidasi dengan simbol %
            nilaiLikuidasi.value = cleanLikuidasi;

            // Konversi ke angka untuk perhitungan
            const nilaiPasar = parseFloat(cleanNilaiPasar) || 0;
            const likuidasi = cleanLikuidasi / 100; // Konversi persentase ke desimal

            // Hitung total likuidasi
            const totalNilaiLikuidasi = nilaiPasar * likuidasi;

            // Tampilkan hasil dengan format yang benar
            totalLikuidasi.value = formatCurrency(totalNilaiLikuidasi.toString());
        }


        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>
    @include('lpj::surveyor.js.utils')
@endpush
