@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('otorisator.' . strtolower($header)) }}
@endsection

@section('content')
    <div class="grid gap-5 mx-auto w-full lg:gap-7.5">
        <div class="pb-2.5 border card border-agi-100">
            <div class="min-w-full card-grid" data-datatable="false" data-datatable-page-size="10"
                 data-datatable-state-save="false" id="permohonan-table"
                 data-api-url="{{ route('otorisator.sla.datatables') }}">
                <div class="flex-wrap py-5 card-header bg-agi-50">
                    <h3 class="card-title">
                        Daftar {{ $header }}
                    </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('permohonan.export') }}"> 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="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="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="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="alasan">
                                    <span class="sort"> <span class="sort-label"> Alasan </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="request">
                                    <span class="sort"> <span class="sort-label"> Request </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="approval_so">
                                    <span class="sort"> <span class="sort-label"> Approval SO </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>

                                <th class="min-w-[150px]" data-datatable-column="approval_eo">
                                    <span class="sort"> <span class="sort-label"> Approval EO </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>

                                <th class="min-w-[150px]" data-datatable-column="approval_dd">
                                    <span class="sort"> <span class="sort-label"> Approval DD </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>
    </div>
@endsection



@push('scripts')
    <script>
        function otorisator() {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        }
                    });

                    $.ajax(`permohonan/${data}`, {
                        type: 'POST'
                    }).then((response) => {
                        swal.fire('eddited!', 'Pelaporan has been edited.', 'success').then(() => {
                            window.location.reload();
                        });
                    }).catch((error) => {
                        console.error('Error:', error);
                        Swal.fire('Error!', 'An error occurred while file.', 'error');
                    });
                }
            })
        }
    </script>



    <script type="module">
        const element = document.querySelector('#permohonan-table');
        const searchInput = document.getElementById('search');

        const dataHeader = @json($header);


        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',
                    render: (item, data) => {
                        return `${data.permohonan.nomor_registrasi}`;
                    },
                },
                tanggal_permohonan: {
                    title: 'Tanggal Permohonan',
                    render: (item, data) => {
                        return `${window.formatTanggalIndonesia(data.created_at)}`;
                    },
                },
                user_id: {
                    title: 'User Pemohon',
                    render: (item, data) => {
                        return `${data.user.name}`;
                    },
                },
                debitur_id: {
                    title: 'Debitur',
                    render: (item, data) => {
                        return `${data.permohonan.debiture.name}`;
                    },
                },
                keterangan: {
                    title: 'Alasan',
                },
                request: {
                    title: 'Request',
                },
                approval_so: {
                    title: 'Approval SO',
                    render: (item, data) => {
                        if(data.approve_so) {
                            return `${data.approve_so.name} | ${window.formatTanggalIndonesia(data.approve_so_at)}`;
                        }
                        return '';
                    },
                },
                approval_eo: {
                    title: 'Approval EO',
                    render: (item, data) => {
                        if(data.approve_eo) {
                            return `${data.approve_eo.name} | ${window.formatTanggalIndonesia(data.approve_eo_at)}`;
                        }
                        return '';
                    },
                },
                approval_dd: {
                    title: 'Approval DD',
                    render: (item, data) => {
                        if(data.approve_dd) {
                            return `${data.approve_dd.name} | ${window.formatTanggalIndonesia(data.approve_dd_at)}`;
                        }
                        return '';
                    },
                },
                actions: {
                    title: 'Status',
                    render: (item, data) => {
                        const userRoles = @json(Auth::user()->getRoleNames());
                        const isAdmin = userRoles.includes('administrator');

                        let buttons = `
        <div class="flex flex-nowrap justify-center">
            <a class="btn btn-sm btn-icon btn-clear btn-warning" href="otorisator/show/${data.id}/${dataHeader}">
                <i class="ki-outline ki-eye"></i>
            </a>
    `;
                        buttons += `</div>`;
                        return buttons;
                    },
                }
            },
        };

        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 otorisatorData(dataId) {
            const dataHeader = @json($header);
            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: `Untuk melakukan otorisator ${dataHeader}!`,
                icon: 'warning',
                input: 'textarea', // Menambahkan 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: `/otorisator/otorisator/${dataId}/${dataHeader}`,
                        type: 'POST',
                        data: {
                            message: userMessage // Kirim pesan sebagai bagian dari data
                        },
                        success: (response) => {
                            Swal.fire('Berhasil!', 'Data berhasil diotorisasi. Menunggu Approval EO dan atau DD', 'success').then(() => {
                                window.location.reload();
                            });
                            console.log(response);
                        },
                        error: (error) => {
                            console.error('Error:', error);
                            Swal.fire('Gagal!', 'Terjadi kesalahan saat melakukan otorisator.',
                                '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.');
                }
            });
        }
    </script>
@endpush
