<form action="{{ isset($document->id) ? route('debitur.jaminan.update', ['id'=>$debitur->id,'jaminan'=>$document->id]) : route('debitur.jaminan.store',$debitur->id) }}" method="POST" class="grid gap-5" enctype="multipart/form-data">
    @if(isset($document->id))
        @method('PUT')
    @endif
    @csrf
    <input type="hidden" name="permohonan_id" value="{{ $document->permohonan_id ?? request()->get('permohonan_id') }}">
    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
        <label class="form-label max-w-56">
            Debitur
        </label>
        <div class="flex flex-wrap items-baseline w-full">
            <input type="hidden" name="debiture_id" value="{{ $debitur->id ?? '' }}">
            <p class="text-base text-gray-700">
                {{ $debitur->name }} |
                {{ formatAlamat($debitur) }}
            </p>
        </div>
    </div>
    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
        <label class="form-label max-w-56">
            Nomor Permohonan
        </label>
        <div class="flex flex-wrap items-baseline w-full">
            <p class="text-base text-gray-700 font-bold">
                {{ $permohonan->nomor_registrasi ?? "-" }}
            </p>
        </div>
    </div>
    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
        <label class="form-label max-w-56">
            Pemilik Jaminan
        </label>
        <div class="flex flex-wrap items-baseline w-full">
            <div class="input-group w-full">
                <select onchange="changePemilikJaminan()" class="input tomselect w-full @error('branch_id') border-danger bg-danger-light @enderror" name="pemilik_jaminan_id" id="pemilik_jaminan_id">
                    <option value="">Pilih Pemilik Jaminan</option>
                    <option value="0">Sama Dengan Debitur</option>
                    <option value="00">Tidak Sama Dengan Debitur</option>
                    @if(isset($pemilikJaminan))
                        @foreach($pemilikJaminan as $pemilik)
                            @if(isset($document))
                                <option value="{{ $pemilik->id }}" {{ isset($document->pemilik_jaminan_id) && $document->pemilik_jaminan_id == $pemilik->id?'selected' : '' }}>
                                    {{ $pemilik->name }}
                                </option>
                            @else
                                <option value="{{ $pemilik->id }}">
                                    {{ $pemilik->name }}
                                </option>
                            @endif
                        @endforeach
                    @endif
                </select>
            </div>
            @error('pemilik_jaminan_id')
            <em class="alert text-danger text-sm">{{ $message }}</em>
            @enderror
            <fieldset id="pemilik_jaminan" class="hidden border border-solid border-gray-300 p-3 w-full mt-5 grid gap-5">
                <legend class="text-sm">Pemilik Jaminan</legend>
                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label class="form-label max-w-56">
                        Hubungan Pemilik Jaminan
                    </label>
                    <div class="flex flex-wrap items-baseline w-full">
                        <select class="input tomselect w-full @error('branch_id') border-danger bg-danger-light @enderror" name="hubungan_pemilik_jaminan_id" id="hubungan_pemilik_jaminan_id">
                            <option value="">Pilih Hubungan Pemilik Jaminan</option>
                            @if(isset($hubunganPemilik))
                                @foreach($hubunganPemilik as $hubungan)
                                    @if(isset($pemilik))
                                        <option value="{{ $hubungan->id }}" {{ isset($pemilik->hubungan_pemilik_jaminan_id) && $pemilik->hubungan_pemilik_jaminan_id == $hubungan->id?'selected' : '' }}>
                                            {{ $hubungan->name }}
                                        </option>
                                    @else
                                        <option value="{{ $hubungan->id }}">
                                            {{ $hubungan->name }}
                                        </option>
                                    @endif
                                @endforeach
                            @endif
                        </select>
                        @error('hubungan_pemilik_jaminan_id')
                        <em class="alert text-danger text-sm">{{ $message }}</em>
                        @enderror
                    </div>
                </div>
                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label class="form-label max-w-56">
                        Nama Lengkap
                    </label>
                    <div class="flex flex-wrap items-baseline w-full">
                        <div class="flex flex-col lg:flex-row gap-2 w-full">
                            <div class="flex flex-wrap items-baseline w-full">
                                <input class="input  @error('pemilik_name') border-danger bg-danger-light @enderror" type="text " id="pemilik_name" name="pemilik_name" value="{{ $pemilik->name ?? '' }}" placeholder="Nama Pemilik Jaminan">
                                @error('pemilik_name')
                                <em class="alert text-danger text-sm">{{ $message }}</em>
                                @enderror
                            </div>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input class="input  @error('nomor_id') border-danger bg-danger-light @enderror" type="number" name="nomor_id" value="{{ $debitur->nomor_id ?? '' }}" placeholder="Nomor ID/KTP">
                                @error('nomor_id')
                                <em class="alert text-danger text-sm">{{ $message }}</em>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>
                <div id="nama_sertifikat">

                </div>
                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label class="form-label max-w-56">
                        &nbsp;
                    </label>
                    <div class="flex flex-wrap items-baseline w-full">
                        <button type="button" id="tambah_sertifikat" class="btn btn-primary btn-xs">Tambah Nama di Sertifikat</button>
                    </div>
                </div>
            </fieldset>
        </div>
    </div>
    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
        <label class="form-label max-w-56">
            Jenis Jaminan
        </label>
        <div class="flex flex-wrap items-baseline w-full">
            @if(isset($document->id))
                <input type="hidden" name="jenis_jaminan_id" value="{{ $document->jenis_jaminan_id }}">
            @endif
            <select onchange="getLegalitasJaminan()" class="input tomselect w-full @error('branch_id') border-danger bg-danger-light @enderror" name="jenis_jaminan_id" id="jenis_jaminan_id">
                <option value="">Pilih Jenis Jaminan</option>
                @foreach($jenisJaminan as $row)
                    @if(isset($document))
                        <option value="{{ $row->id }}" {{ isset($document->jenis_jaminan_id) && $document->jenis_jaminan_id == $row->id?'selected' : '' }}>
                            {{ $row->name }}
                        </option>
                    @else
                        <option value="{{ $row->id }}">{{ $row->name }}</option>
                    @endif
                @endforeach
            </select>
            @error('jenis_jaminan_id')
            <em class="alert text-danger text-sm">{{ $message }}</em>
            @enderror
        </div>
    </div>

    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
        <label class="form-label max-w-56">
            Alamat
        </label>
        <div class="flex flex-wrap items-baseline w-full">
            <div class="flex flex-col lg:flex-row gap-2 w-full">
                <div class="flex flex-wrap items-baseline w-full">
                    <select id="province_code" name="province_code" class="select w-full @error('province_code') border-danger bg-danger-light @enderror">
                        <option value="">Select Province</option>
                        @foreach($provinces as $province)
                            @if(isset($document))
                                <option value="{{ $province->code }}" {{ isset($document->province_code) && $document->province_code == $province->code?'selected' : '' }}>
                                    {{ $province->name }}
                                </option>
                            @else
                                <option value="{{ $province->code }}">
                                    {{ $province->name }}
                                </option>
                            @endif
                            ;
                        @endforeach
                    </select>
                    @error('province_code')
                    <em class="alert text-danger text-sm">{{ $message }}</em>
                    @enderror
                </div>
                <div class="flex flex-wrap items-baseline w-full">
                    <select id="city_code" name="city_code" class="select w-full @error('city_code') border-danger bg-danger-light @enderror">
                        <option value="">Select City</option>
                        @if(isset($cities))
                            @foreach($cities as $city)
                                @if(isset($document))
                                    <option value="{{ $city->code }}" {{ isset($document->city_code) && $document->city_code == $city->code?'selected' : '' }}>
                                        {{ $city->name }}
                                    </option>
                                @else
                                    <option value="{{ $city->code }}">
                                        {{ $city->name }}
                                    </option>
                                @endif
                            @endforeach

                        @endif
                    </select>
                    @error('city_code')
                    <em class="alert text-danger text-sm">{{ $message }}</em>
                    @enderror
                </div>
            </div>
            <div class="flex flex-col lg:flex-row gap-2 w-full mt-2 lg:mt-5">
                <div class="flex flex-wrap items-baseline w-full">
                    <select id="district_code" name="district_code" class="select w-full @error('district_code') border-danger bg-danger-light @enderror">
                        <option value="">Select District</option>
                        @if(isset($districts))
                            @foreach($districts as $district)
                                @if(isset($document))
                                    <option value="{{ $district->code }}" {{ isset($document->district_code) && $document->district_code == $district->code?'selected' : '' }}>
                                        {{ $district->name }}
                                    </option>
                                @else
                                    <option value="{{ $district->code }}">
                                        {{ $district->name }}
                                    </option>
                                @endif
                            @endforeach

                        @endif
                    </select>
                    @error('district_code')
                    <em class="alert text-danger text-sm">{{ $message }}</em>
                    @enderror
                </div>
                <div class="flex flex-wrap items-baseline w-full">
                    <select id="village_code" name="village_code" class="select w-full @error('district_code') border-danger bg-danger-light @enderror">
                        <option value="">Select Village</option>
                        @if(isset($villages))
                            @foreach($villages as $village)
                                @if(isset($document))
                                    <option value="{{ $village->code }}" {{ isset($document->village_code) && $document->village_code == $village->code?'selected' : '' }}>
                                        {{ $village->name }}
                                    </option>
                                @else
                                    <option value="{{ $village->code }}">
                                        {{ $village->name }}
                                    </option>
                                @endif
                            @endforeach

                        @endif
                    </select>
                    @error('district_code')
                    <em class="alert text-danger text-sm">{{ $message }}</em>
                    @enderror
                </div>
                <div class="flex flex-wrap items-baseline w-full">
                    <input class="input  @error('postal_code') border-danger bg-danger-light @enderror" type="number" id="postal_code" name="postal_code" value="{{ $document->postal_code ?? '' }}" placeholder="Postal Code">
                    @error('postal_code')
                    <em class="alert text-danger text-sm">{{ $message }}</em>
                    @enderror
                </div>
            </div>
            <div class="flex flex-row w-full mt-2 lg:mt-5">
                <textarea class="textarea  @error('address') border-danger bg-danger-light @enderror" rows="3" type="number" id="address" name="address">{{ $document->address ?? '' }}</textarea>
                @error('address')
                <em class="alert text-danger text-sm">{{ $message }}</em>
                @enderror
            </div>
        </div>
    </div>

    <div id="doctainer" class="grid gap-5">
        @if(isset($document->id))
            @php $n = 0; $p_index = 0; @endphp
            @foreach($document->detail as $detail)
                <input type="hidden" name="detail_dokumen_jaminan_id[]" value="{{ $detail->id }}">
                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label class="form-label max-w-56 font-bold">
                        {{ $n + 1 }}. {{ $detail->jenisLegalitasJaminan->name }}
                    </label>
                    <input type="hidden" name="jenis_legalitas_jaminan_id[]" value="{{ $detail->jenis_legalitas_jaminan_id }}">
                    <button type="button" class="btn btn-danger btn-sm" onclick="clearDetail({{ $detail->id }})">
                        <i class="ki-duotone ki-trash-square fs-2">
                            <span class="path1"></span>
                            <span class="path2"></span>
                            <span class="path3"></span>
                            <span class="path4"></span>
                        </i>
                        Reset
                    </button>
                </div>

                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label class="form-label max-w-56">
                        Nama Dokumen
                    </label>
                    <div class="flex flex-wrap items-baseline w-full">
                        <input class="input " type="text" id="name" name="name[]" value="{{ $detail->name ?? "" }}" placeholder="Nomor">
                    </div>
                </div>
                <div id="document-container-{{ $n }}">
                    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                        <label class="form-label max-w-56">
                            Dokumen Jaminan
                        </label>
                        <div class="flex flex-wrap items-baseline w-full">
                            @if(isset($detail->dokumen_jaminan))
                                @php
                                    $dokumen_jaminan = is_array(json_decode($detail->dokumen_jaminan)) ? json_decode($detail->dokumen_jaminan) : [$detail->dokumen_jaminan];
                                    $dokumen_nomor = is_array(json_decode($detail->dokumen_nomor)) ? json_decode($detail->dokumen_nomor) : ($detail->dokumen_nomor ? [$detail->dokumen_nomor] : []);
                                @endphp
                                <div class="flex flex-col w-full gap-2" id="document_container">
                                    @foreach($dokumen_jaminan as $index => $dokumen)
                                        <div class="flex flex-col w-full gap-2 custom-field-set" id="document_container_{{ $p_index }}">
                                            <div class="flex items-start gap-2 mt-2">
                                                <input class="flex-1 input" type="text" name="dokumen_nomor[{{ $n }}][]" placeholder="Nomor Dokumen" value="{{ $dokumen_nomor[$index] ?? '' }}">
                                                <span class="flex-1">
                                                        <input class="file-input" type="file" name="dokumen_jaminan[{{ $n }}][]" accept=".pdf,image/*">
                                                        <input type="hidden" name="dokumen_jaminan[{{ $n }}][]" value="{{ $dokumen }}">
                                                        <a href="{{ route('debitur.jaminan.download', ['id' => $debitur->id, 'dokumen' => $detail->id, 'index' => $index]) }}"
                                                           class="flex-none badge badge-sm badge-outline mt-2 mr-2">
                                                            {{ basename($dokumen) }}
                                                            <i class="ki-filled ki-cloud-download"></i>
                                                        </a>
                                                        </span>
                                                <button type="button" class="flex-none btn btn-danger w-[100px] text-center" onclick="removeFileInput(this)">Remove</button>

                                            </div>

                                            @if($detail->details)
                                                @if($detail->jenisLegalitasJaminan->custom_fields)
                                                    @foreach($detail->jenisLegalitasJaminan->custom_fields as $key)
                                                        <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5 custom-field">
                                                            @php
                                                                $customField = getCustomField($key);
                                                                $fieldValue = json_decode($detail->details)[$index]->{$customField->name} ?? '';
                                                            @endphp
                                                            <label class="form-label max-w-56 capitalize">
                                                                {{ $customField->label ?? "" }}
                                                            </label>
                                                            <div class="flex flex-wrap items-baseline w-full">
                                                                @switch($customField->type)
                                                                    @case('text')
                                                                        <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" value="{{ $fieldValue }}" placeholder="...">
                                                                        @break
                                                                    @case('number')
                                                                        <input class="input" type="number" step="0.01" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" value="{{ $fieldValue }}" placeholder="...">
                                                                        @break
                                                                    @case('date')
                                                                        <input class="input" type="date" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" value="{{ $fieldValue }}">
                                                                        @break
                                                                    @case('textarea')
                                                                        <textarea class="textarea" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="...">{{ $fieldValue }}</textarea>
                                                                        @break
                                                                    @case('select')
                                                                        <select class="select" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]">
                                                                            <option value="">Select an option</option>
                                                                            @foreach($customField->options as $option)
                                                                                <option value="{{ $option }}" {{ $fieldValue == $option ? 'selected' : '' }}>{{ $option }}</option>
                                                                            @endforeach
                                                                        </select>
                                                                        @break
                                                                    @default
                                                                        <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" value="{{ $fieldValue }}" placeholder="...">
                                                                @endswitch
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                @endif
                                            @else
                                                @if($detail->jenisLegalitasJaminan->custom_fields)
                                                    @foreach($detail->jenisLegalitasJaminan->custom_fields as $key)
                                                        <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                                                            @php
                                                                $customField = getCustomField($key);
                                                            @endphp
                                                            <label class="form-label max-w-56 capitalize">
                                                                {{ $customField->label }}
                                                            </label>
                                                            <div class="flex flex-wrap items-baseline w-full">
                                                                @switch($customField->type)
                                                                    @case('text')
                                                                        <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="...">
                                                                        @break
                                                                    @case('number')
                                                                        <input class="input" type="number" step="0.01" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="...">
                                                                        @break
                                                                    @case('date')
                                                                        <input class="input" type="date" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]">
                                                                        @break
                                                                    @case('textarea')
                                                                        <textarea class="textarea" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="..."></textarea>
                                                                        @break
                                                                    @case('select')
                                                                        <select class="select" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]">
                                                                            <option value="">Select an option</option>
                                                                            @foreach($customField->options as $option)
                                                                                <option value="{{ $option }}">{{ $option }}</option>
                                                                            @endforeach
                                                                        </select>
                                                                        @break
                                                                    @default
                                                                        <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="...">
                                                                @endswitch
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                @endif
                                            @endif
                                        </div>
                                        @php $p_index++; @endphp
                                    @endforeach
                                </div>
                                <div class="flex items-center justify-end gap-2 my-2 w-full">
                                    <button type="button" class="flex-none btn btn-primary text-center" onclick="addFileInput({{$n}},{{ $detail->jenisLegalitasJaminan->id }})">Add File</button>
                                </div>
                            @else
                                <div class="flex flex-col w-full gap-2" id="document_container">
                                    <div class="flex items-start gap-2 mt-2">
                                        <input class="flex-1 input" type="text" name="dokumen_nomor[{{ $n }}][]" placeholder="Nomor Dokumenss">
                                        <span class="flex-1">
                                                    <input class="file-input" type="file" name="dokumen_jaminan[{{ $n }}][]" accept=".pdf,image/*">
                                                    </span>
                                    </div>
                                    @if($detail->jenisLegalitasJaminan->custom_fields)
                                        @foreach($detail->jenisLegalitasJaminan->custom_fields as $key)
                                            <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                                                @php
                                                    $customField = getCustomField($key);
                                                @endphp
                                                <label class="form-label max-w-56 capitalize">
                                                    {{ $customField->label }}
                                                </label>
                                                <div class="flex flex-wrap items-baseline w-full">
                                                    @switch($customField->type)
                                                        @case('text')
                                                            <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="...">
                                                            @break
                                                        @case('number')
                                                            <input class="input" type="number" step="0.01" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="...">
                                                            @break
                                                        @case('date')
                                                            <input class="input" type="date" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]">
                                                            @break
                                                        @case('textarea')
                                                            <textarea class="textarea" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="..."></textarea>
                                                            @break
                                                        @case('select')
                                                            <select class="select" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]">
                                                                <option value="">Select an option</option>
                                                                @foreach($customField->options as $option)
                                                                    <option value="{{ $option }}">{{ $option }}</option>
                                                                @endforeach
                                                            </select>
                                                            @break
                                                        @default
                                                            <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$customField->name}}]" placeholder="...">
                                                    @endswitch
                                                </div>
                                            </div>
                                        @endforeach
                                    @endif
                                </div>
                                <div class="flex items-center justify-end gap-2 my-2 w-full">
                                    <button type="button" class="flex-none btn btn-primary text-center" onclick="addFileInput({{ $n }},{{ $detail->jenisLegalitasJaminan->id }})">Add File</button>
                                </div>
                                @php $p_index++; @endphp
                            @endif
                        </div>
                    </div>
                </div>

                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label class="form-label max-w-56">
                        Keterangan
                    </label>
                    <div class="flex flex-wrap items-baseline w-full">
                        <textarea class="textarea" rows="3" type="number" name="keterangan[]">{{ $detail->keterangan ?? ""  }}</textarea>
                    </div>
                </div>
                @php $n++; @endphp
            @endforeach

            @if($legalitas)
                @foreach($legalitas as $item)
                    <div id="document-container-{{ $n }}">
                        <div class="flex flex-col w-full gap-2">
                            <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                                <label class="form-label max-w-56 font-bold">
                                    {{ $n + 1 }}. {{ $item->name }}
                                </label>
                                <input type="hidden" name="jenis_legalitas_jaminan_id[]" value=" {{ $item->id }}">
                            </div>

                            <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                                <label class="form-label max-w-56">
                                    Nama Dokumen
                                </label>
                                <div class="flex flex-wrap items-baseline w-full">
                                    <input class="input " type="text" id="name" name="name[]" value="" placeholder="Nomor">
                                </div>
                            </div>

                            <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                                <label class="form-label max-w-56">
                                    Dokumen Jaminan
                                </label>
                                <div class="flex flex-wrap items-baseline w-full">
                                    <div class="flex flex-col w-full gap-2" id="document_container">
                                        <div class="flex items-center gap-2">
                                            <input class="flex-1 input" type="text" name="dokumen_nomor[{{ $n }}][]" placeholder="Nomor Dokumen">
                                            <input class="flex-1 file-input" type="file" name="dokumen_jaminan[{{ $n }}][]" accept=".pdf,image/*">
                                        </div>

                                        @if($item->custom_fields)
                                            @foreach($item->custom_fields as $field)
                                                @php $custom_field = getCustomField($field) @endphp
                                                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                                                    <label class="form-label max-w-56 capitalize">
                                                        {{ $custom_field->label }}
                                                    </label>
                                                    <div class="flex flex-wrap items-baseline w-full">
                                                        @switch($custom_field->type)
                                                            @case('text')
                                                                <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$custom_field->name}}]" placeholder="...">
                                                                @break
                                                            @case('number')
                                                                <input class="input" type="number" step="0.01" name="custom_field[{{$n}}][{{$p_index}}][{{$custom_field->name}}]" placeholder="...">
                                                                @break
                                                            @case('date')
                                                                <input class="input" type="date" name="custom_field[{{$n}}][{{$p_index}}][{{$custom_field->name}}]">
                                                                @break
                                                            @case('textarea')
                                                                <textarea class="textarea" name="custom_field[{{$n}}][{{$p_index}}][{{$custom_field->name}}]" placeholder="..."></textarea>
                                                                @break
                                                            @case('select')
                                                                <select class="select" name="custom_field[{{$n}}][{{$p_index}}][{{$custom_field->name}}]">
                                                                    <option value="">Select an option</option>
                                                                    @foreach($custom_field->options as $option)
                                                                        <option value="{{ $option }}">{{ $option }}</option>
                                                                    @endforeach
                                                                </select>
                                                                @break
                                                            @default
                                                                <input class="input" type="text" name="custom_field[{{$n}}][{{$p_index}}][{{$custom_field->name}}]" placeholder="...">
                                                        @endswitch
                                                    </div>
                                                </div>
                                            @endforeach
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center justify-end gap-2 my-2 w-full">
                            <button type="button" class="flex-none btn btn-primary text-center" onclick="addFileInput({{ $n }}, {{ $item->id }})">Add File</button>
                        </div>

                        <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                            <label class="form-label max-w-56">
                                Keterangan
                            </label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <textarea class="textarea" rows="3" type="number" name="keterangan[]"></textarea>
                            </div>
                        </div>
                    </div>
                    @php $n++;$p_index++; @endphp
                @endforeach
            @endif

        @endif
    </div>
    <div class="flex justify-end">
        <button type="submit" class="btn btn-primary">
            Save
        </button>
    </div>
