<div class="filter-section mb-3">
    <form id="filterForm" 
          action="{{ route('superadmin.purchase.v1.index') }}" 
          method="get" 
          class="row g-2 align-items-end" 
          data-ajax-url="{{ route('superadmin.purchase.v1.index') }}">
          
        @php
            $startDate = request()->input('filters.purchase_date:range')
                ? explode(' - ', request()->input('filters.purchase_date:range'))[0]
                : null;
            $endDate = request()->input('filters.purchase_date:range')
                ? explode(' - ', request()->input('filters.purchase_date:range'))[1]
                : null;
            $dateRange = isset($startDate) ? $startDate . ' - ' . $endDate : null;
        @endphp

        <div class="col-md-2">
            <label class="form-label">Date Range</label>
            <input 
                type="text" 
                class="form-control filter-item date-range" 
                name="filters[purchase_date:range]"
                value="{{ $dateRange }}"
                autocomplete="off"
                placeholder="Select Date Range"
            />
        </div>

        <div class="col-md-2">
            <label class="form-label">Vendors</label>
            <select class="form-control filter-item" name="filters[vendor_id]">
                <option value="">Select Vendor</option>
                @foreach ($vendors ?? [] as $vendor)
                    <option value="{{ $vendor->id }}" {{ request()->input('filters.vendor_id') == $vendor->id ? 'selected' : '' }}>
                        {{ $vendor->company }}
                    </option>
                @endforeach
            </select>
        </div>

        <div class="col-md-2">
            <label class="form-label">Invoice No</label>
            <input 
                type="text" 
                class="form-control filter-item" 
                placeholder="Invoice No" 
                name="filters[vendor_invoice_no]"
                value="{{ request()->input('filters.vendor_invoice_no', '') }}"
            />
        </div>

        <div class="col-md-2">
            <label class="form-label">Payment Status</label>
            <select class="form-control filter-item" name="filters[payment_status]">
                <option value="">All</option>
                @foreach (['paid', 'partial', 'unpaid'] as $status)
                    <option value="{{ $status }}" {{ request()->input('filters.payment_status') == $status ? 'selected' : '' }}>
                        {{ ucfirst($status) }}
                    </option>
                @endforeach
            </select>
        </div>

        <div class="col-md-2">
            <label class="form-label">Invoice Age</label>
            @php
                $selectedRange = request()->input('filters.invoice_age_range'); // new name for range
                $now = now();
                $ranges = [
                    '0-15' => [
                        'label' => '0–15 Days',
                        'gte' => $now->copy()->subDays(15)->format('Y-m-d'),
                        'lte' => $now->format('Y-m-d'),
                    ],
                    '15-30' => [
                        'label' => '15–30 Days',
                        'gte' => $now->copy()->subDays(30)->format('Y-m-d'),
                        'lte' => $now->copy()->subDays(15)->format('Y-m-d'),
                    ],
                    '30-45' => [
                        'label' => '30–45 Days',
                        'gte' => $now->copy()->subDays(45)->format('Y-m-d'),
                        'lte' => $now->copy()->subDays(30)->format('Y-m-d'),
                    ],
                    '45+' => [
                        'label' => '45+ Days',
                        'lte' => $now->copy()->subDays(45)->format('Y-m-d'),
                    ],
                ];
            @endphp
        
            <select class="form-control filter-item" name="filters[invoice_age_range]">
                <option value="">All</option>
                @foreach ($ranges as $key => $range)
                    <option value="{{ $key }}" {{ $selectedRange == $key ? 'selected' : '' }}>
                        {{ $range['label'] }}
                    </option>
                @endforeach
            </select>
        </div>


        <div class="col-md-2 d-flex align-items-end">
            <button type="button" class="btn btn-primary w-100" id="resetFilter">
                Reset
            </button>
        </div>

    </form>
</div>


<script>
    document.addEventListener('DOMContentLoaded', function () {
        let filterTimeout;
        const filterForm = $('#filterForm');
        const ajaxUrl = filterForm.data('ajax-url');
        
        // Function to apply filters via AJAX
        function applyFilters() {
            clearTimeout(filterTimeout);
            filterTimeout = setTimeout(() => {
                const formData = filterForm.serialize();
                
                // Show loading indicator
                $('#purchase-table-container').html('<div class="text-center p-5"><i class="fas fa-spinner fa-spin fa-3x"></i><p class="mt-3">Loading...</p></div>');
                
                $.ajax({
                    url: ajaxUrl,
                    type: 'GET',
                    data: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#purchase-table-container').html(response.html);
                            
                            // Reinitialize DataTable
                            if ($.fn.DataTable.isDataTable('#purchaseInvoiceTable')) {
                                $('#purchaseInvoiceTable').DataTable().destroy();
                            }
                            $('#purchaseInvoiceTable').DataTable({
                                dom: 'Bfrtip',
                                buttons: [
                                    'copy', 'csv', 'excel', 'pdf', 'print', 'colvis'
                                ],
                                responsive: true
                            });
                            
                            // Don't update URL for AJAX filtering
                        }
                    },
                    error: function(xhr) {
                        console.error('Filter error:', xhr);
                        $('#purchase-table-container').html('<div class="alert alert-danger">Error loading data. Please try again.</div>');
                    }
                });
            }, 300); // 300ms debounce
        }

        // Date range picker
        if ($.fn.daterangepicker) {
            $('.date-range').daterangepicker({
                autoUpdateInput: false,
                locale: {
                    cancelLabel: 'Clear',
                    format: 'YYYY-MM-DD'
                }
            }).on('apply.daterangepicker', function (ev, picker) {
                $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                applyFilters();
            }).on('cancel.daterangepicker', function () {
                $(this).val('');
                applyFilters();
            });
        }

        // Apply filters on change
        $(".filter-item").on("change", function () {
            applyFilters();
        });
        
        // Apply filters on text input (with debounce)
        $(".filter-item[type='text']").on("input", function () {
            applyFilters();
        });
        
        // Reset button
        $('#resetFilter').on('click', function (e) {
            e.preventDefault();
            $('#filterForm')[0].reset();
            $('.date-range').val('');
            // Clear filters and reload with base URL via AJAX
            const formData = '';
            
            $('#purchase-table-container').html('<div class="text-center p-5"><i class="fas fa-spinner fa-spin fa-3x"></i><p class="mt-3">Loading...</p></div>');
            
            $.ajax({
                url: ajaxUrl,
                type: 'GET',
                data: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                success: function(response) {
                    if (response.success) {
                        $('#purchase-table-container').html(response.html);
                        
                        // Reinitialize DataTable
                        if ($.fn.DataTable.isDataTable('#purchaseInvoiceTable')) {
                            $('#purchaseInvoiceTable').DataTable().destroy();
                        }
                        $('#purchaseInvoiceTable').DataTable({
                            dom: 'Bfrtip',
                            buttons: [
                                'copy', 'csv', 'excel', 'pdf', 'print', 'colvis'
                            ],
                            responsive: true
                        });
                    }
                },
                error: function(xhr) {
                    console.error('Filter error:', xhr);
                    $('#purchase-table-container').html('<div class="alert alert-danger">Error loading data. Please try again.</div>');
                }
            });
        });
    });
</script>

