@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="grid gap-5 mx-auto w-full lg:gap-7.5">


        <!-- Filter Card -->
        <div class="border card border-agi-100">
            <div class="py-5 card-header bg-agi-50">
                <h3 class="card-title">Filter Laporan</h3>
            </div>
            <div class="grid gap-4 card-body">
                <!-- Search field at the top, full width -->
                <div class="flex flex-col w-full">
                    <label class="mb-1 text-sm font-medium">Pencarian</label>
                    <label class="input input-sm">
                        <i class="ki-filled ki-magnifier"></i>
                        <input placeholder="Search Laporan Penilaian Jaminan" id="search" type="text" value="">
                    </label>
                </div>

                <!-- Other filter fields in grid layout -->
                <div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
                    <div class="flex flex-col">
                        <label class="mb-1 text-base font-medium">Tanggal Awal</label>
                        <label class="input">
                            <input placeholder="Tanggal Awal" id="start_date" type="date">
                        </label>
                    </div>
                    <div class="flex flex-col">
                        <label class="mb-1 text-base font-medium">Tanggal Akhir</label>
                        <label class="input">
                            <input placeholder="Tanggal Akhir" id="end_date" type="date">
                        </label>
                    </div>
                    <div class="flex flex-col">
                        <label class="mb-1 text-base font-medium">Cabang</label>
                        <select class="select tomselect" id="branch_filter">
                            <option value="">Semua Cabang</option>
                            @foreach (\Modules\Basicdata\Models\Branch::where('status', 1)->get() as $branch)
                                <option value="{{ $branch->id }}">{{ $branch->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="flex flex-col">

                        <label class="mb-1 text-base font-medium">Laporan</label>
                        <select class="select tomselect" name="laporan[]" id="laporan" multiple>
                            <option value="">Semua Laporan</option>
                            @php
                                $status_laporan = ['Standar', 'Sederhana', 'Memo', 'Resume', 'Call Report', 'RAP'];
                            @endphp
                            @foreach ($status_laporan as $item)
                                <option value="{{ strtolower($item) }}">{{ $item }}</option>
                            @endforeach
                        </select>


                    </div>
                </div>

                <!-- Buttons row at the bottom -->
                <div class="grid grid-cols-1 gap-4 mt-2 md:grid-cols-2">
                    <button class="btn btn-sm btn-primary" id="filter_tanggal">
                        <i class="ki-outline ki-filter fs-2 me-1"></i>
                        Terapkan Filter
                    </button>
                    <button class="btn btn-sm btn-light" id="export-btn">
                        <i class="ki-outline ki-file-down fs-2 me-1"></i>
                        Export to Excel
                    </button>
                </div>
            </div>
        </div>


        <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="laporan-penilai-jaminan-table"
            data-api-url="{{ route('laporan-penilai-jaminan.datatables') }}">
            <div class="flex-wrap py-5 card-header bg-agi-50">
                <h3 class="card-title">
                    Daftar Laporan Penilai Jaminan
                </h3>

            </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"
                                        id="check-all" />
                                </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="branch">
                                    <span class="sort"> <span class="sort-label"> Cabang </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">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">Nama 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="jenis_agunan">
                                    <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>

                                <th class="" data-datatable-column="actions">
                                    <span class="sort"><span class="sort-label">Actions</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </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>

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


@push('scripts')
    <script type="module">
        const element = document.querySelector('#laporan-penilai-jaminan-table');

        const searchInput = document.getElementById('search');
        const startDateInput = document.getElementById('start_date');
        const endDateInput = document.getElementById('end_date');
        const branchFilter = document.getElementById('branch_filter');
        const laporanFilter = document.getElementById('laporan');
        const filterTanggalButton = document.getElementById('filter_tanggal');
        const exportButton = document.getElementById('export-btn');

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

        // Export elements
        const exportForm = document.getElementById('export-form');
        const exportStartDate = document.getElementById('export_tanggal_awal');
        const exportEndDate = document.getElementById('export_tanggal_akhir');
        const exportBranchId = document.getElementById('export_branch_id');
        const exportLaporan = document.getElementById('export_laporan');
        const exportStatus = document.getElementById('export_status');
        const exportSelectedIds = document.getElementById('export_selected_ids');
        const exportType = document.getElementById('export_type');
        const exportSearch = document.getElementById('export_search');
        const apiUrl = element.getAttribute('data-api-url');

        // Simple pagination state management
        let currentPage = 1;
        let isReturningFromDetail = false;

        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',
                },
                tanggal_permohonan: {
                    title: 'Tanggal Permohonan',
                    render: (item, data) => {
                        return data.tanggal_permohonan ? window.formatTanggalIndonesia(data.tanggal_permohonan) :
                            '-';
                    },
                },
                branch: {
                    title: 'Cabang',
                    render: (item, data) => {
                        return data.branch && data.branch.name ? `${data.branch.name}` : '-';
                    },
                },
                user_id: {
                    title: 'User Pemohon',
                    render: (item, data) => {
                        return data?.user?.name ?? data?.mig_nama_ao ?? '-';
                    }
                },
                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_agunan: {
                    title: 'Jenis Jaminan',
                    render: (item, data) => {
                        return data.dokumenjaminan.map((item) => {
                            return item.jenis_jaminan ? item.jenis_jaminan.name : '-';
                        }).join(', ');
                    },
                },
                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>`;
                    },
                },
                actions: {
                    title: 'Action',
                    render: (item, data) => {
                        const status = data.status;
                        const dokumenjaminan = data.dokumenjaminan || [];

                        return `
            <div class="flex flex-nowrap gap-1 justify-center">
                ${
                    ['done'].includes(status) ?
                    dokumenjaminan.map(dokumen => {
                        return `
                            <a class="btn btn-sm btn-primary" href="surveyor/print-out-inspeksi/${data.id}/${dokumen.id}/${dokumen.jenis_jaminan_id}">
                                <i class="ki-outline ki-printer"></i>Inspeksi
                            </a>
                            <a class="btn btn-sm btn-info detail-btn" href="laporan-penilai-jaminan/show/${data.id}/${dokumen.id}/${dokumen.jenis_jaminan_id}">
                                <i class="ki-filled ki-eye"></i>Lihat
                            </a>
                            <a class="btn btn-sm btn-success" href="penilai/print-out-laporan/${data.id}/${dokumen.id}/${dokumen.jenis_jaminan_id}">
                                <i class="ki-filled ki-printer"></i>Laporan
                            </a>
                        `;
                    }).join('') : ''
                }
            </div>
        `;
                    }
                }
            },
        };

        let dataTable = new KTDataTable(element, dataTableOptions);
        const fromDetail = true;
        if (fromDetail) {
            isReturningFromDetail = true;
            console.log('Returning from detail page');
            // Remove the parameter from URL
            window.history.replaceState({}, document.title, window.location.pathname);
            setTimeout(() => {
                restoreCurrentPage();
                isReturningFromDetail = false;
            }, 500);
        }

        function getCurrentPageFromDOM() {
            const activePage = document.querySelector('.pagination .btn.active');
            if (activePage) {
                const pageText = activePage.textContent.trim();
                const pageNum = parseInt(pageText);
                return isNaN(pageNum) ? 1 : pageNum;
            }
            return 1;
        }

        function saveCurrentPage() {
            const page = getCurrentPageFromDOM();
            currentPage = page;
            sessionStorage.setItem('currentTablePage', currentPage.toString());
        }

        function restoreCurrentPage() {
            const savedPage = sessionStorage.getItem('currentTablePage');
            if (savedPage && savedPage !== '1') {
                currentPage = parseInt(savedPage);
                console.log('Restoring to page:', currentPage);

                // Use the goPage method to navigate to the saved page
                dataTable.goPage(currentPage);
            }
        }

        // Listen for pagination events to track current page
        element.addEventListener('pagination', function(e) {
            const page = e.detail.page;
            currentPage = page;
            console.log('Page changed to:', page);
        });

        // Alternative: Listen for pagination button clicks
        document.addEventListener('click', function(e) {
            if (e.target.matches('.pagination .btn') && !e.target.closest('.detail-btn')) {
                setTimeout(() => {
                    currentPage = getCurrentPageFromDOM();
                    console.log('Current page updated to:', currentPage);
                }, 100);
            }
        });

        // Detail page redirection
        document.addEventListener('click', function(e) {
            if (e.target.closest('.detail-btn')) {
                e.preventDefault();

                // Save current page before navigating
                const currentPageNum = getCurrentPageFromDOM();
                currentPage = currentPageNum;
                sessionStorage.setItem('currentTablePage', currentPage.toString());
                console.log('Saving page before detail navigation:', currentPage);

                const link = e.target.closest('.detail-btn');
                const href = link.getAttribute('href');
                window.location.href = href;
            }
        });

        // Search functionality
        searchInput.addEventListener('input', function() {
            applyDateFilter();
        });

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

        function applyDateFilter() {
            const startDate = startDateInput.value;
            const endDate = endDateInput.value;
            const branch = branchFilter.value;
            const laporan = Array.from(laporanFilter.selectedOptions).map(option => option.value);

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

            if (startDate) {
                filters.start_date = startDate;
            }

            if (endDate) {
                filters.end_date = endDate;
            }

            if (branch) {
                filters.branch_id = branch;
            }

            if (laporan.length > 0) {
                filters.laporan = laporan;
            }

            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('');
            } else {
                dataTable.search(selectedStatuses.join(','), true);
            }

            dataTable.reload();

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

        // Export functionality
        exportButton.addEventListener('click', function(e) {
            e.preventDefault();

            const selectedIds = getSelectedRowIds();

            if (selectedIds.length > 0) {
                exportData({
                    selected_ids: selectedIds,
                    export_type: 'selected'
                });
            } else if (startDateInput.value && endDateInput.value || getSelectedStatuses().length > 0) {
                exportData({
                    start_date: startDateInput.value,
                    end_date: endDateInput.value,
                    branch_id: branchFilter.value,
                    laporan: Array.from(laporanFilter.selectedOptions).map(option => option.value),
                    status: getSelectedStatuses(),
                    search: searchInput.value,
                    export_type: 'filtered'
                });
            } else if (searchInput.value) {
                exportData({
                    search: searchInput.value,
                    export_type: 'filtered'
                });
            } else {
                exportData({
                    export_type: 'all'
                });
            }
        });

        function exportData(filters = {}) {
            exportStartDate.value = filters.start_date || '';
            exportEndDate.value = filters.end_date || '';
            exportStatus.value = filters.status ? filters.status.join(',') : '';
            exportBranchId.value = filters.branch_id || '';
            exportLaporan.value = filters.laporan ? filters.laporan.join(',') : '';
            exportSelectedIds.value = filters.selected_ids ? filters.selected_ids.join(',') : '';
            exportType.value = filters.export_type || 'all';
            exportSearch.value = filters.search || '';
            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);
        }

        // Save page before leaving (only when not going to detail)
        window.addEventListener('beforeunload', function() {
            if (!isReturningFromDetail) {
                saveCurrentPage();
            }
        });
    </script>
@endpush
