@extends('layouts.main')

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

@section('content')
    <div class="grid">
        <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="debitur-table" data-api-url="{{ route('debitur.datatables') }}">
            <div class="flex-wrap py-5 card-header bg-agi-50">
                <h3 class="card-title">
                    Daftar Debitur
                </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 Debitur" 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('debitur.export') }}"> Export to Excel </a>
                        @if(auth()->user()->hasAnyRole(['administrator', 'pemohon-ao','admin']))
                            <a class="btn btn-sm btn-primary" href="{{ route('debitur.create') }}"> Tambah Debitur </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-[50px]" data-datatable-column="cif">
                                    <span class="sort"> <span class="sort-label"> Cif </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px]" data-datatable-column="nomor_rekening">
                                    <span class="sort"> <span class="sort-label"> Nomor Rekening </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px]" data-datatable-column="name">
                                    <span class="sort"> <span class="sort-label"> Debitur </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px]" data-datatable-column="branch">
                                    <span class="sort"> <span class="sort-label"> Cabang </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px]" data-datatable-column="nomor_id">
                                    <span class="sort"> <span class="sort-label"> Nomor ID </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px]" data-datatable-column="npwp">
                                    <span class="sort"> <span class="sort-label"> NPWP </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px]" data-datatable-column="phone">
                                    <span class="sort"> <span class="sort-label"> Phone </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px]" data-datatable-column="address">
                                    <span class="sort"> <span class="sort-label"> Alamat KTP</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>
        const userRoles = @json(auth()->user()->roles->pluck('name'));
    </script>

    <script type="text/javascript">
        window.addEventListener('DOMContentLoaded', function() {

        })

        function deleteData(data) {
            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, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        }
                    });

                    $.ajax(`debitur/${data}`, {
                        type: 'DELETE'
                    }).then((response) => {
                        swal.fire('Deleted!', 'User has been deleted.', 'success').then(() => {
                            window.location.reload();
                        });
                    }).catch((error) => {
                        Swal.fire('Error!', error.responseJSON.message, 'error');
                    });
                }
            })
        }
    </script>
    <script type="module">
        const element = document.querySelector('#debitur-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();
                    },
                },
                cif: {
                    title: 'CIF',
                },
                nomor_rekening: {
                    title: 'Nomor Rekening',
                },
                name: {
                    title: 'Debitur',
                },
                branch: {
                    title: 'Cabang',
                    render: (item, data, context) => {
                        return `${data.branch.name}`;
                    },
                },
                nomor_id: {
                    title: 'Nomor ID',
                },
                npwp: {
                    title: 'NPWP',
                },
                phone: {
                    title: 'Phone',
                },
                address: {
                    title: 'Alamat KTP',
                },
                actions: {
                    title: 'Status',
                    render: (item, data) => {
                        let actionHtml = `<div class="flex flex-nowrap justify-center">`;

                        // Fungsi helper untuk memeriksa peran
                        const hasRole = (roles) => roles.some(role => userRoles.includes(role));

                        // Fungsi helper untuk memeriksa status permohonan
                        const hasValidStatus = (permohonan) => ['order', 'revisi'].includes(permohonan.status);

                        // Periksa apakah permohonan ada dan merupakan array
                        const permohonanArray = Array.isArray(data.permohonan) ? data.permohonan : [];

                        // Periksa apakah ada setidaknya satu permohonan dengan status yang valid
                        const hasAnyValidPermohonan = permohonanArray.some(hasValidStatus);

                        if (hasRole(['administrator','admin']) && hasAnyValidPermohonan || data.permohonan.length < 1) {
                            actionHtml += `
                            <a class="btn btn-sm btn-icon btn-clear btn-info" href="/debitur/${data.id}/edit">
                                <i class="ki-outline ki-notepad-edit"></i>
                            </a>`;
                        }

                        if (hasRole(['administrator', 'pemohon-ao','admin']) && data.permohonan.length < 1) {
                            actionHtml += `
                <a onclick="deleteData(${data.id})" class="delete btn btn-sm btn-icon btn-clear btn-danger">
                    <i class="ki-outline ki-trash"></i>
                </a>`;
                        }

                        actionHtml += `</div>`;
                        return actionHtml;
                    },
                }
            },
        };

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

        });
    </script>
@endpush
