@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">
        <div class="pb-2.5 border card border-agi-100">
            @if(isset($permohonan->id))
            <div class="card-header bg-agi-50" id="basic_settings">
                <div class="flex flex-row gap-1.5 card-title">
                    <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 gap-2 items-center">
                    @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 gap-2 items-center">
                        <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 }}">

                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="gap-1 form-label max-w-56">
                            Cabang
                            <span class="text-danger">*</span>
                        </label>
                        <div class="flex flex-wrap items-baseline w-full">
                            @if (auth()->user()->hasRole(['administrator','admin']))
                                <select class="input tomselect w-full @error('branch_id') border-danger bg-danger-light @enderror"
                                    name="branch_id" id="branch_id">
                                    <option value="">Pilih Cabang</option>
                                    @foreach ($branches as $branch)
                                        <option value="{{ $branch->id }}"
                                            {{ (isset($debitur) && $branch->id == $debitur->branch_id) || old('branch_id') == $branch->id ? 'selected' : '' }}>
                                            {{ $branch->name }}
                                        </option>
                                    @endforeach
                                </select>
                            @else
                                <input type="hidden" name="branch_id" value="{{ auth()->user()->branch_id }}">
                                <input type="text" class="w-full input" value="{{ auth()->user()->branch->name }}" readonly>
                            @endif
                            @error('branch_id')
                                <em class="text-sm alert text-danger">{{ $message }}</em>
                            @enderror
                        </div>
                    </div>

                    @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',
                                'tidak_bayar' => 'Tidak Bayar'
                            ]],
                            'nilai_njop' => ['label' => 'Nilai NJOP', 'type' => 'text'],
                        ];
                    @endphp

                    @foreach($formFields as $field => $config)
                        <div id="{{ $field }}_wrapper" class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                            <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="text-sm alert text-danger">{{ $message }}</em>
                                @enderror
                            </div>
                        </div>
                    @endforeach

                    @if(isset($permohonan) && $permohonan->status == 'revisi')
                        <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                            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);

                const hideAndSetTidakBayar = (tujuanPenilaianValue === '2' || tujuanPenilaianValue === '4') &&
                    ['1', '2', '3'].includes(nilaiPlafondValue);


                if (hideAndSetTidakBayar) {
                    statusBayarTomSelect.setValue('tidak_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
