@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('activity') }}
@endsection
@section('content')
    @push('styles')
        <style>
            .dropdown {
                position: relative;
                display: inline-block;
            }

            .dropdowns-content {
                display: none;
                position: absolute;
                background-color: white;
                min-width: 224px;
                box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
                z-index: 1;
                margin-top: 0;
                /* Hilangkan jarak antara tombol dan dropdown */
            }

            .dropdown:hover .dropdowns-content {
                display: block;
            }

            /* Tambahkan hover untuk elemen dropdown agar tidak hilang */
            .dropdowns-content:hover {
                display: block;
            }

            .dropdowns-content a {
                color: black;
                padding: 12px 16px;
                text-decoration: none;
                display: block;
            }

            .dropdowns-content a:hover {
                background-color: #f1f1f1;
            }
        </style>
    @endpush
    <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="card-header bg-agi-50" id="basic_settings">
                <div class="flex flex-row gap-1.5 card-title">
                    Activity
                </div>


                <div class="flex-wrap py-5 card-header bg-agi-50">

                    <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="dropdown" data-dropdown="true" data-dropdown-trigger="click">
                            <button
                                class="inline-flex justify-between items-center w-full dropdowns-toggle btn btn-sm btn-light">
                                Pilih Status
                                <i class="ki-outline ki-down dropdown-open:hidden">
                                </i>
                                <i class="hidden ki-outline ki-up dropdown-open:block">
                                </i>
                            </button>
                            <div
                                class="absolute z-50 py-2 mt-2 w-full bg-white rounded-md ring-1 ring-black ring-opacity-5 shadow-lg origin-top-right dropdowns-content max-w-56">
                                <div class="flex flex-col w-full menu menu-default">
                                    <!-- Checkbox untuk All Status -->
                                    <div class="menu-item">
                                        <label class="flex items-center px-4 py-2 text-sm text-gray-700 menu-link">
                                            <input id="select-all" type="checkbox"
                                                class="w-4 h-4 text-blue-600 form-checkbox">
                                            <span class="ml-2">All Status</span>
                                        </label>
                                    </div>
                                    <!-- Dinamis Status dari Backend -->
                                    @foreach ($status_permohonan as $item)
                                        <div class="menu-item">
                                            <label class="flex items-center px-4 py-2 text-sm text-gray-700 menu-link">
                                                <input type="checkbox"
                                                    class="w-4 h-4 text-blue-600 form-checkbox status-checkbox"
                                                    value="{{ strtolower($item->name) }}">
                                                <span class="ml-2">{{ $item->name }}</span>
                                            </label>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </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>

            <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('activity.datatables') }}">

                <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="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">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>
    </div>
@endsection

@push('scripts')
    <script type="module">
        const element = document.querySelector('#permohonan-table');
        const searchInput = document.getElementById('search');
        const statusFilter = document.getElementById('status-filter'); // Dropdown filter element

        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 Permohonan'
                },
                user_id: {
            title: 'User Pemohon',
            render: (item, data) => {
                return data?.user?.name ?? data?.mig_nama_ao ?? '-';
            }},


                branch_id: {
                    title: 'Cabang Pemohon',
                    render: (item, data) => {
                        return data.branch && data.branch.name ? `${data.branch.name}` : '-';
                    },
                },
                debitur_id: {
                    title: 'Debitur',
                    render: (item, data) => {
                        return data.debiture && data.debiture.name ? `${data.debiture.name}` : '-';
                    },
                },
                tujuan_penilaian_id: {
                    title: 'Tujuan Penilaian',
                    render: (item, data) => {
                        return data.tujuan_penilaian && data.tujuan_penilaian.name ?
                            `${data.tujuan_penilaian.name}` : '-';
                    },
                },
                status: {
                    title: 'Status',
                    render: (item, data) => {
                        let badgeClass = '';
                        switch (data.status.toLowerCase()) {
                            case 'revisi':
                                badgeClass = 'badge badge-pill badge-outline badge-warning';
                                break;
                            case 'order':
                                badgeClass = 'badge badge-pill badge-outline badge-info';
                                break;
                            case 'register':
                                badgeClass = 'badge badge-pill badge-outline badge-success';
                                break;
                            case 'survey':
                                badgeClass = 'badge badge-pill badge-outline badge-primary';
                                break;
                            case 'assign':
                                badgeClass = 'badge badge-pill badge-outline badge-dark';
                                break;
                            default:
                                badgeClass = 'badge badge-pill badge-outline';
                        }

                        return `<span class="badge ${badgeClass}">${data.status}</span>`;
                    },
                },
                actions: {
                    title: 'Action',
                    render: (item, data) => {
                        const status = data.status; // Anggap status berada di dalam objek data
                        const dokumenjaminan = data.dokumenjaminan || [];

                        return `
            <div class="flex flex-nowrap justify-center">
                <a class="btn btn-sm btn-icon  ${status === 'freeze' ? 'btn-light' : 'btn-warning btn-clear'}" href="activity/${data.id}/show" title="Lihat Detail">
                    <i class="ki-outline ki-eye"></i>
                </a>
                ${
                    ['survey', 'done', 'proses-laporan', 'laporan', 'paparan'].includes(status) ?
                    dokumenjaminan.map(dokumen => {
                        return `
                                    <a class="btn btn-sm btn-icon btn-clear btn-info" href="surveyor/print-out-inspeksi/${data.id}/${dokumen.id}/${dokumen.jenis_jaminan_id}" title="Print Inspeksi Permohonan">
                                        <i class="ki-outline ki-printer"></i>
                                    </a>
                                `;
                    }).join('') : ''
                }
            </div>
        `;
                    },
                },
            }


        };


        let dataTable = new KTDataTable(element, dataTableOptions);

        function highlightFreezeRows() {
            const table = document.querySelector('#permohonan-table table[data-datatable-table="true"]');
            if (!table) return;

            const rows = table.querySelectorAll('tbody tr');

            rows.forEach(row => {
                const statusCell = row.cells[7];
                if (!statusCell) return;

                const statusText = statusCell.textContent.trim().toLowerCase();

                if (statusText === 'freeze') {
                    row.classList.add('bg-red-400', 'text-white');
                } else {
                    row.classList.remove('bg-red-400', 'text-white');
                }
            });
        }

        // Polling setiap 1 detik untuk sementara
        setInterval(() => {
            highlightFreezeRows();
        }, 500);



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


        const selectAllCheckbox = document.getElementById('select-all');
        const statusCheckboxes = document.querySelectorAll('.status-checkbox');

        statusCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', applyStatusFilter);
        });

        // Event listener untuk "Select All"
        selectAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            statusCheckboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            applyStatusFilter();
        });

        function applyStatusFilter() {
            const selectedStatuses = Array.from(statusCheckboxes)
                .filter(checkbox => checkbox.checked)
                .map(checkbox => checkbox.value);


            if (selectedStatuses.length === 0) {
                dataTable.search('');
                console.log(selectedStatuses);

            } else {

                dataTable.search(selectedStatuses.join(','), true);
                console.log(selectedStatuses);

            }

            const allChecked = Array.from(statusCheckboxes).every(cb => cb.checked);
            selectAllCheckbox.checked = allChecked;
        }
    </script>
@endpush
