@extends('layouts.main')

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

@section('content')
    <div class="w-full grid gap-5 lg:gap-7.5 mx-auto">
        <div class="card border border-agi-100 pb-2.5">
            @if(isset($permohonan->id))
            <div class="card-header bg-agi-50" id="basic_settings">
                <div class="card-title flex flex-row gap-1.5">
                    <a href="{{ route('permohonan.edit',array_merge(request()->query(),['permohonan'=>$permohonan->id])) }}" class="btn btn-xs {{ request()->routeIs('permohonan.edit') ? 'btn-outline btn-primary' : 'btn-light' }}">Data Permohonan</a>
                    <a href="{{ route('debitur.edit',array_merge(request()->query(),['debitur'=>$debitur->id,'permohonan_id' => $permohonan->id])) }}" class="btn btn-xs {{ request()->routeIs('debitur.edit') ? 'btn-outline btn-primary' : 'btn-light' }}">Data Debitur</a>
                    <a href="{{ route('debitur.jaminan.index',array_merge(request()->query(),['id'=>$debitur->id,'permohonan_id' => $permohonan->id])) }}" class="btn btn-xs {{ request()->routeIs('debitur.jaminan.index') ? 'btn-outline btn-primary' : 'btn-light' }}">Dokumen Jaminan</a>
                    <a href="{{ route('debitur.pemilik.index',array_merge(request()->query(),['id'=>$debitur->id,'permohonan_id' => $permohonan->id])) }}" class="btn btn-xs {{ request()->routeIs('debitur.pemilik.index') ? 'btn-outline btn-primary' : 'btn-light' }}">Pemilk Jaminan</a>
                </div>
                <div class="flex items-center gap-2">
                    @if(isset($debitur->id) && !isset($permohonan->id))
                        <a class="btn btn-sm btn-primary" href="{{ route('permohonan.create.debitur', $debitur->id) }}"> Buat Permohonan </a>
                    @endif

                    @if(request()->get('from') == 'permohonan')
                        <a href="{{ route('permohonan.create') }}" class="btn btn-xs btn-info"><i class="ki-filled ki-exit-left"></i> Back</a>
                    @elseif($permohonan->id)
                        <a href="{{ route('permohonan.index') }}" class="btn btn-xs btn-info"><i class="ki-filled ki-exit-left"></i> Back</a>
                    @else
                        <a href="{{ route('debitur.index') }}" class="btn btn-xs btn-info"><i class="ki-filled ki-exit-left"></i> Back</a>
                    @endif
                </div>
            </div>
            @else
                <div class="card-header bg-agi-50" id="basic_settings">
                    <h3 class="card-title">
                        {{ isset($permohonan->id) ? 'Edit' : 'Tambah' }} Permohonan
                    </h3>
                    <div class="flex items-center gap-2">
                        <a href="{{ route('permohonan.index') }}" class="btn btn-xs btn-info"><i class="ki-filled ki-exit-left"></i> Back</a>
                    </div>
                </div>
            @endif

            <div class="card-body">
                <form action="{{ isset($permohonan->id) ? route('permohonan.update', $permohonan) : route('permohonan.store') }}" method="POST" class="grid gap-5" enctype="multipart/form-data">
                    @csrf
                    @if(isset($permohonan->id))
                        @method('PUT')
                        <input type="hidden" name="id" value="{{ $permohonan->id }}">
                    @endif

                    <input type="hidden" name="debiture_id" value="{{ $debitur->id }}">

                    @php
                        $formFields = [
                            'tujuan_penilaian_id' => ['label' => 'Tujuan Penilaian', 'type' => 'select', 'options' => $tujuanPenilaian],
                            'jenis_fasilitas_kredit_id' => ['label' => 'Fasilitas Kredit', 'type' => 'select', 'options' => $fasilitasKredit],
                            'nilai_plafond_id' => ['label' => 'Nilai Plafond', 'type' => 'select', 'options' => $plafond],
                            'status_bayar' => ['label' => 'Status Bayar', 'type' => 'select', 'options' => [
                                'sudah_bayar' => 'Sudah Bayar',
                                'belum_bayar' => 'Belum Bayar'
                            ]],
                            'nilai_njop' => ['label' => 'Nilai NJOP', 'type' => 'text'],
                        ];
                    @endphp

                    @foreach($formFields as $field => $config)
                        <div id="{{ $field }}_wrapper" class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                            <label class="form-label max-w-56">{{ $config['label'] }}</label>
                            <div class="flex flex-wrap items-baseline w-full">
                                @if($config['type'] === 'select')
                                    <select class="input {{ $field != 'status_bayar' ? 'tomselect' : '' }} w-full @error($field) border-danger bg-danger-light @enderror" name="{{ $field }}" id="{{ $field }}">
                                        <option value="">Pilih {{ $config['label'] }}</option>
                                        @foreach($config['options'] as $key => $value)
                                            <option value="{{ $value->id ?? $key }}"
                                                {{ (old($field) == ($value->id ?? $key)) || (isset($permohonan) && $permohonan->$field == ($value->id ?? $key)) ? 'selected' : '' }}>
                                                {{ $value->name ?? $value }}
                                            </option>
                                        @endforeach
                                    </select>
                                @else
                                    <input class="input @error($field) border-danger bg-danger-light @enderror"
                                           type="{{ $config['type'] }}"
                                           name="{{ $field }}"
                                           value="{{ old($field, $permohonan->$field ?? '') }}">
                                @endif
                                @error($field)
                                    <em class="alert text-danger text-sm">{{ $message }}</em>
                                @enderror
                            </div>
                        </div>
                    @endforeach

                    @if(isset($permohonan) && $permohonan->status == 'revisi')
                        <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                            Catatan : <br>
                            <em class="text-red-500">{{ $permohonan->keterangan }} {{ $permohonan->registrasi_catatan }}</em>
                        </div>
                    @endif

                    <div class="flex justify-end">
                        <button type="submit" class="btn btn-primary">
                            {{ isset($permohonan) && $permohonan->status == 'revisi' ? 'Submit Ulang' : 'Save' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const tujuanPenilaianSelect = document.getElementById('tujuan_penilaian_id');
            const nilaiPlafondSelect = document.getElementById('nilai_plafond_id');
            const statusBayarSelect = document.getElementById('status_bayar');
            const statusBayarWrapper = document.getElementById('status_bayar_wrapper');

            // Initialize TomSelect
            const statusBayarTomSelect = new window.TomSelect(statusBayarSelect, {
                create: false,
                sortField: {
                    field: "text",
                    direction: "asc"
                }
            });

            function updateStatusBayar() {
                const tujuanPenilaianValue = tujuanPenilaianSelect.value;
                const nilaiPlafondValue = nilaiPlafondSelect.value;
                console.log('Tujuan Penilaian:', tujuanPenilaianValue, 'Nilai Plafond:', nilaiPlafondValue);

                if (tujuanPenilaianValue === '2' && (nilaiPlafondValue === '2' || nilaiPlafondValue === '3')) {
                    statusBayarTomSelect.setValue('sudah_bayar');
                    statusBayarWrapper.style.display = 'none';
                } else {
                    @if(isset($permohonan))
                    statusBayarTomSelect.setValue('{{$permohonan->status_bayar ?? ''}}');
                    @else
                    statusBayarTomSelect.setValue('');
                    @endif
                        statusBayarWrapper.style.display = 'flex';
                }
                console.log('Status Bayar:', statusBayarTomSelect.getValue());
            }

            if (tujuanPenilaianSelect && nilaiPlafondSelect && statusBayarSelect) {
                tujuanPenilaianSelect.addEventListener('change', updateStatusBayar);
                nilaiPlafondSelect.addEventListener('change', updateStatusBayar);

                // Call the function when the page loads to set the initial status
                updateStatusBayar();
            } else {
                console.error('One or more required elements not found');
            }
        });
    </script>
@endpush
