@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">
        <form id="formInspeksi" method="POST" enctype="multipart/form-data" class="grid gap-5">
            @csrf
            <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') }}">
            <input type="hidden" name="action" value="rap">
            <input type="hidden" name="type" value="rap">
            @include('lpj::assetsku.includenya')
            <div class="card">
                <div class="card-header bg-agi-50">
                    <h3 class="uppercase card-title">
                        RAP
                    </h3>
		    <div class="flex gap-2 items-center">
		    	<a href="{{ route('penilai.show', $permohonan->id) }}" class="btn btn-xs btn-info">
                       		<i class="ki-filled ki-exit-left"></i> Back
                    	</a>
		    </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=" {{ $rap['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="{{ $rap['dari'] ?? '' }}">
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        <label class="form-label max-w-56">Nomor RAP</label>
                        <div class="flex flex-wrap w-full items-base line">
                            <input type="text" name="nomor_rap" class="w-full 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="{{ $rap['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="{{ $rap['perihal'] ?? '' }}">
                        </div>
                    </div>
                </div>
            </div>
            @include('lpj::surveyor.components.header')
            @include('lpj::surveyor.components.rap')
            <div class="flex gap-2 justify-end" style="margin-right: 20px; margin-top: 20px">
                @if (Auth::user()->hasAnyRole(['senior-officer', 'penilai', '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">Save</span>
                        <div class="spinner-border spinner-border-sm text-light" role="status" style="display: none;"
                            id="saveButtonSpinner">

                        </div>
                    </button>
                @endif
                @if (Auth::user()->hasAnyRole(['senior-officer', 'EO Appraisal', 'DD Appraisal', 'administrator']))
                    <a class="btn btn-info"
                        href="{{ route('penilai.lampiran') }}?permohonanId={{ request('permohonanId') }}&documentId={{ request('documentId') }}&jaminanId={{ request('jaminanId') }}&statusLpj=1">
                        Lampiran Foto dan Dokumen
                    </a>
                    <a href="{{ route('surveyor.print_out_inspeksi', ['permohonan_id' => $permohonan->id, 'dokument_id' => request('documentId'), 'jenis_jaminan_id' => request('jaminanId')]) }}"
                        class="btn btn-light">
                        <i class="ki-filled ki-printer"></i> Cetak Hasil Inspeksi
                    </a>
                    <a class="btn btn-success"
                        onclick="checkLaporan('{{ $permohonan->id }}', '{{ request('documentId') }}',  {{ request('jaminanId') }}, )">
                        <i class="ki-filled ki-printer"></i> Cetak Laporan
                    </a>
                @endif
            </div>
        </form>
    </div>
@endsection
@push('scripts')
    <script type="text/javascript">
        const rap = @json($forminspeksi);
        console.log('rap', rap)

        function updateAlamatFields(status) {
            // Ambil elemen formulir
            const addressForm = document.getElementById('alamat_form');
            const inputs = addressForm.querySelectorAll('input, select');
            const addressInput = document.getElementById('address');

            if (status === 'sesuai') {
                addressInput.value = {!! json_encode($dokumen->address ?? '') !!};

                inputs.forEach(element => {
                    if (element.tagName === 'INPUT') {
                        element.setAttribute('readonly', true);
                    } else if (element.tagName === 'SELECT') {
                        element.setAttribute('disabled', true);
                        element.classList.add('disabled-input')
                    }
                });

                addressForm.style.display = 'grid';
                addressForm.disabled = true;
                addressForm.classList.add('disabled-input')


            } else if (status === 'tidak sesuai') {
                addressForm.style.display = 'grid';

                addressForm.removeAttribute('disabled');
                addressForm.classList.remove('disabled-input')
                const formInspeksi = @json($forminspeksi);
                const addressInput = document.getElementById('address');

                if (formInspeksi && formInspeksi.asset && formInspeksi.asset.alamat) {
                    if (formInspeksi.asset.alamat['tidak sesuai'] && formInspeksi.asset.alamat['tidak sesuai'].address) {
                        addressInput.value = formInspeksi.asset.alamat['tidak sesuai'].address;
                    } else if (formInspeksi.asset.alamat['sesuai'] && formInspeksi.asset.alamat['sesuai'].address) {
                        addressInput.value = formInspeksi.asset.alamat['sesuai'].address;
                    } else {
                        addressInput.value = "";
                    }
                }

                inputs.forEach(element => {
                    if (element.tagName === 'INPUT') {
                        element.removeAttribute('readonly');
                    } else if (element.tagName === 'SELECT') {
                        element.removeAttribute('disabled');
                        element.classList.remove('disabled-input')
                    }
                });
            }
        }

        function toggleFieldVisibility(fieldName, inputId, visibleValues = []) {
            const selectedValue = $(`[name="${fieldName}"]:checked`).val();
            const inputField = $(`#${inputId}`);

            if (visibleValues.includes(selectedValue)) {
                inputField.show();
            } else {
                inputField.hide().val('');
            }
        }


        function toggleCheckboxVisibility(fieldName, inputId, visibleValues = []) {
            const selectedValues = $(`[name="${fieldName}[]"]:checked`)
                .map(function() {
                    return $(this).val().toLowerCase(); // Konversi nilai ke huruf kecil
                })
                .get();

            const inputField = $(`#${inputId}`);

            // Cek apakah salah satu nilai yang dipilih cocok dengan visibleValues
            const shouldShow = visibleValues.some(value => selectedValues.includes(value.toLowerCase()));

            if (shouldShow) {
                inputField.show();
            } else {
                inputField.hide().val('');
            }
        }


        function toggleMultipleFields(fieldName, mappings) {
            // Ambil semua nilai checkbox yang dicentang
            const selectedValues = $(`[name="${fieldName}[]"]:checked`)
                .map(function() {
                    return $(this).val().toLowerCase(); // Konversi nilai ke huruf kecil
                })
                .get();

            // Iterasi melalui setiap mapping
            for (const [key, inputId] of Object.entries(mappings)) {
                const inputField = $(`#${inputId}`);

                // Tampilkan input jika nilai yang relevan dipilih
                if (selectedValues.includes(key.toLowerCase())) {
                    inputField.show();
                } else {
                    inputField.hide().val(''); // Sembunyikan dan reset nilai
                }
            }
        }


        function toggleAlamatVisibility(idSesuai, idTidakSesuai, selectedValue) {
            // Ambil elemen berdasarkan ID
            const alamatSesuai = document.getElementById(idSesuai);
            const alamatTidakSesuai = document.getElementById(idTidakSesuai);

            // Periksa nilai yang dipilih dan tampilkan elemen yang sesuai
            if (selectedValue === 'sesuai') {
                alamatSesuai.style.display = 'grid'; // Tampilkan "Alamat Sesuai"
                alamatTidakSesuai.style.display = 'none'; // Sembunyikan "Alamat Tidak Sesuai"
            } else if (selectedValue === 'tidak sesuai') {
                alamatSesuai.style.display = 'none'; // Sembunyikan "Alamat Sesuai"
                alamatTidakSesuai.style.display = 'grid'; // Tampilkan "Alamat Tidak Sesuai"
            }
        }



        function submitData() {
            showLoadingSwal('Mengirim data ke server...');
            const form = document.querySelector('form');
            const formData = new FormData(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 requestUrl =
                `{{ route('penilai.storeRap') }}?permohonanId=${permohonanId}&documentId=${documentId}`;
            $.ajax({
                url: requestUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                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);
                }
            });
        }



        // Ensure existing remove buttons are functional
        document.addEventListener('DOMContentLoaded', () => {
            const removeButtons = document.querySelectorAll('.remove-btn');
            removeButtons.forEach(button => {
                button.addEventListener('click', function() {
                    this.closest('.perwakilan').remove();
                });
            });

            document.querySelectorAll('.number-format').forEach(input => {
                input.addEventListener('input', function() {
                    formatNumber(this);
                });
            });
        });



        function updateAnalisa(params) {
            const inputMap = {
                jenis_asset: 'jenis_asset_tidak_sesuai',
                analisa_tanah: 'analisa_tanah_tidak_sesuai',
                analisa_unit: 'analisa_luas_unit_tidak_sesuai',
                analisa_bangunan: 'analisa_bangunan_tidak_sesuai',
            };

            // Pastikan elemen ID ada di inputMap
            if (!inputMap[params]) {
                console.error('Parameter tidak valid:', params);
                return;
            }

            // Ambil nilai berdasarkan parameter
            const inputValue = document.getElementById(inputMap[params]).value;
            const data = {
                [params === 'jenis_asset' ? 'jenis_asset' : params.replace('analisa_', 'luas_')]: inputValue,
                types: params
            };

            $.ajax({
                url: '{{ route('surveyor.update_analisa', ['id' => $permohonan->id]) }}',
                type: 'POST',
                data: data,
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                success: function(response) {
                    console.log(response);
                    if (response.success) {
                        // window.location.href =
                        //     '{{ route('surveyor.show', ['id' => $permohonan->id]) }}';
                        toastrSuccessBuild(response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Terjadi error:', error);
                    console.log('Status:', status);
                    console.log('Response:', xhr.responseText);
                    if (xhr.responseJSON.message) {
                        toastrErrorBuild(xhr.responseJSON.message);
                    } else {
                        toastrErrorBuild('Terjadi kesalahan');
                    }
                }
            });
        }
    </script>
    @include('lpj::surveyor.js.utils')
@endpush
