@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('penilai') }}
@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="penilai-table" data-api-url="{{ route('penilai.dataForTables') }}">
            <div class="flex-wrap py-5 card-header bg-agi-50">
                <h3 class="card-title">
                    Penilai
                </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 Penilai" 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="#"> Export to Excel </a>
                    </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="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="branch_id">
                                    <span class="sort"> <span class="sort-label"> Pemohon(Cabang/Direktorat) </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="user_id">
                                    <span class="sort"> <span class="sort-label"> AO </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]" data-datatable-column="jenis_fasilitas_kredit_id">
                                    <span class="sort"> <span class="sort-label"> Fasilitas Kredit </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="jenis_laporan">
                                    <span class="sort"> <span class="sort-label"> Jenis Laporan </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="tanggal_survei">
                                    <span class="sort"> <span class="sort-label"> Tanggal Survei </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="due_date_sla">
                                    <span class="sort"> <span class="sort-label"> Due Date SLA </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="status">
                                    <span class="sort"> <span class="sort-label"> Status</span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px] text-center" 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 type="text/javascript">
        function formatDate(date) {
            const day = date.getDate().toString().padStart(2, '0');
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            // Months are 0-indexed
            const year = date.getFullYear();

            return `${day} ${getIndonesianMonth(month)} ${year}`;
        }

        function getIndonesianMonth(month) {
            const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
            ];
            return months[month -
                1];
        }
    </script>
    <script type="module">
        const element = document.querySelector('#penilai-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',
                },
                debitur_id: {
                    title: 'Debitur',
                    render: (item, data) => {
                        return data.debiture && data.debiture.name ? `${data.debiture.name}` : '-';
                    },
                },
                branch_id: {
                    title: 'Cabang Pemohon',
                    render: (item, data) => {
                        return data.branch && data.branch.name ? `${data.branch.name}` : '-';
                    },
                },
                user_id: {
                    title: 'User Pemohon',
                    render: (item, data) => {
                        return data.user && data.user.name ? `${data.user.name}` : '-';
                    },
                },
                tujuan_penilaian_id: {
                    title: 'Tujuan Penilaian',
                    render: (item, data) => {
                        return data.tujuan_penilaian && data.tujuan_penilaian.name ?
                            `${data.tujuan_penilaian.name}` : '-';
                    },
                },
                jenis_fasilitas_kredit_id: {
                    title: 'Fasilitas Kredit',
                    render: (item, data) => {
                        return data.jenisfasilitas_kredit && data.jenisfasilitas_kredit.name ?
                            `${data.jenisfasilitas_kredit.name}` : '-';
                    },
                },
                jenis_laporan: {
                    title: 'Jenis Laporan',
                    render: (item, data) => {
                        return data.penilai?.type;
                    },
                },
                tanggal_survei: {
                    title: 'Tanggal Survei',
                    render: (item, data) => {
                        if (data.penilaian.waktu_penilaian) {
                            return `${formatDate(new Date(data.penilaian.waktu_penilaian))}`;
                        }
                        return `${formatDate(new Date(data.penilaian.created_at))}`;
                    },
                },
                due_date_sla: {
                    title: 'Due Date SLA',
                    render: (item, data) => {
                        const tujuan_penilaian = data.tujuan_penilaian.name;
                        const tipe_laporan = data.penilai?.type;
                        const nilai_plafond = data.penilaian.nilaiPlafond?.name;
                        let waktu_penilaian = new Date(data.penilaian.created_at);
                        if (data.penilaian.waktu_penilaian) {
                            waktu_penilaian = new Date(data.penilaian.waktu_penilaian);
                        }

                        if (tujuan_penilaian.name === "RAP") {
                            waktu_penilaian.setDate(waktu_penilaian.getDate() + 3);
                        } else {
                            if (tipe_laporan === "sederhana") {
                                waktu_penilaian.setDate(waktu_penilaian.getDate() + 2);
                            } else if (tipe_laporan === "standar") {
                                if (nilai_plafond === "2 M - 5 M") {
                                    waktu_penilaian.setDate(waktu_penilaian.getDate() + 3);
                                } else if (nilai_plafond === "< 2M") {
                                    waktu_penilaian.setDate(waktu_penilaian.getDate() + 3);
                                } else {
                                    waktu_penilaian.setDate(waktu_penilaian.getDate() + 5);
                                }
                            }
                        }

                        return formatDate(waktu_penilaian);

                    },
                },
                status: {
                    title: 'Status',
                    render: (item, data) => {
                        if (data.penawaran) {
                            return `<span class="flex justify-center uppercase badge badge-sm badge-default">${data.penawaran?.status.replace(/-/g, ' ')}</span>`;
                        }

                        return `<span class="flex justify-center uppercase badge badge-sm badge-default">${data.status.replace(/-/g, ' ')}</span>`;
                    },
                },
                actions: {
                    title: 'Action',
                    render: (item, data) => {
                        if (data.status === 'survey-completed' || data.status === 'proses-laporan' || data
                            .status === 'paparan' || data.status === 'proses-paparan' || data.status ===
                            'paparan' || data.status == 'revisi-laporan' || data.status === 'done' || data
                            .status === 'revisi-paparan' || data.status === 'unfreeze-sla' || data.status ===
                            'reject-freeze' || data.penawaran?.status === 'registrasi-final') {
                            return `
                        <div class="flex flex-nowrap gap-1.5 justify-center">
                            <a class="btn btn-sm btn-icon btn-clear btn-info" href="penilai/${data.id}/show">
                                <i class="ki-outline ki-eye"></i>
                            </a>
                            <button type="button"
                            class="btn btn-sm btn-icon btn-clear btn-warning"
                            onclick="surveyorFreeze('${data.id}', '${data.nomor_registrasi}', '${data.debiture?.name}')"
                            title="Freeze SLA">
                        <i class="ki-filled ki-arrow-circle-right"></i>
                        </button>
                        </div>`;
                        } else if (data.status === 'request-freeze') {
                            return `
            <div class="flex flex-nowrap justify-center">
                <a class="btn btn-sm btn-icon btn-clear btn-warning" onclick="showLoadingSwal('Masih dalam proses pengajuan freeze...')">
                    <i class="ki-filled ki-watch"></i>
                </a>
            </div>`;
                        } else if (data.status === 'freeze') {
                            return ` <div class="flex flex-nowrap gap-1.5 justify-center">
                            <a class="btn btn-sm btn-icon btn-clear btn-info" href="penilai/${data.id}/show">
                                <i class="ki-outline ki-eye"></i>
                            </a>
                            </div>`
                        } else {
                            return `<div class="flex flex-nowrap justify-center">
                            <a class="btn btn-sm btn-icon btn-clear btn-success" onclick="showLoadingSwal('Masih Menunggu proses ...')">
                                <i class="ki-filled ki-watch"></i>
                            </a>
                        </div>`
                        }

                    },
                }
            },
        };

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

        });
    </script>

    <script>
        function surveyorFreeze(permohonanId, noReg, debitur) {

            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: "Yakin akan Request Freeze dengan " + noReg + " untuk Debitur " + debitur +
                    " ?",
                icon: 'warning',
                input: 'textarea',
                inputLabel: 'Keterangan',
                inputPlaceholder: 'Masukkan keterangan...',
                inputAttributes: {
                    'aria-label': 'Masukkan keterangan'
                },
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, Lanjutkan!',
                cancelButtonText: 'Batal',
            }).then((result) => {
                if (result.isConfirmed) {
                    const userMessage = result.value || ''; // Ambil pesan dari textarea
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                    });
                    $.ajax({
                        url: `/surveyor/storeFreeze/${permohonanId}`,
                        type: 'POST',
                        data: {
                            keterangan: userMessage
                        },
                        success: (response) => {
                            Swal.fire('Berhasil!',
                                response.message,
                                'success').then(() => {
                                window.location.reload();
                            });
                            console.log(response);
                        },
                        error: (error) => {
                            console.error('Error:', error);
                            Swal.fire('Gagal!', 'Terjadi kesalahan saat melakukan Freeze.',
                                'error');
                        }
                    });
                }
            });

        }

        function showLoadingSwal(message, duration = 5000) {
            Swal.fire({
                title: message,
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                },
                timer: duration, // Durasi dalam milidetik
                timerProgressBar: true, // Menampilkan progres bar timer
            }).then((result) => {
                if (result.dismiss === Swal.DismissReason.timer) {
                    console.log("Dialog loading otomatis ditutup.");
                }
            });
        }

        function hideLoadingSwal() {
            Swal.close();
        }
    </script>
@endpush
