@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('surveyor') }}
@endsection
@section('content')
    <div class="w-full grid gap-5 lg:gap-7.5 mx-auto">
        <div class="card border border-agi-100 card-grid min-w-full" data-datatable="false" data-datatable-page-size="10"
            data-datatable-state-save="false" id="permohonan-table" data-api-url="{{ route('surveyor.datatables') }}">
            <div class="card-header light:bg-agi-50 py-5 flex-wrap">
                <h3 class="card-title">
                    Surveyor
                </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 Penilaian" 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('activity.export') }}"> Export to Excel </a>
                    </div>
                </div>
            </div>

            <div class="card-body">
                <div class="scrollable-x-auto">
                    <table class="table table-auto table-border align-middle text-gray-700 font-medium text-sm"
                        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="tanggal_permohonan">
                                    <span class="sort"><span class="sort-label">Tanggal Assigned</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">User Pemohon</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">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]" data-datatable-column="status">
                                    <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="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="card-footer justify-center md:justify-between flex-col md:flex-row gap-3 text-gray-600 text-2sm font-medium">
                    <div class="flex items-center gap-2">
                        Show
                        <select class="select select-sm w-16" data-datatable-size="true" name="perpage"> </select> per
                        page
                    </div>
                    <div class="flex items-center gap-4">
                        <span data-datatable-info="true"></span>
                        <div class="pagination" data-datatable-pagination="true"></div>
                    </div>
                </div>
            </div>
        </div>

    </div>
@endsection

