@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="min-w-full border card border-agi-100 card-grid" data-datatable="false" data-datatable-page-size="10"
             data-datatable-state-save="false" id="permohonan-table" data-api-url="{{ route('permohonan.datatables') }}">
            <div class="flex-wrap py-5 card-header bg-agi-50">
                <h3 class="card-title">
                    Daftar Permohonan
                </h3>
                <div class="flex flex-wrap gap-2 lg:gap-5">
                    <div class="flex">
                        <label class="input input-sm"> <i class="ki-filled ki-magnifier"> </i>
                            <input placeholder="Search Permohonan" id="search" type="text" value="">
                        </label>
                    </div>
                    <div class="flex flex-wrap gap-2.5">
                        <div class="h-[24px] border border-r-gray-200"></div>
                        <a class="btn btn-sm btn-light" href="{{ route('permohonan.export') }}"> Export to Excel </a>
                        @if(auth()->user()->hasAnyRole(['administrator', 'pemohon-ao','admin']))
                            <a class="btn btn-sm btn-primary" href="{{ route('permohonan.create') }}"> Tambah Permohonan </a>
                        @endif
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="scrollable-x-auto">
                    <table class="table text-sm font-medium text-gray-700 align-middle table-auto table-border"
                           data-datatable-table="true">
                        <thead>
                        <tr>
                            <th class="w-14">
                                <input class="checkbox checkbox-sm" data-datatable-check="true" type="checkbox"/>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="nomor_registrasi">
                                    <span class="sort"> <span class="sort-label"> Nomor Registrasi </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="mig_mst_lpj_nomor_jaminan">
                                    <span class="sort"> <span class="sort-label"> Nomor LPJ Lama </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="tanggal_permohonan">
                                    <span class="sort"> <span class="sort-label"> Tanggal Permohonan </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="pemohon">
                                    <span class="sort"> <span class="sort-label"> User Pemohon </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="branch">
                                    <span class="sort"> <span class="sort-label"> Cabang Pemohon </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="debitur_id">
                                    <span class="sort"> <span class="sort-label"> Debitur </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="tujuan_penilaian_id">
                                    <span class="sort"> <span class="sort-label"> Tujuan Penilaian </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px] text-center" data-datatable-column="status">
                                    <span class="sort"> <span class="sort-label"> Status </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="keterangan">
                                    <span class="sort"> <span class="sort-label"> Keterangan </span>
                                        <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[50px] text-right" data-datatable-column="actions">Action</th>
                        </tr>
                        </thead>
                    </table>
                </div>
                <div
                    class="flex-col gap-3 justify-center font-medium text-gray-600 card-footer md:justify-between md:flex-row text-2sm">
                    <div class="flex gap-2 items-center">
                        Show
                        <select class="w-16 select select-sm" data-datatable-size="true" name="perpage"> </select> per page
                    </div>
                    <div class="flex gap-4 items-center">
                        <span data-datatable-info="true"> </span>
                        <div class="pagination" data-datatable-pagination="true">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        const userRoles = @json(auth()->user()->roles->pluck('name'));
    </script>

    <script type="text/javascript">
        function deleteData(data, noReg, debitur) {
            Swal.fire({
                title: 'Pembatalan Permohonan',
                text: "Yakin akan membatalkan permohonan dengan nomor " + noReg + " untuk Debitur " + debitur + "?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        }
                    });

                    window.location = `permohonan/${data}/pembatalan`;
                }
            })
        }
    </script>
    <script type="module">
        const element = document.querySelector('#permohonan-table');
        const searchInput = document.getElementById('search');

        const apiUrl = element.getAttribute('data-api-url');
        const dataTableOptions = {
            apiEndpoint: apiUrl,
            pageSize: 5,
            columns: {
                select: {
                    render: (item, data, context) => {
                        const checkbox = document.createElement('input');
                        checkbox.className = 'checkbox checkbox-sm';
                        checkbox.type = 'checkbox';
                        checkbox.value = data.id.toString();
                        checkbox.setAttribute('data-datatable-row-check', 'true');
                        return checkbox.outerHTML.trim();
                    },
                },
                nomor_registrasi: {
                    title: 'Nomor Registrasi',
                },
                nomor_lpj: {
                    title: 'Nomor LPJ Lama',
                },
                tanggal_permohonan: {
                    title: 'Tanggal Permohonan',
                    render: (item, data) => {
                        return `${window.formatTanggalIndonesia(data.tanggal_permohonan)}`;
                    },
                },
                user_id: {
            title: 'User Pemohon',
            render: (item, data) => {
                return data?.user?.name ?? data?.mig_nama_ao ?? '-';
            }},

                branch_id: {
                    title: 'Cabang Pemohon',
                    render: (item, data) => {
                        return `${data?.branch?.name || '-'}`;
                    },
                },
                debitur_id: {
                    title: 'Debitur',
                    render: (item, data) => {
                        if (data.debiture) {
                            return `${data.debiture?.name.toUpperCase()}`;
                        }
                        return "-";
                    },
                },
                tujuan_penilaian_id: {
                    title: 'Tujuan Penilaian',
                    render: (item, data) => {
                        switch (data.tujuan_penilaian.code) {
                            case "TP0001":
                                return `<span class="badge badge-sm badge-primary">${data.tujuan_penilaian.name}</span>`;
                            case "TP0002":
                                return `<span class="badge badge-sm badge-info">${data.tujuan_penilaian.name}</span>`;
                            case "TP0003":
                                return `<span class="badge badge-sm badge-success">${data.tujuan_penilaian.name}</span>`;
                            case "TP0004":
                                return `<span class="badge badge-sm badge-danger">${data.tujuan_penilaian.name}</span>`;
                            case "TP0005":
                                return `<span class="badge badge-sm badge-warning">${data.tujuan_penilaian.name}</span>`;
                            case "TP0006":
                                return `<span class="badge badge-sm badge-dark">${data.tujuan_penilaian.name}</span>`;
                            case "TP0007":
                                return `<span class="badge badge-sm badge-outline badge-info">${data.tujuan_penilaian.name}</span>`;
                            default:
                                return `<span class="badge badge-sm badge-outline badge-default">${data.tujuan_penilaian.name}</span>`;
                        }
                    },
                },
                status: {
                    title: 'Status',
                    render: (item, data) => {
                        if (data.documents > 0) {
                            return `<span class="flex justify-center uppercase badge badge-sm badge-default">${data.status}</span>`;
                        }
                        return `<span class="flex justify-center uppercase badge badge-sm badge-danger">Lengkapi Aset Jaminan</span>`;

                    }
                },
                keterangan: {
                    title: 'Keterangan',
                    render: (item, data) => {

                        let keterangan = data.keterangan ?? ""
                        if (data.registrasi_catatan) {
                            if (keterangan) keterangan += "\n";
                            keterangan += data.registrasi_catatan;
                        }

                        return keterangan
                    }
                },
                actions: {
                    title: 'Actions',
                    render: (item, data) => {
                        let actionHtml = `<div class="flex flex-nowrap gap-1.5 justify-end">`;
                        const hasRole = (roles) => roles.some(role => userRoles.includes(role));

                        if (data.status === 'proses-survey' || data.status == 'rejected-reschedule') {
                            actionHtml += `
                                <a
                                title="Reschedule Jadwal Survey"
                        data-permohonan-id="${data.id}"
                        data-id-penilaian="${data.penilaian.id}"
                        data-no-reg="${data.nomor_registrasi}"
                        data-debitur="${data.debiture ? data.debiture.name.replace(/'/g, "\\'") : ""}"
                        data-waktu-penilaian="${data.penilaian.waktu_penilaian}"
                        data-rejected-note="${data.penilaian.rejected_note ? JSON.stringify(data.penilaian.rejected_note).replace(/'/g, "\\'").replace(/"/g, '&quot;') : '{}'}"
                        onclick="surveyorRescheduleJadwalSurvey(this)"
                        class="delete btn btn-sm btn-outline btn-light">
                        <i class="ki-filled ki-calendar-remove"></i>
                    </a>`;
                        }

                        if (data && data.penilaian && data.penilaian.waktu_penilaian !== null && data.status !==
                            'done' && data.penilaian.authorized_status == null || data.status ===
                            'approved-reschedule') {
                            actionHtml += `
            <a class="btn btn-sm btn-outline btn-primary"
title="Approve Jadwal Kunjungan No Reg ${data.nomor_registrasi}"
            data-permohonan-id="${data.id}"
            data-id-penilaian="${data.penilaian.id}"
            data-no-reg="${data.nomor_registrasi}"
            data-debitur="${data.debiture ? data.debiture.name.replace(/'/g, "\\'") : ""}"
            data-waktu-penilaian="${data.penilaian.waktu_penilaian}"
            onclick="surveyorApproveKunjungan(this)"  >
                    <i class="ki-filled ki-calendar-edit"></i>
                </a>
            `;
                        }

                        if (data.status !== 'order') {
                            actionHtml += `
                <a class="btn btn-sm btn-outline btn-success" href="permohonan/${data.id}" href="javascript:void(0)" title="Surat Permohonan">
                    <i class="ki-filled ki-document"></i>
                </a>
            `;
                        }

                        if (data.status !== 'done' && data.status !== 'batal' && hasRole(['administrator', 'pemohon-ao','admin'])) {
                            actionHtml += `
            <a class="btn btn-sm btn-outline btn-info" href="permohonan/${data.id}/edit" title="Edit Permohonan">
                <i class="ki-outline ki-notepad-edit"></i>
            </a>`;
                        }
                        if (data.status === 'order' && hasRole(['administrator', 'pemohon-ao','admin'])) {
                            actionHtml += `
            <a onclick="deleteData(${data.id}, '${data.nomor_registrasi}','${data.debiture?.name}')" class="delete btn btn-sm btn-outline btn-danger" title="Batalkan Permohonan">
                <i class="ki-outline ki-cross-square"></i>
            </a>`;
                        }


                        actionHtml += `</div>`;

                        return actionHtml;
                    },
                }
            },
        };

        let dataTable = new KTDataTable(element, dataTableOptions);
        // Custom search functionality
        searchInput.addEventListener('input', function () {
            const searchValue = this.value.trim();
            dataTable.search(searchValue, true);

        });
    </script>
    <script type="text/javascript">
        function surveyorApproveKunjungan(element) {
            const permohonanId = element.getAttribute('data-permohonan-id');
            const idPenilaian = element.getAttribute('data-id-penilaian');
            const noReg = element.getAttribute('data-no-reg');
            const debitur = element.getAttribute('data-debitur');
            const waktuPenilaian = element.getAttribute('data-waktu-penilaian');

            Swal.fire({
                title: ' ',
                text: "Yakin akan Menyetujui Jadwal Kunjungan " + noReg + " untuk Debitur " + debitur +
                    " pada waktu " + window.formatTanggalWaktuIndonesia(waktuPenilaian) + "?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes',
                cancelButtonText: 'Cancel',
                showDenyButton: true,
                denyButtonText: 'Reschedule',
                confirmButtonColor: '#3085d6',
                denyButtonColor: '#f4b400',
                cancelButtonColor: '#d33',
            }).then((result) => {
                if (result.isConfirmed) {
                    //define variable
                    // $id ==> penilaian.id
                    let token = "{{ csrf_token() }}";
                    let useURL = "{{ URL::to('/permohonan/store-approved') }}" + "/" + idPenilaian;

                    var input_data = new Object();
                    input_data._token = token;
                    input_data.id = idPenilaian;
                    input_data.noReg = noReg;
                    input_data.permohonan_id = permohonanId;
                    $.ajax({
                        url: useURL,
                        type: "PUT",
                        cache: false,
                        data: input_data,
                        dataType: "json",
                        success: function (response) {
                            console.log(response);
                            if ('success' == response.status) {
                                swal.fire('Sukses Menyetujui!', response.message, 'success').then(
                                    () => {
                                        location.reload(true);
                                    });
                            } else {
                                Swal.fire('Error!', response.message, 'error');
                            }

                        },
                        error: function (response, textStatus, errorThrown) {
                            // var errors = response.responseJSON.errors;
                            // console.log(errors);
                            console.log(response);

                        }
                    });
                } else if (result.isDenied) {
                    Swal.fire({
                        title: 'Reschedule Jadwal Kunjungan',
                        html: `
                    <div class="space-y-4 text-left">

                <p class="text-gray-700">
                    Yakin akan Reschedule Jadwal Kunjungan
                    <span class="font-semibold text-blue-600">${noReg}</span>
                    untuk Debitur
                    <span class="font-semibold text-blue-600">${debitur}</span>
                    pada waktu
                    <span class="font-semibold">${window.formatTanggalWaktuIndonesia(waktuPenilaian)}</span>?
                </p>

                <div>
                    <label for="reschedule_date" class="block mb-1 text-sm font-medium text-gray-700">Tanggal Baru</label>
                    <input type="datetime-local" id="reschedule_date"
                           class="block px-4 py-2 w-full rounded-lg border border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                </div>

                <div>
                    <label for="reschedule_note" class="block mb-1 text-sm font-medium text-gray-700">Catatan</label>
                    <textarea id="reschedule_note"
                              class="block px-4 py-2 w-full rounded-lg border border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                              placeholder="Masukkan alasan reschedule..."></textarea>
                </div>


            </div>
                `,
                        showCancelButton: true,
                        confirmButtonText: 'Reschedule',
                        cancelButtonText: 'Batal',
                        preConfirm: () => {
                            const rescheduleDate = document.getElementById('reschedule_date').value;
                            const rescheduleNote = document.getElementById('reschedule_note').value;

                            if (!rescheduleDate || !rescheduleNote) {
                                Swal.showValidationMessage('Semua input wajib diisi!');
                                return false;
                            }

                            return {
                                rescheduleDate,
                                rescheduleNote
                            };
                        }
                    }).then((rescheduleResult) => {
                        if (rescheduleResult.isConfirmed) {
                            const {
                                rescheduleDate,
                                rescheduleNote
                            } = rescheduleResult.value;

                            const data = {
                                _token: "{{ csrf_token() }}",
                                penilaian_id: idPenilaian,
                                nomor_registrasi: noReg,
                                permohonan_id: permohonanId,
                                reschedule_date: rescheduleDate,
                                reschedule_note: rescheduleNote,
                                keterangan: rescheduleNote
                            };

                            $.ajax({
                                url: `{{ URL::to('/permohonan/store-reschedule-survey') }}/${idPenilaian}`,
                                type: "PUT",
                                cache: false,
                                data: data,
                                dataType: "json",
                                success: function (response) {
                                    if (response.status === 'success') {
                                        Swal.fire('Sukses Reschedule!', response.message,
                                            'success').then(() => {
                                            location.reload();
                                        });
                                    } else {
                                        Swal.fire('Error!', response.message, 'error');
                                    }
                                },
                                error: function (response) {
                                    console.log(response);
                                }
                            });
                        }
                    });

                }
            })

        }


        function surveyorRescheduleJadwalSurvey(element) {
            const permohonanId = element.getAttribute('data-permohonan-id');
            const idPenilaian = element.getAttribute('data-id-penilaian');
            const noReg = element.getAttribute('data-no-reg');
            const debitur = element.getAttribute('data-debitur');
            const waktuPenilaian = element.getAttribute('data-waktu-penilaian');
            let rejectedNote = element.getAttribute('data-rejected-note');
            try {
                rejectedNote = rejectedNote ? JSON.parse(rejectedNote) : null;
            } catch (e) {
                console.warn('Failed to parse rejectedNote:', e);
                rejectedNote = null;
            }
            const note = rejectedNote && typeof rejectedNote === 'string' && rejectedNote.trim() ? String(rejectedNote)
                .trim() : '';

            Swal.fire({
                title: 'Reschedule Jadwal Kunjungan',
                html: `
            <div class="space-y-4 text-left">

                <p class="text-gray-700">
                    Yakin akan Reschedule Jadwal Kunjungan
                    <span class="font-semibold text-blue-600">${noReg}</span>
                    untuk Debitur
                    <span class="font-semibold text-blue-600">${debitur}</span>
                    pada waktu
                    <span class="font-semibold">${window.formatTanggalWaktuIndonesia(waktuPenilaian)}</span>?
                </p>

                <div>
                    <label for="reschedule_date" class="block mb-1 text-sm font-medium text-gray-700">Tanggal Baru</label>
                    <input type="datetime-local" id="reschedule_date"
                           class="block px-4 py-2 w-full rounded-lg border border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                </div>

                <div>
                    <label for="reschedule_note" class="block mb-1 text-sm font-medium text-gray-700">Catatan</label>
                    <textarea id="reschedule_note"
                              class="block px-4 py-2 w-full rounded-lg border border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                              placeholder="Masukkan alasan reschedule..."></textarea>
                </div>
                ${note ? `
                        <p class="text-gray-700"><strong>Catatan Reject:</strong> ${note}</p>
                    ` : ''}

            </div>
        `,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Reschedule',
                preConfirm: () => {
                    const rescheduleDate = document.getElementById('reschedule_date').value;
                    const rescheduleNote = document.getElementById('reschedule_note').value;

                    if (!rescheduleDate || !rescheduleNote) {
                        Swal.showValidationMessage('Semua inputan wajib diisi!');
                        return false;
                    }

                    return {
                        rescheduleDate,
                        rescheduleNote
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const {
                        rescheduleDate,
                        rescheduleNote
                    } = result.value;

                    // Data to send
                    const data = {
                        _token: "{{ csrf_token() }}",
                        penilaian_id: idPenilaian,
                        nomor_registrasi: noReg,
                        permohonan_id: permohonanId,
                        reschedule_date: rescheduleDate,
                        reschedule_note: rescheduleNote,
                        keterangan: rescheduleNote
                    };

                    $.ajax({
                        url: `{{ URL::to('/permohonan/store-reschedule-survey') }}/${idPenilaian}`,
                        type: "PUT",
                        cache: false,
                        data: data,
                        dataType: "json",
                        success: function (response) {
                            if (response.status === 'success') {
                                Swal.fire('Sukses Reschedule!', response.message, 'success').then(
                                    () => {
                                        location.reload();
                                    });
                            } else {
                                Swal.fire('Error!', response.message, 'error');
                            }
                        },
                        error: function (response) {
                            const errorMessage = response.responseJSON?.message ||
                                'Terjadi kesalahan saat memproses data.';
                            Swal.fire('Error!', errorMessage, 'error');
                        }
                    });
                }
            });
        }


        // window.formatTanggalIndonesia(date)
    </script>
@endpush
