@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('spk') }}
@endsection

@section('content')
    <div class="grid">
        <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="spk-table" data-api-url="{{ route('spk.datatables') }}">
            <div class="card-header bg-agi-50 py-5 flex-wrap">
                <h3 class="card-title">
                    Daftar SPK
                </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 SPK" 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 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="code">
                                <span class="sort"> <span class="sort-label"> Nomor Penawaran </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="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="date_range">
                                <span class="sort"> <span class="sort-label"> Tanggal Penawaran </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="tujuan_penilaian_kjpp_id">
                                <span class="sort"> <span class="sort-label"> Tujuan Penilaian KJPP </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="kjpp_data">
                                <span class="sort"> <span class="sort-label">KJPP Data</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 type="text/javascript">
    function spkCreate(regId, sla)
    {
        const csrf = '{{ @csrf_token() }}';
        if (!sla) {
            Swal.fire({
                title: 'Input SLA',
                input: 'number',
                inputAttributes: {
                    min: 1,
                    step: 1
                },
                showCancelButton: true,
                confirmButtonText: 'Submit',
                showLoaderOnConfirm: true,
                preConfirm: (inputValue) => {
                    if (inputValue) {
                        return fetch(`/spk/update-sla/${regId}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': `${csrf}`
                            },
                            body: JSON.stringify({ sla: inputValue })
                        })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error(response.statusText)
                                }
                                return response.json()
                            })
                            .catch(error => {
                                Swal.showValidationMessage(
                                    `Request failed: ${error}`
                                )
                            })
                    } else {
                        Swal.showValidationMessage('SLA is required')
                    }
                },
                allowOutsideClick: () => !Swal.isLoading()
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'SLA updated successfully',
                        icon: 'success'
                    }).then(() => {
                        // Redirect to edit page after successful SLA update
                        window.location.href = "{{ url('/') }}/spk/"+regId+"/edit";
                    });
                }
            });
        } else {
            // If SLA is not empty, directly redirect to edit page
            window.location.href = "{{ url('/') }}/spk/"+regId+"/edit";
        }
    }

</script>
<script type="module">
    const element = document.querySelector('#spk-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',
                render: (item, data) => {
                    return `${data.permohonan.nomor_registrasi}`;
                },
            },
            code: {
                title: 'Nomor Penawaran',
                render: (item, data) => {
                   if(data.code) {
                       return `${data.code}`;
                   }

                   return '-';
                },
            },
            tanggal_permohonan: {
                title: 'Tanggal Permohonan',
                render: (item, data) => {
                    return `${data.permohonan.tanggal_permohonan}`;
                },
            },
            user_id: {
                title: 'User Pemohon',
                render: (item, data) => {
                    return `${data.permohonan.user.name}`;
                },
            },
            branch_id: {
                title: 'Cabang Pemohon',
                render: (item, data) => {
                    return `${data.permohonan.branch.name}`;
                },
            },
            debitur_id: {
                title: 'Debitur',
                render: (item, data) => {
                    if (data.permohonan.debiture) {
                        return `${data.permohonan.debiture.name}`;
                    }
                    return "-";
                },
            },
            date_range: {
                title: 'Tanggal Penawaran'
            },
            tujuan_penilaian_id: {
                title: 'Tujuan Penilaian',
                render: (item, data) => {
                    return `${data.permohonan.tujuan_penilaian.name}`;
                },
            },
            tujuan_penilaian_kjpp_id: {
                title: 'Tujuan Penilaian KJPP',
                render: (item, data) => {
                    if(data.tujuan_penilaian_kjpp) {
                        return `${data.tujuan_penilaian_kjpp.name}`;
                    }

                    return '-';
                },
            },
            kjpp_data: {
                title: 'Nama KJPP Terpilih',
                render: (item, data) => {
                    return `${data.nama_kjpp_sebelumnya}`+'<br />'
                            +`${data.biaya_kjpp_sebelumnya}`+'<br /> '
                            +`${data.tanggal_penilaian_sebelumnya}`;
                },
            },
            status: {
                title: 'Status',
                render: (item, data) => {
                    return `${data.status}`.toUpperCase();
                },
            },
            actions: {
                title: 'Status',
                render: (item, data) => {
                    console.log(data.id);
                    var spkShow ='';
                    var spkCreate='';
                    if(!data.spk_dokumen_path)
                    {
                        spkCreate=`<a class="btn btn-sm btn-icon btn-clear btn-info" title="Buat SPK" onclick="spkCreate(${data.id}, ${data.permohonan.sla})" >
                            <i class="ki-outline ki-notepad-edit"></i>
                        </a>`;
                    }
                    else
                    {
                        spkShow =`<div class="flex flex-nowrap justify-center">
                        <a href="/spk/${data.id}/download" class="btn btn-sm btn-icon btn-clear btn-primary" title="Download SPK">
                            <i class="ki-filled ki-cloud-download"></i>
                        </a> `;
                        if(data.status==='spk') {
                            spkCreate = `<a class="btn btn-sm btn-icon btn-clear btn-info" title="Buat SPK" onclick="spkCreate(${data.id}, ${data.permohonan.sla})" >
                            <i class="ki-outline ki-notepad-edit"></i>
                        </a>`;
                        }
                    }

                    return `<div class="flex flex-nowrap justify-center">`
                             +spkShow+spkCreate+
                             `</div>`;
                },
            }
        },
    };

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

    });

</script>
@endpush

