@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('laporan-penilai-jaminan') }}
@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="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="laporan-penilai-jaminan-table"
            data-api-url="{{ route('laporan-penilai-jaminan.datatables') }}">
            <div class="card-header bg-agi-50 py-5 flex-wrap">
                <h3 class="card-title">
                    Daftar Laporan Penilai Jaminan
                </h3>
                <div class="flex flex-wrap gap-2 lg:gap-5">
                    <div class="flex">
                        <label class="input">
                            Start Date
                            <input placeholder="Tanggal Awal" id="tanggal_awal" type="date">
                        </label>
                    </div>
                    <div class="flex">
                        <label class="input">
                            End Date
                            <input placeholder="Tanggal Akhir" id="tanggal_akhir" type="date">
                        </label>
                    </div>
                    <div class="flex">
                        <button class="btn btn-primary" id="filter_tanggal">Filter</button>
                    </div>
                    <div class="flex">
                        <label class="input "> <i class="ki-filled ki-magnifier"> </i>
                            <input placeholder="Search Laporan" id="search" type="text" value="">
                        </label>
                    </div>
                    <div class="flex">
                        <!-- Custom dropdown for status filter -->
                        <div class="dropdown" data-dropdown="true" data-dropdown-trigger="click">
                            <button class="dropdowns-toggle btn  btn-light inline-flex justify-between w-full items-center">
                                Pilih Type Laporan
                                <i class="ki-outline ki-down dropdown-open:hidden">
                                </i>
                                <i class="ki-outline ki-up hidden dropdown-open:block">
                                </i>
                            </button>
                            <div
                                class="dropdowns-content w-full max-w-56 py-2 absolute mt-2 origin-top-right z-50 bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5">
                                <div class="menu menu-default flex flex-col w-full">
                                    <!-- Checkbox untuk All Status -->
                                    <div class="menu-item">
                                        <label class="menu-link flex items-center px-4 py-2 text-sm text-gray-700">
                                            <input id="select-all" type="checkbox"
                                                class="form-checkbox h-4 w-4 text-blue-600">
                                            <span class="ml-2">All Status</span>
                                        </label>
                                    </div>
                                    <!-- Dinamis Status dari Backend -->
                                    @php
                                        $status_laporan = [
                                            'Standar',
                                            'Sederhana',
                                            'Memo',
                                            'Resume',
                                            'Call Report',
                                            'RAP',
                                        ];
                                    @endphp
                                    @foreach ($status_laporan as $item)
                                        <div class="menu-item">
                                            <label class="menu-link flex items-center px-4 py-2 text-sm text-gray-700">
                                                <input type="checkbox"
                                                    class="form-checkbox status-checkbox h-4 w-4 text-blue-600"
                                                    value="{{ strtolower($item) }}">
                                                <span class="ml-2">{{ $item }}</span>
                                            </label>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2.5">
                        <div class="h-[24px] border border-r-gray-200"></div>
                        <button class="btn  btn-light" id="export-button">
                            Export Excel
                        </button>
                    </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="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="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_id">
                                    <span class="sort"><span class="sort-label">Jenis Jaminan</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="laporan">
                                    <span class="sort"><span class="sort-label">Laporan</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </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>

    <!-- Form tersembunyi untuk export -->
    <form id="export-form" action="{{ route('laporan-penilai-jaminan.export') }}" method="GET" class="hidden">
        <input type="hidden" name="tanggal_awal" id="export_tanggal_awal">
        <input type="hidden" name="tanggal_akhir" id="export_tanggal_akhir">
        <input type="hidden" name="status" id="export_status">
        <input type="hidden" name="selected_ids" id="export_selected_ids">
        <input type="hidden" name="export_type" id="export_type" value="all">
    </form>
@endsection