@push('scripts')
    <script>
        function approveReschedule(penilaianId, permohonanId, noReg, debitur, reschedule_date, reschedule_note) {
            Swal.fire({
                title: 'Konfirmasi',
                html: `
            <p>Yakin akan Menyetujui atau Menolak Reschedule Jadwal Kunjungan <b>${noReg}</b> untuk Debitur <b>${debitur}</b>
            pada waktu <b>${window.formatTanggalWaktuIndonesia(reschedule_date)}</b>?</p>
            <p><b>Catatan: </b> <br/>${reschedule_note}</p>
        `,
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                denyButtonColor: '#d33',
                confirmButtonText: 'Approve',
                denyButtonText: 'Reject'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Approve action
                    let token = "{{ csrf_token() }}";
                    let useURL = "{{ URL::to('/surveyor/store-approve-reschedule') }}" + "/" + penilaianId;

                    var input_data = {
                        _token: token,
                        permohonan_id: permohonanId,
                        nomor_registrasi: noReg
                    }
                    $.ajax({
                        url: useURL,
                        type: "PUT",
                        cache: false,
                        data: input_data,
                        success: function(response) {
                            console.log(response);
                            if ('success' == response.status) {
                                Swal.fire('Sukses!', response.message, 'success').then(() => {
                                    location.reload(true);
                                });
                            } else {
                                Swal.fire('Error!', response.message, 'error');
                            }
                        },
                        error: function(response, textStatus, errorThrown) {
                            console.log(response);
                        }
                    });
                } else if (result.isDenied) {
                    // Reject action
                    Swal.fire({
                        title: 'Masukkan Keterangan',
                        input: 'textarea',
                        inputPlaceholder: 'Tuliskan alasan penolakan di sini...',
                        inputAttributes: {
                            'aria-label': 'Tuliskan alasan penolakan di sini'
                        },
                        showCancelButton: true,
                        confirmButtonText: 'Submit',
                        cancelButtonText: 'Batal'
                    }).then((rejectResult) => {
                        if (rejectResult.isConfirmed && rejectResult.value) {
                            let token = "{{ csrf_token() }}";
                            let useURL = "{{ URL::to('/surveyor/store-rejected-reschedule') }}" + "/" +
                                penilaianId;


                            var input_data = {
                                _token: token,
                                permohonan_id: permohonanId,
                                nomor_registrasi: noReg,
                                rejected_note: rejectResult.value,
                                keterangan: rejectResult.value
                            }
                            $.ajax({
                                url: useURL,
                                type: "PUT",
                                cache: false,
                                data: input_data,

                                success: function(response) {
                                    console.log(response);
                                    if ('success' == response.status) {
                                        Swal.fire('Ditolak!', response.message, 'success').then(
                                            () => {
                                                location.reload(true);
                                            });
                                    } else {
                                        Swal.fire('Error!', response.message, 'error');
                                    }
                                },
                                error: function(response, textStatus, errorThrown) {
                                    console.log(response);
                                }
                            });
                        } else if (rejectResult.dismiss === Swal.DismissReason.cancel) {
                            Swal.fire('Dibatalkan', 'Aksi penolakan dibatalkan.', 'info');
                        }
                    });
                }
            });
        }


        function prosesSurvey(permohonanId, nomor_registrasi, penilaianId) {
            Swal.fire({
                title: 'Konfirmasi',
                text: `Yakin akan Melakukan Inspeksi dengan nomor registrasi ${nomor_registrasi}?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, Setujui',
                cancelButtonText: 'Batal',
                denyButtonText: 'Ubah Jadwal Kunjungan',
                denyButtonColor: '#f4b400',
                showDenyButton: true
            }).then((result) => {
                if (result.isConfirmed) {
                    // Mendefinisikan URL dan data
                    let token = "{{ csrf_token() }}";
                    let useURL = `{{ URL::to('/surveyor/store-proses-survey') }}/${permohonanId}`;

                    let input_data = {
                        _token: token,
                        permohonan_id: permohonanId
                    };

                    // Melakukan AJAX request

                    $.ajax({
                        url: useURL,
                        type: "PUT",
                        cache: false,
                        data: input_data,

                        dataType: "json",
                        success: function(response) {
                            if (response.status === 'success') {
                                // Arahkan langsung ke halaman inspeksi
                                window.location.href = `surveyor/${permohonanId}/show?form=inspeksi`;
                            } 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');
                        }
                    });
                }else if (result.isDenied) {

                    // Reject action
                    Swal.fire({
                        title: 'Masukkan Keterangan',
                        input: 'textarea',
                        inputPlaceholder: 'Tuliskan alasan perubahan jadwal di sini dan masukkan tanggal kunjungan...',
                        inputAttributes: {
                            'aria-label': 'Tuliskan alasan perubahan jadwal di sini dan masukkan tanggal kunjungan'
                        },
                        showCancelButton: true,
                        confirmButtonText: 'Submit',
                        cancelButtonText: 'Batal'
                    }).then((rejectResult) => {
                        if (rejectResult.isConfirmed && rejectResult.value) {
                            let token = "{{ csrf_token() }}";
                            let useURL = "{{ URL::to('/surveyor/store-rejected-reschedule') }}" + "/" +
                                penilaianId;


                            var input_data = {
                                _token: token,
                                permohonan_id: permohonanId,
                                nomor_registrasi: nomor_registrasi,
                                rejected_note: rejectResult.value,
                                keterangan: rejectResult.value
                            }
                            $.ajax({
                                url: useURL,
                                type: "PUT",
                                cache: false,
                                data: input_data,

                                success: function(response) {
                                    console.log(response);
                                    if ('success' == response.status) {
                                        Swal.fire('Ditolak!', response.message, 'success').then(
                                            () => {
                                                location.reload(true);
                                            });
                                    } else {
                                        Swal.fire('Error!', response.message, 'error');
                                    }
                                },
                                error: function(response, textStatus, errorThrown) {
                                    console.log(response);
                                }
                            });
                        } else if (rejectResult.dismiss === Swal.DismissReason.cancel) {
                            Swal.fire('Dibatalkan', 'Aksi penolakan dibatalkan.', 'info');
                        }
                    });
                }
            });
        }

        function prosesJadwalSurvey(permohonanId) {
    Swal.fire({
        title: 'Apakah Anda Yakin?',
        html: `
        <div class="text-left space-y-4">
            <p class="text-gray-700 text-center">Untuk membuat jadwal kunjungan, silahkan isi form berikut!</p>
            <div>
                <label for="tanggal_kunjungan" class="block text-sm font-medium text-gray-700 mb-1" style="text-align: start;">Tanggal Kunjungan <span class="text-danger">*</span></label>
                <input type="date" id="tanggal_kunjungan" class="input" style="margin-top: 10px; width: 100%;" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1 mt-2" style="text-align: start;">Waktu Kunjungan (Format 24 Jam) <span class="text-danger">*</span></label>
                <div style="display: flex; align-items: center; gap: 10px; margin-top: 10px;">
    <div style="position: relative; flex: 1;">
        <input type="text" id="jam_kunjungan" class="input" maxlength="2" style="width: 100%; text-align: center; padding-right: 30px;" placeholder="00">
        <div style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); display: flex; flex-direction: column;">
            <button type="button" id="jam_up" class="btn btn-xs btn-light" style="height: 12px; padding: 0 4px; font-size: 10px; margin-bottom: 2px;">▲</button>
            <button type="button" id="jam_down" class="btn btn-xs btn-light" style="height: 12px; padding: 0 4px; font-size: 10px;">▼</button>
        </div>
    </div>
    <span style="font-weight: bold;">:</span>
    <div style="position: relative; flex: 1;">
        <input type="text" id="menit_kunjungan" class="input" maxlength="2" style="width: 100%; text-align: center; padding-right: 30px;" placeholder="00">
        <div style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); display: flex; flex-direction: column;">
            <button type="button" id="menit_up" class="btn btn-xs btn-light" style="height: 12px; padding: 0 4px; font-size: 10px; margin-bottom: 2px;">▲</button>
            <button type="button" id="menit_down" class="btn btn-xs btn-light" style="height: 12px; padding: 0 4px; font-size: 10px;">▼</button>
        </div>
    </div>
</div>

            </div>
            <div>
                <label for="deskripsi-penilaian" class="block text-sm font-medium text-gray-700 mb-1 mt-2" style="text-align: start;">Keterangan <span class="text-danger">*</span> </label>
                <textarea id="deskripsi-penilaian" class="textarea" placeholder="Masukkan keterangan" style="margin-top: 10px;" required></textarea>
            </div>
        </div>
        `,
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Submit',
        cancelButtonText: 'Batal',
        didOpen: () => {
            // Set default value ke waktu saat ini
            const now = new Date();
            const dateString = now.toISOString().slice(0, 10);
            const hours = now.getHours();
            const minutes = now.getMinutes();

            // Set default values
            document.getElementById('tanggal_kunjungan').value = dateString;
            document.getElementById('jam_kunjungan').value = hours.toString().padStart(2, '0');
            document.getElementById('menit_kunjungan').value = minutes.toString().padStart(2, '0');

            // Handler untuk input jam
            const jamInput = document.getElementById('jam_kunjungan');
            const jamUp = document.getElementById('jam_up');
            const jamDown = document.getElementById('jam_down');

            // Validasi hanya angka untuk jam
            jamInput.addEventListener('input', function(e) {
                this.value = this.value.replace(/[^0-9]/g, '').substring(0, 2);
                let value = parseInt(this.value, 10);

                if (!isNaN(value)) {
                    if (value > 23) {
                        this.value = "00";
                    } else {
                        this.value = value.toString().padStart(2, '0');
                    }
                }
            });

            jamInput.addEventListener('blur', function() {
                if (this.value === "" || isNaN(parseInt(this.value, 10))) {
                    this.value = "00";
                } else {
                    this.value = parseInt(this.value, 10).toString().padStart(2, '0');
                }
            });

            // Button handlers untuk jam
            jamUp.addEventListener('click', function() {
                let value = parseInt(jamInput.value, 10);
                if (isNaN(value)) value = 0;

                value = (value + 1) % 24;
                jamInput.value = value.toString().padStart(2, '0');
            });

            jamDown.addEventListener('click', function() {
                let value = parseInt(jamInput.value, 10);
                if (isNaN(value)) value = 0;

                value = (value - 1 + 24) % 24;
                jamInput.value = value.toString().padStart(2, '0');
            });

            // Handler untuk input menit
            const menitInput = document.getElementById('menit_kunjungan');
            const menitUp = document.getElementById('menit_up');
            const menitDown = document.getElementById('menit_down');

            // Validasi hanya angka untuk menit
            menitInput.addEventListener('input', function(e) {
                this.value = this.value.replace(/[^0-9]/g, '').substring(0, 2);
                let value = parseInt(this.value, 10);

                if (!isNaN(value)) {
                    if (value > 59) {
                        this.value = "00";
                    } else {
                        this.value = value.toString().padStart(2, '0');
                    }
                }
            });

            menitInput.addEventListener('blur', function() {
                if (this.value === "" || isNaN(parseInt(this.value, 10))) {
                    this.value = "00";
                } else {
                    this.value = parseInt(this.value, 10).toString().padStart(2, '0');
                }
            });

            // Button handlers untuk menit
            menitUp.addEventListener('click', function() {
                let value = parseInt(menitInput.value, 10);
                if (isNaN(value)) value = 0;

                value = (value + 1) % 60;
                menitInput.value = value.toString().padStart(2, '0');
            });

            menitDown.addEventListener('click', function() {
                let value = parseInt(menitInput.value, 10);
                if (isNaN(value)) value = 0;

                value = (value - 1 + 60) % 60;
                menitInput.value = value.toString().padStart(2, '0');
            });
        },
        preConfirm: () => {
            // Ambil nilai input
            const tanggalKunjungan = document.getElementById('tanggal_kunjungan').value;
            let jamKunjungan = document.getElementById('jam_kunjungan').value;
            let menitKunjungan = document.getElementById('menit_kunjungan').value;
            const keteranganInspeksi = document.getElementById('deskripsi-penilaian').value;

            // Validasi input: cek apakah input kosong
            if (!tanggalKunjungan.trim()) {
                Swal.showValidationMessage('Harap mengisi Tanggal Kunjungan.');
                return false;
            }
            if (!jamKunjungan || !menitKunjungan) {
                Swal.showValidationMessage('Harap mengisi Waktu Kunjungan.');
                return false;
            }
            if (!keteranganInspeksi.trim()) {
                Swal.showValidationMessage('Harap mengisi Keterangan.');
                return false;
            }

            // Pastikan format 2 digit
            jamKunjungan = parseInt(jamKunjungan, 10).toString().padStart(2, '0');
            menitKunjungan = parseInt(menitKunjungan, 10).toString().padStart(2, '0');

            // Gabungkan tanggal dan waktu dalam format ISO
            const datetimeValue = `${tanggalKunjungan}T${jamKunjungan}:${menitKunjungan}`;

            // Jika semua valid, kembalikan data
            return {
                tanggal: datetimeValue,
                keterangan: keteranganInspeksi
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const {
                tanggal,
                keterangan
            } = result.value;

            let token = "{{ csrf_token() }}";
            let useURL = "/surveyor/store-jadwal/" + permohonanId;

            let input_data = {
                _token: token,
                id: permohonanId,
                waktu_penilaian: tanggal,
                deskripsi_penilaian: keterangan,
                keterangan:'Permintaan Jadwal Kujungan: ' + window.formatTanggalWaktuIndonesia(tanggal) + ', ' + keterangan
            };

            $.ajax({
                url: useURL,
                type: "POST",
                cache: false,
                data: input_data,
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Berhasil!', 'Berhasil membuat jadwal.', 'success').then(
                        () => {
                            window.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');
                }
            });
        }
    });
}
    </script>

    <script type="module">
        const element = document.querySelector('#permohonan-table');
        const searchInput = document.getElementById('search');
        const statusFilter = document.getElementById('status-filter');
        const apiUrl = element.getAttribute('data-api-url');
        const dataTableOptions = {
            apiEndpoint: apiUrl,
            pageSize: 5,
            order: [{
                column: 'nomor_registrasi',
                dir: 'asc'
            }], // Default order by 'nomor_registrasi' ascending
            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',
                },
                tanggal_permohonan: {
                    title: 'Tanggal Assigned',
                },
                user_id: {
                    title: 'User Pemohon',
                    render: (item, data) => data.user ? `${data.user.name}` : 'N/A',
                },
                branch_id: {
                    title: 'Cabang Pemohon',
                    render: (item, data) => data.branch ? `${data.branch.name}` : 'N/A',
                },
                debitur_id: {
                    title: 'Debitur',
                    render: (item, data) => {
                        return data.debiture ? `${data.debiture.name}` : 'N/A';
                    },
                },
                tujuan_penilaian_id: {
                    title: 'Tujuan Penilaian',
                    render: (item, data) => data.tujuan_penilaian ? `${data.tujuan_penilaian.name}` : 'N/A',
                },
                jenis_fasilitas_kredit_id: {
                    title: 'Fasilitas Kredit',
                    render: (item, data) => data.jenis_fasilitas_kredit ? `${data.jenis_fasilitas_kredit.name}` : 'N/A',
                },
                status: {
                    title: 'status',
                    render: (item, data) => {
                        let tooltip = '';

                        if (data.status === 'revisi-laporan' || data.status === 'revisi-survey') {
                            tooltip = data.keterangan || '';
                        } else if (data.status === 'reschedule') {
                            tooltip = data.penilaian?.reschedule_note || '';
                        }

                        return `
                        <button
                            class="badge badge-sm badge-default uppercase flex justify-center"
                            title="${tooltip}">
                            ${data.status}
                        </button>`;
                    }
                },
                actions: {
                    title: 'Action',
                    render: (item, data) => {
                        let actionHtml = '';

                        if (data.status === 'request-reschedule') {
                            actionHtml += `
                <button class="btn btn-sm btn-icon btn-clear btn-success"
                        onclick="approveReschedule('${data.penilaian.id}','${data.id}', '${data.nomor_registrasi}', '${data.debiture?.name}', '${data.penilaian.reschedule_date}', '${data.penilaian.reschedule_note}')"
                        title="Approve Reschedule">
                   <i class="ki-filled ki-double-check"></i>
                </button>
            `;
                        } else {
                            if (!data.penilaian.waktu_penilaian) {
                                actionHtml += `
                    <a class="btn btn-sm btn-icon btn-clear btn-primary"
                       onclick="prosesJadwalSurvey(${data.penilaian.id})"
                       title="Buat Jadwal Kunjungan">
                        <i class="ki-filled ki-calendar-edit"></i>
                    </a>
                `;

                                if (data.penilaian.waktu_penilaian && data.penilaian.authorized_status == null) {
                                    actionHtml += `
                        <span class="badge badge-xs badge-outline badge-warning text-4xs">Menunggu Pemohon</span>
                    `;
                                }
                            } else if (data.status === 'approved-reschedule' || data.status ===
                                'rejected-reschedule' || data.status === 'request-jadwal') {
                                actionHtml += `
                    <span class="badge badge-xs badge-outline badge-warning text-4xs">Menunggu Pemohon</span>
                `;
                            } else if (data.status === 'proses-survey') {
                                actionHtml += `
                     <a class="btn btn-sm btn-icon btn-clear btn-clarity"
                        onclick="prosesSurvey(${data.id}, '${data.nomor_registrasi}', '${data.penilaian.id}')"
                       title="Masuk Form Inspeksi">
                       <i class="ki-filled ki-tablet-ok"></i>
                    </a>
                `;
                            } else {
                                // Tombol Lihat Form Inspeksi dan Freeze Survey
                                actionHtml += `
                    <a class="btn btn-sm btn-icon btn-clear btn-warning"
                       href="surveyor/${data.id}/show?form=inspeksi"
                       title="Lihat Form Inspeksi">
                        <i class="ki-outline ki-eye"></i>
                    </a>

                `;
                            }
                        }

                        return actionHtml;
                    }
                }

            }
        };

        let dataTable = new KTDataTable(element, dataTableOptions);

        searchInput.addEventListener('input', function() {
            const searchValue = this.value.trim();
            dataTable.search(searchValue, true);
        });

        // statusFilter.addEventListener('change', function() {
        //     const selectedStatus = this.value;
        //     dataTable.search(selectedStatus);
        // });

        function convertDate(date) {
            const createdAt = new Date(date);
            const day = String(createdAt.getDate()).padStart(2, '0');
            const month = String(createdAt.getMonth() + 1).padStart(2, '0');
            const year = createdAt.getFullYear();
            return `${day}-${month}-${year}`;
        }
    </script>
@endpush