</form>


@push('scripts')
    {{--Pemilik Jaminan--}}
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const namaSertifikatDiv = document.getElementById("nama_sertifikat");

            // Function to add delete event listeners to existing buttons
            function addDeleteListeners() {
                document.querySelectorAll(".delete-button").forEach(button => {
                    button.addEventListener("click", function () {
                        this.closest(".flex.items-baseline.flex-wrap.lg\\:flex-nowrap.gap-2\\.5.mb-5").remove();
                    });
                });
            }

            // Add delete listeners to existing buttons
            addDeleteListeners();

            document.getElementById("tambah_sertifikat").addEventListener("click", function () {
                const newDiv = document.createElement("div");
                newDiv.className = "flex items-baseline flex-wrap lg:flex-nowrap gap-2.5 mb-5";
                newDiv.innerHTML = `
                    <label class="form-label max-w-56">
                        Nama Lengkap
                    </label>
                    <div class="flex flex-wrap items-baseline w-full">
                        <div class="flex flex-col lg:flex-row gap-2 w-full">
                            <div class="flex flex-wrap items-baseline w-full">
                                <input class="input" type="text" name="detail_sertifikat[name][]" value="" placeholder="Nama Pemilik Jaminan">
                            </div>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input class="input" type="number" name="detail_sertifikat[nomor_id][]" value="" placeholder="Nomor ID/KTP">
                            </div>
                            <button type="button" class="btn btn-danger btn-xs delete-button">Hapus</button>
                        </div>
                    </div>
                `;
                namaSertifikatDiv.appendChild(newDiv);

                // Add delete listener to the new button
                addDeleteListeners();
            });
        });

        function changePemilikJaminan() {
            var pemilikJaminan = document.getElementById("pemilik_jaminan_id").value;
            var fieldsetPemilikJaminan = document.getElementById("pemilik_jaminan");
            if (pemilikJaminan === "00") {
                fieldsetPemilikJaminan.classList.remove("hidden");
            } else {
                fieldsetPemilikJaminan.classList.add("hidden");
            }
        }
    </script>

    {{--Legalitas Jaminan--}}
    <script>
        function getCustomFields(jenisLegalitasJaminanId, index, newFieldIndex) {
            return fetch(`/basic-data/jenis-jaminan/custom-fields/${jenisLegalitasJaminanId}`, {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    "X-Requested-With": "XMLHttpRequest"
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(customFields => {
                    let customFieldsHtml = '';
                    customFields.forEach(field => {
                        customFieldsHtml += `
                <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5 mb-2 custom-field">
                    <label class="form-label max-w-56 capitalize">
                        ${field.label}
                    </label>
                    <div class="flex flex-wrap items-baseline w-full">
                        ${getCustomFieldInput(index, field.type, field.name, null, jenisLegalitasJaminanId, newFieldIndex)}
                    </div>
                </div>
            `;
                    });
                    return customFieldsHtml;
                })
                .catch(error => {
                    console.error("Error fetching custom fields:", error);
                    return '';
                });
        }

        function getLegalitasJaminan() {
            var legalitasJaminan = document.getElementById("jenis_jaminan_id").value;
            var documentId = "{{ $document->id ?? "0" }}";
            var debiturId = "{{ $debitur->id }}";
            var url = `/basic-data/jenis-jaminan/legalitas/${documentId}/${legalitasJaminan}`;
            fetch(url, {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    "X-Requested-With": "XMLHttpRequest"
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    var doctainer = document.getElementById("doctainer");
                    doctainer.innerHTML = "";
                    data.forEach((item, index) => {
                        console.log(item);
                        doctainer.innerHTML += `
                        <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                            <label class="form-label max-w-56 font-bold">
                                ${index + 1}. ${item.name}
                            </label>
                            <input type="hidden" name="jenis_legalitas_jaminan_id[]" value="${item.jenis_legalitas_jaminan_id}">
                            ${item.is_existing ? `<input type="hidden" name="detail_dokumen_jaminan_id[]" value="${item.id}">` : ""}
                        </div>

                        <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                            <label class="form-label max-w-56">
                                 Nama Dokumen
                            </label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <input class="input" type="text" name="name[]" value="${item.name || ""}" placeholder="Nomor">
                            </div>
                        </div>
                        <div id="document-container-${index}">
                            <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                                <label class="form-label max-w-56">
                                    Dokumen Jaminan
                                </label>
                                <div class="flex flex-wrap items-baseline w-full" id="document_container">
                                    <div class="flex flex-col w-full gap-2">
                                        ${item.dokumen_jaminan ? renderExistingFiles(item.dokumen_jaminan, debiturId, item.id, item.dokumen_nomor) : ""}

<div class="flex items-center gap-2 my-2 w-full">
                                        <input class="flex-1 input" type="text" name="dokumen_nomor[${index}][]" placeholder="Nomor Dokumen">
                                        <input class="flex-1 file-input" type="file" name="dokumen_jaminan[${index}][]" accept=".pdf,image/*">
                                    </div>
                                    ${item.custom_fields && item.custom_fields.length > 0 ? item.custom_fields.map(field => `
                                    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5 mb-2 custom-field">
                                        <label class="form-label max-w-56 capitalize">
                                            ${field.label}
                                        </label>
                                        <div class="flex flex-wrap items-baseline w-full">
                                            ${getCustomFieldInput(index, field.type, field.name, item.details, item.jenis_legalitas_jaminan_id, 0)}
                                        </div>
                                    </div>
                                    `).join('') : ""}
                                    </div>
                                </div>
                            </div>

                                    <div class="flex items-center justify-end gap-2 my-2 w-full">
                                        <button type="button" class="flex-none btn btn-primary text-center" onclick="addFileInput(${index},${item.jenis_legalitas_jaminan_id})">Add File</button>
                                    </div>
                        </div>

                        <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                            <label class="form-label max-w-56">
                                Keterangan
                            </label>
                            <div class="flex flex-wrap items-baseline w-full">
                                <textarea class="textarea" rows="3" name="keterangan[]">${item.keterangan || ""}</textarea>
                            </div>
                        </div>
                    `;
                    });
                })
                .catch(error => console.error("Error:", error));
        }

        function addFileInput(index, jenisLegalitasJaminanId = null) {
            const documentContainer = document.getElementById(`document-container-${index}`);
            const container = documentContainer.querySelector('#document_container');

            const customFields = container.querySelectorAll('.custom-field');


            // Get the current number of custom field sets
            const currentFieldSets = container.querySelectorAll('.custom-field-set').length;
            const newFieldIndex = currentFieldSets + 1;

            const newInput = document.createElement("div");
            newInput.className = "flex flex-col w-full gap-2 mb-4 custom-field-set";

            getCustomFields(jenisLegalitasJaminanId, index, newFieldIndex).then(customFieldsHtml => {
                newInput.innerHTML = `
            <div class="flex flex-wrap items-baseline w-full">
                <div class="flex items-center gap-2 w-full">
                    <input class="flex-1 input" type="text" name="dokumen_nomor[${index}][]" placeholder="Nomor Dokumen">
                    <input class="flex-1 file-input" type="file" name="dokumen_jaminan[${index}][]" accept=".pdf,image/*">
                    <button type="button" class="flex-none btn btn-danger text-center" onclick="removeFileInput(this)">Remove</button>
                </div>
            </div>
            ${customFieldsHtml}
        `;

                container.appendChild(newInput);
            });
        }

        function removeFileInput(button) {
            button.closest(".custom-field-set").remove();

        }

        function renderExistingFiles(dokumenJaminan, debiturId, itemId, dokumenNomor) {
            if (typeof dokumenJaminan === "string" && typeof dokumenNomor === "string") {
                return `
                <div class="flex w-full lg:w-[30%]">
                    <span class="flex-1 mt-2 text-info text-sm">Nomor Dokumen : ${dokumenNomor}</span>
                    <a href="/debitur/${debiturId}/jaminan/download?dokumen=${itemId}" class="flex-none badge badge-sm badge-outline mt-2">
                        ${dokumenJaminan.split("/").pop()}
                        <i class="ki-filled ki-cloud-download"></i>
                    </a>
                </div>
                `;
            } else if (typeof dokumenJaminan === "string" && dokumenNomor === null) {
                return `
                <div class="flex w-full lg:w-[30%]">
                    <span class="flex-1 mt-2 text-info text-sm">Nomor Dokumen : --</span>
                    <a href="/debitur/${debiturId}/jaminan/download?dokumen=${itemId}" class="flex-none badge badge-sm badge-outline mt-2">
                        ${dokumenJaminan.split("/").pop()}
                        <i class="ki-filled ki-cloud-download"></i>
                    </a>
                </div>
                `;
            } else if (Array.isArray(dokumenJaminan) && Array.isArray(dokumenNomor)) {
                return dokumenJaminan.map((file, index) => `<div class="flex w-full lg:w-[30%]">
                    <span class="flex-1 mt-2 text-info text-sm">Nomor Dokumen : ${dokumenNomor[index] || "N/A"}</span>
                    <a href="/debitur/${debiturId}/jaminan/download?dokumen=${itemId}&file=${file}" class="flex-none badge badge-sm badge-outline mt-2 mr-2">
                        ${file.split("/").pop()}
                        <i class="ki-filled ki-cloud-download"></i>
                    </a></div>
                `).join("");
            } else if (Array.isArray(dokumenJaminan) && typeof dokumenNomor === "string") {
                return dokumenJaminan.map((file, index) => `<div class="flex w-full lg:w-[30%]">
                    <span class="flex-1 mt-2 text-info text-sm">Nomor Dokumen : ${dokumenNomor} || 'N/A'}</span>
                    <a href="/debitur/${debiturId}/jaminan/download?dokumen=${itemId}&file=${file}" class="flex-none badge badge-sm badge-outline mt-2 mr-2">
                        ${file.split("/").pop()}
                        <i class="ki-filled ki-cloud-download"></i>
                    </a></div>
                `).join("");
            } else if (Array.isArray(dokumenJaminan) && dokumenNomor === "null") {
                return dokumenJaminan.map((file, index) => `<div class="flex w-full lg:w-[30%]">
                    <span class="flex-1 mt-2 text-info text-sm">Nomor Dokumen : ${dokumenNomor} || 'N/A'}</span>
                    <a href="/debitur/${debiturId}/jaminan/download?dokumen=${itemId}&file=${file}" class="flex-none badge badge-sm badge-outline mt-2 mr-2">
                        ${file.split("/").pop()}
                        <i class="ki-filled ki-cloud-download"></i>
                    </a></div>
                `).join("");
            }
            return dokumenNomor;
        }

        function getCustomFieldInput(index, type, fieldName, value, itemId, fieldIndex = 0) {
            value = value ? JSON.parse(value)[fieldName] || "" : "";
            switch (type) {
                case "text":
                    return `<input class="input" type="text" name="custom_field[${index}][${fieldIndex}][${fieldName}]" value="${value}">`;
                case "number":
                    return `<input class="input" type="number" step="0.01" name="custom_field[${index}][${fieldIndex}][${fieldName}]" value="${value}">`;
                case "date":
                    return `<input class="input" type="date" name="custom_field[${index}][${fieldIndex}][${fieldName}]" value="${value}">`;
                case "textarea":
                    return `<textarea class="textarea" rows="3" name="custom_field[${index}][${fieldIndex}][${fieldName}]">${value}</textarea>`;
                default:
                    return `<input class="input" type="text" name="custom_field[${index}][${fieldIndex}][${fieldName}]" value="${value}">`;
            }
        }

        function clearDetail(detailId) {
            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: "Anda akan menghapus detail ini!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, yakin!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Apakah Anda yakin?',
                        text: "Data yang telah di hapus tidak dapat di kembalikan",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Ya, hapus!',
                        cancelButtonText: 'Batal'
                    }).then((result2) => {
                        if (result2.isConfirmed) {
                            // Hapus input fields
                            $(`input[name="detail_dokumen_jaminan_id[]"][value="${detailId}"]`).closest('.grid.gap-5').remove();

                            // Kirim request AJAX untuk menghapus data dari database
                            $.ajax({
                                url: '{{ route("debitur.jaminan.clearDetail", $debitur->id ) }}',
                                type: 'POST',
                                data: {
                                    _token: '{{ csrf_token() }}',
                                    detail_id: detailId
                                },
                                success: function (response) {
                                    if (response.success) {
                                        Swal.fire({
                                            title: 'Berhasil!',
                                            text: 'Detail berhasil dihapus',
                                            icon: 'success',
                                            confirmButtonText: 'OK'
                                        }).then((result) => {
                                            if (result.isConfirmed) {
                                                location.reload();
                                            }
                                        });
                                    } else {
                                        Swal.fire({
                                            title: 'Gagal!',
                                            text: 'Detail gagal dihapus',
                                            icon: 'error',
                                            confirmButtonText: 'OK'
                                        });
                                    }
                                },
                                error: function () {
                                    Swal.fire({
                                        title: 'Gagal!',
                                        text: 'Terjadi kesalahan saat menghapus detail',
                                        icon: 'error',
                                        confirmButtonText: 'OK'
                                    });
                                }
                            });
                        }
                    });
                }
            });
        }
    </script>
@endpush