@push('scripts')
    <script type="module">
        const element = document.querySelector('#laporan-penilai-jaminan-table');
        const searchInput = document.getElementById('search');
        const tanggalAwalInput = document.getElementById('tanggal_awal');
        const tanggalAkhirInput = document.getElementById('tanggal_akhir');
        const filterTanggalButton = document.getElementById('filter_tanggal');
        const selectAllCheckbox = document.getElementById('select-all');
        const statusCheckboxes = document.querySelectorAll('.status-checkbox');

        // Export elements
        const exportForm = document.getElementById('export-form');
        const exportButton = document.getElementById('export-button');
        const exportTanggalAwal = document.getElementById('export_tanggal_awal');
        const exportTanggalAkhir = document.getElementById('export_tanggal_akhir');
        const exportStatus = document.getElementById('export_status');
        const exportSelectedIds = document.getElementById('export_selected_ids');
        const exportType = document.getElementById('export_type');

        const apiUrl = element.getAttribute('data-api-url');
        const dataTableOptions = {
            apiEndpoint: apiUrl,
            pageSize: 5,
            params: {
                startDate: '',
                endDate: '',
            },
            order: [{
                column: 'nomor_registrasi',
                dir: 'asc'
            }],

            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',
                },

                user_id: {
                    title: 'User Pemohon',
                    render: (item, data) => {
                        return data.user && data.user.name ? `${data.user.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}` : '-';
                    },
                },
                jenis_jaminan_id: {
                    title: 'Jenis Jaminan',
                    render: (item, data) => {
                        const jenisJaminan = data.dokumenjaminan.map(d => d.jenis_jaminan.name).join(', ');
                        return jenisJaminan || '-';
                    }
                },
                laporan: {
                    title: 'Status',
                    render: (item, data) => {
                        let badgeClass = '';

                        const statusLaporan = data.penilai?.type_penilai || '-';

                        switch (statusLaporan.toLowerCase()) {
                            case 'standar':
                                badgeClass = 'badge badge-pill badge-outline badge-warning';
                                break;
                            case 'sederhana':
                                badgeClass = 'badge badge-pill badge-outline badge-info';
                                break;
                            case 'memo':
                                badgeClass = 'badge badge-pill badge-outline badge-success';
                                break;
                            case 'resume':
                                badgeClass = 'badge badge-pill badge-outline badge-primary';
                                break;
                            case 'call-report':
                                badgeClass = 'badge badge-pill badge-outline badge-dark';
                                break;
                            default:
                                badgeClass = 'badge badge-pill badge-outline';
                        }

                        return `<span class="badge ${badgeClass}">${statusLaporan}</span>`;
                    },
                },

            },

        };

        let dataTable = new KTDataTable(element, dataTableOptions);

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

        // Filter by date range
        filterTanggalButton.addEventListener('click', function() {
            applyDateFilter();
        });

        function applyDateFilter() {
            const tanggalAwal = tanggalAwalInput.value;
            const tanggalAkhir = tanggalAkhirInput.value;

            let filters = {};
            if (searchInput.value) {
                filters.search = searchInput.value;
            }

            if (tanggalAwal) {
                filters.tanggal_awal = tanggalAwal
            }

            if (tanggalAkhir) {
                filters.tanggal_akhir = tanggalAkhir
            }

            dataTable.search(filters);
        }

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

        // Select All functionality
        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);
            }

            dataTable.reload();

            // Update "Select All" checkbox state
            const allChecked = Array.from(statusCheckboxes).every(cb => cb.checked);
            selectAllCheckbox.checked = allChecked;
        }

        // Single export button functionality
        exportButton.addEventListener('click', function(e) {
            e.preventDefault();

            // Check if any rows are selected
            const selectedIds = getSelectedRowIds();

            // Determine export type based on context
            if (selectedIds.length > 0) {
                // If rows are selected, export those
                exportData({
                    selected_ids: selectedIds,
                    export_type: 'selected'
                });
            } else if (tanggalAwalInput.value && tanggalAkhirInput.value || getSelectedStatuses().length > 0) {
                // If filters are applied but no rows selected, export filtered data
                exportData({
                    tanggal_awal: tanggalAwalInput.value,
                    tanggal_akhir: tanggalAkhirInput.value,
                    status: getSelectedStatuses(),
                    export_type: 'filtered'
                });
            } else {
                // If no selection and no filters, export all
                exportData({
                    export_type: 'all'
                });
            }
        });

        function exportData(filters = {}) {
            // Set filter values in the hidden form
            exportTanggalAwal.value = filters.tanggal_awal || '';
            exportTanggalAkhir.value = filters.tanggal_akhir || '';
            exportStatus.value = filters.status ? filters.status.join(',') : '';
            exportSelectedIds.value = filters.selected_ids ? filters.selected_ids.join(',') : '';
            exportType.value = filters.export_type || 'all';

            // Submit the form
            exportForm.submit();
        }

        function getSelectedStatuses() {
            return Array.from(statusCheckboxes)
                .filter(checkbox => checkbox.checked)
                .map(checkbox => checkbox.value);
        }

        function getSelectedRowIds() {
            const checkboxes = document.querySelectorAll('[data-datatable-row-check="true"]:checked');
            return Array.from(checkboxes).map(checkbox => checkbox.value);
        }
    </script>
@endpush
