$(async function () {
    "use strict";
    /** #################### -- The base JS part should be on top of all JS files --  #################### **/
    // Language Translator
    let base_url = $('#base_url').val();
    let language_name = $('#language_name').val();
    let language_path = '/resources/lang/' + language_name + '.json';
    let language_file = base_url + language_path;
    let language_key = {};
  
    async function loadLanguage() {
      try {
        const res = await fetch(language_file);
        language_key = await res.json();
      } catch (err) {
        console.error('Failed to load language file:', err);
      }
    }
    await loadLanguage();
  
  
    // Company Info
    let company_data = $('#company_data').val();
    let company_session_data = {};
    try {
        company_session_data = JSON.parse(company_data);
    } catch (e) {
        console.error('Error parsing company info:', e);
    }
    /** #################### -- The base JS part should be on top of all JS files --  #################### **/
  
    let outletId = '';
    let supplierId = '';
    let dateFrom = '';
    let dateTo = '';
    let table;
    let summaryData = {};
    
    // Get route paths
    let purchaseReportRoute;
    try {
        purchaseReportRoute = route('report.purchase-report', {}, false, Ziggy);
    } catch (e) {
        // Fallback if route helper doesn't work
        purchaseReportRoute = '/reports/purchase-report';
    }
    
    // Store filter info for exports (use server format; date_from/date_to only when filtered)
    let currentFilterInfo = {
        outlet: null,
        supplier: null,
        date_from: null,
        date_to: null,
        generated_at: null,
        generated_by: null
    };
  
    // Function to update filtered information header (Report Heading, Generated On, Generated By always show after Apply Filter)
    function updateFilteredInformation(filterInfo) {
        if (!filterInfo) {
            $('#filteredInformation').hide();
            return;
        }
        let html = '<p class="pb-0 mb-0"><strong>' + (language_key.PurchaseReport || 'Purchase Report') + '</strong></p>';
        
        if (filterInfo.outlet) {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.OutletName || 'Outlet Name') + ': </strong> ' + (filterInfo.outlet.name || '-') + '</p>';
            if (filterInfo.outlet.phone) {
                html += '<p class="pb-0 mb-0"><strong>' + (language_key.OutletPhone || 'Outlet Phone') + ': </strong> ' + filterInfo.outlet.phone + '</p>';
            }
            if (filterInfo.outlet.address) {
                html += '<p class="pb-0 mb-0"><strong>' + (language_key.OutletAddress || 'Outlet Address') + ': </strong> ' + filterInfo.outlet.address + '</p>';
            }
        }
        
        if (filterInfo.supplier) {
            let supplierText = filterInfo.supplier.name || '-';
            if (filterInfo.supplier.phone) {
                supplierText += ' (' + filterInfo.supplier.phone + ')';
            }
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.Supplier || 'Supplier') + ': </strong> ' + supplierText + '</p>';
        }
        
        if (filterInfo.date_from || filterInfo.date_to) {
            let dateRange = (filterInfo.date_from || '') + ' to ' + (filterInfo.date_to || '');
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.DateRange || 'Date Range') + ': </strong> ' + dateRange + '</p>';
        }
        
        if (filterInfo.generated_at) {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.GeneratedOn || 'Generated on') + ': </strong> ' + filterInfo.generated_at + '</p>';
        }
        if (filterInfo.generated_by && (filterInfo.generated_by.name || filterInfo.generated_by.phone)) {
            let byText = [filterInfo.generated_by.name, filterInfo.generated_by.phone].filter(Boolean).join(', ');
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.GeneratedBy || 'Generated by') + ': </strong> ' + byText + '</p>';
        }
        
        $('#filterInfoContent').html(html);
        $('#filteredInformation').show();
    }
  
    // Function to get header HTML for exports
    function getExportHeader() {
        let header = '<div style="margin-bottom: 20px;">';
        header += '<h3 style="text-align: center; margin-bottom: 15px;">' + (language_key.PurchaseReport || 'Purchase Report') + '</h3>';
        
        if (currentFilterInfo.outlet) {
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.OutletName || 'Outlet Name') + ': </strong> ' + (currentFilterInfo.outlet.name || '-') + '</p>';
            if (currentFilterInfo.outlet.phone) {
                header += '<p style="margin: 5px 0;"><strong>' + (language_key.OutletPhone || 'Outlet Phone') + ': </strong> ' + currentFilterInfo.outlet.phone + '</p>';
            }
            if (currentFilterInfo.outlet.address) {
                header += '<p style="margin: 5px 0;"><strong>' + (language_key.OutletAddress || 'Outlet Address') + ': </strong> ' + currentFilterInfo.outlet.address + '</p>';
            }
        }
        
        if (currentFilterInfo.supplier) {
            let supplierText = currentFilterInfo.supplier.name || '-';
            if (currentFilterInfo.supplier.phone) {
                supplierText += ' (' + currentFilterInfo.supplier.phone + ')';
            }
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.Supplier || 'Supplier') + ': </strong> ' + supplierText + '</p>';
        }
        
        if (currentFilterInfo.date_from || currentFilterInfo.date_to) {
            let dateRange = (currentFilterInfo.date_from || '') + ' to ' + (currentFilterInfo.date_to || '');
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.DateRange || 'Date Range') + ': </strong> ' + dateRange + '</p>';
        }
        if (currentFilterInfo.generated_at) {
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.GeneratedOn || 'Generated on') + ': </strong> ' + currentFilterInfo.generated_at + '</p>';
        }
        if (currentFilterInfo.generated_by && (currentFilterInfo.generated_by.name || currentFilterInfo.generated_by.phone)) {
            let byText = [currentFilterInfo.generated_by.name, currentFilterInfo.generated_by.phone].filter(Boolean).join(', ');
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.GeneratedBy || 'Generated by') + ': </strong> ' + byText + '</p>';
        }
        
        header += '</div>';
        return header;
    }
  
    // Function to update footer totals from controller summary
    function updateFooterTotals(summary) {
        if (summary) {
            $('#totalGrandTotal').text(summary.total_grand_total || '0.00');
            $('#totalPaid').text(summary.total_paid || '0.00');
            $('#totalDue').text(summary.total_due || '0.00');
        }
    }
  
    // Configure pdfmake fonts if available, otherwise use defaults
    if (typeof pdfMake !== 'undefined') {
        try {
            // Try to set default fonts if vfs_fonts is not available
            if (typeof pdfMake.vfs === 'undefined' || Object.keys(pdfMake.vfs).length === 0) {
                // Use default fonts without custom font files
                pdfMake.fonts = {
                    Roboto: {
                        normal: 'Roboto-Regular.ttf',
                        bold: 'Roboto-Medium.ttf',
                        italics: 'Roboto-Italic.ttf',
                        bolditalics: 'Roboto-MediumItalic.ttf'
                    }
                };
            }
        } catch (e) {
            console.warn('PDF fonts configuration warning:', e);
        }
    }
  
    // Initialize DataTable (without loading data initially)
    function initTable() {
        if ($.fn.DataTable.isDataTable('#purchaseReportTable')) {
            $('#purchaseReportTable').DataTable().destroy();
        }
      
        table = $('#purchaseReportTable').DataTable({
            processing: true,
            serverSide: false,
            paging: false,
            searching: true,
            ordering: true,
            info: true,
            autoWidth: false,
            responsive: true,
            data: [], // Start with empty data
            columns: [
                { data: 'sn' },
                { data: 'reference_no' },
                { data: 'date_time' },
                { data: 'purchase_date' },
                { data: 'supplier' },
                { data: 'items' },
                { data: 'grand_total' },
                { data: 'paid' },
                { data: 'due' },
                { data: 'purchase_by' }
            ],
            order: [[3, 'desc']], // Order by purchase date descending
            dom: '<"card-header border-bottom p-3"<"head-label"><"dt-action-buttons text-end"B>>' +
                '<"row"<"col-sm-12"tr>>',
            buttons: [
                {
                    extend: 'collection',
                    className: 'btn btn-primary dropdown-toggle me-2',
                    text: '<i class="ti tabler-file-export me-sm-1"></i> <span class="d-none d-sm-inline-block">'+language_key['Export']+'</span>',
                    buttons: [
                        {
                            extend: 'print',
                            text: '<i class="ti tabler-printer me-1"></i>' + (language_key.Print || 'Print'),
                            className: 'dropdown-item',
                            title: '',
                            customize: function (win) {
                                $(win.document.body).prepend(getExportHeader());
                            }
                        },
                        {
                            extend: 'excelHtml5',
                            text: '<i class="ti tabler-file-spreadsheet me-1"></i>' + (language_key.Excel || 'Excel'),
                            className: 'dropdown-item',
                            title: '',
                            customize: function (xlsx) {
                                var sheet = xlsx.xl.worksheets['sheet1.xml'];
                                $('row c[r^="A"]', sheet).attr('s', '2');
                            },
                            messageTop: function() {
                                let header = (language_key.PurchaseReport || 'Purchase Report') + '\n\n';
                                if (currentFilterInfo.outlet) {
                                    header += (language_key.OutletName || 'Outlet Name') + ': ' + (currentFilterInfo.outlet.name || '-') + '\n';
                                    if (currentFilterInfo.outlet.phone) {
                                        header += (language_key.OutletPhone || 'Outlet Phone') + ': ' + currentFilterInfo.outlet.phone + '\n';
                                    }
                                    if (currentFilterInfo.outlet.address) {
                                        header += (language_key.OutletAddress || 'Outlet Address') + ': ' + currentFilterInfo.outlet.address + '\n';
                                    }
                                }
                                if (currentFilterInfo.supplier) {
                                    let supplierText = currentFilterInfo.supplier.name || '-';
                                    if (currentFilterInfo.supplier.phone) {
                                        supplierText += ' (' + currentFilterInfo.supplier.phone + ')';
                                    }
                                    header += (language_key.Supplier || 'Supplier') + ': ' + supplierText + '\n';
                                }
                                if (currentFilterInfo.date_from || currentFilterInfo.date_to) {
                                    let dateRange = (currentFilterInfo.date_from || '') + ' to ' + (currentFilterInfo.date_to || '');
                                    header += (language_key.DateRange || 'Date Range') + ': ' + dateRange + '\n';
                                }
                                if (currentFilterInfo.generated_at) {
                                    header += (language_key.GeneratedOn || 'Generated on') + ': ' + currentFilterInfo.generated_at + '\n';
                                }
                                if (currentFilterInfo.generated_by && (currentFilterInfo.generated_by.name || currentFilterInfo.generated_by.phone)) {
                                    let byText = [currentFilterInfo.generated_by.name, currentFilterInfo.generated_by.phone].filter(Boolean).join(', ');
                                    header += (language_key.GeneratedBy || 'Generated by') + ': ' + byText + '\n';
                                }
                                return header;
                            }
                        },
                        {
                            extend: 'pdf',
                            text: '<i class="ti tabler-file-description me-1"></i>' + (language_key.Pdf || 'PDF'),
                            className: 'dropdown-item',
                            title: '',
                            orientation: 'portrait', //landscape
                            pageSize: 'A4',
                            messageTop: function() {
                                let header = (language_key.PurchaseReport || 'Purchase Report') + '\n\n';
                                if (currentFilterInfo.outlet) {
                                    header += (language_key.OutletName || 'Outlet Name') + ': ' + (currentFilterInfo.outlet.name || '-') + '\n';
                                    if (currentFilterInfo.outlet.phone) {
                                        header += (language_key.OutletPhone || 'Outlet Phone') + ': ' + currentFilterInfo.outlet.phone + '\n';
                                    }
                                    if (currentFilterInfo.outlet.address) {
                                        header += (language_key.OutletAddress || 'Outlet Address') + ': ' + currentFilterInfo.outlet.address + '\n';
                                    }
                                }
                                if (currentFilterInfo.supplier) {
                                    let supplierText = currentFilterInfo.supplier.name || '-';
                                    if (currentFilterInfo.supplier.phone) {
                                        supplierText += ' (' + currentFilterInfo.supplier.phone + ')';
                                    }
                                    header += (language_key.Supplier || 'Supplier') + ': ' + supplierText + '\n';
                                }
                                if (currentFilterInfo.date_from || currentFilterInfo.date_to) {
                                    let dateRange = (currentFilterInfo.date_from || '') + ' to ' + (currentFilterInfo.date_to || '');
                                    header += (language_key.DateRange || 'Date Range') + ': ' + dateRange + '\n';
                                }
                                if (currentFilterInfo.generated_at) {
                                    header += (language_key.GeneratedOn || 'Generated on') + ': ' + currentFilterInfo.generated_at + '\n';
                                }
                                if (currentFilterInfo.generated_by && (currentFilterInfo.generated_by.name || currentFilterInfo.generated_by.phone)) {
                                    let byText = [currentFilterInfo.generated_by.name, currentFilterInfo.generated_by.phone].filter(Boolean).join(', ');
                                    header += (language_key.GeneratedBy || 'Generated by') + ': ' + byText + '\n';
                                }
                                return header;
                            }
                        }
                    ]
                },
                {
                    text: '<i class="ti tabler-filter me-sm-1"></i> <span class="d-none d-sm-inline-block">'+language_key['Filter']+'</span>',
                    className: 'btn create-new btn-primary',
                    action: function (e, dt, node, config) {
                        $('#filterSection').slideToggle();
                        let isVisible = $('#filterSection').is(':visible');
                    }
                }
            ],
          
            drawCallback: function(settings) {
                // Use summary from controller instead of calculating
                if (summaryData) {
                    updateFooterTotals(summaryData);
                }
            }
        });
    }
  
    // Initialize Select2 for filter dropdowns
    function initSelect2() {
        // Initialize Outlet Select2
        if ($('#outlet_id').length && !$('#outlet_id').hasClass('select2-hidden-accessible')) {
            $('#outlet_id').select2({
                dropdownParent: $('#filterSection'),
                width: '100%',
                placeholder: language_key.AllOutlets || 'All Outlets',
                allowClear: true
            });
        }
        
        // Initialize Supplier Select2
        if ($('#supplier_id').length && !$('#supplier_id').hasClass('select2-hidden-accessible')) {
            $('#supplier_id').select2({
                dropdownParent: $('#filterSection'),
                width: '100%',
                placeholder: language_key.AllSuppliers || 'All Suppliers',
                allowClear: true
            });
        }
    }
  
    // Load report data
    function loadReportData() {
        $.ajax({
            url: base_url + purchaseReportRoute,
            type: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            data: {
                outlet_id: outletId,
                supplier_id: supplierId,
                date_from: dateFrom,
                date_to: dateTo
            },
            success: function(response) {
                if (response.success && response.data && response.data.purchases) {
                    // Store summary data from controller
                    summaryData = response.data.summary || {};
                    
                    // Update filter info for exports (use server format; date_from/date_to only when filtered)
                    if (response.data.filter_info) {
                        currentFilterInfo = response.data.filter_info;
                        updateFilteredInformation(currentFilterInfo);
                    } else {
                        currentFilterInfo = {
                            outlet: null,
                            supplier: null,
                            date_from: null,
                            date_to: null,
                            generated_at: null,
                            generated_by: null
                        };
                        updateFilteredInformation(currentFilterInfo);
                    }
                    
                    table.clear();
                    table.rows.add(response.data.purchases);
                    table.draw();
                    
                    // Update footer totals from controller summary
                    updateFooterTotals(summaryData);
                } else {
                    table.clear().draw();
                    $('#filteredInformation').hide();
                    updateFooterTotals({
                        total_paid: '0.00',
                        total_due: '0.00'
                    });
                }
            }
        });
    }
  
    // Prevent form submission - attach early
    $(document).on('submit', '#filterForm', function(e) {
        e.preventDefault();
        e.stopPropagation();
        return false;
    });
    
    // Prevent Enter key from submitting form
    $(document).on('keydown', '#filterForm input, #filterForm select', function(e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            e.preventDefault();
            e.stopPropagation();
            $('#applyFilter').click();
            return false;
        }
    });
  
    // Apply filter
    $(document).on('click', '#applyFilter', function(e) {
        e.preventDefault();
        e.stopPropagation();
        outletId = $('#outlet_id').val();
        supplierId = $('#supplier_id').val();
        dateFrom = $('#date_from').val();
        dateTo = $('#date_to').val();
        loadReportData();
        return false;
    });
  
    
    
    // Show filter section if filters are applied (on page load)
    function checkAndShowFilters() {
        let dateFromVal = $('#date_from').val();
        let dateToVal = $('#date_to').val();
        let outletIdVal = $('#outlet_id').val();
        let supplierIdVal = $('#supplier_id').val();
        
        if (dateFromVal || dateToVal || outletIdVal || supplierIdVal) {
            // Set global variables before loading data
            outletId = outletIdVal || '';
            supplierId = supplierIdVal || '';
            dateFrom = dateFromVal || '';
            dateTo = dateToVal || '';
            
            $('#filterSection').show();
            initSelect2();
            // Load data if filters are present
            loadReportData();
        }
    }
    
    // Reinitialize Select2 when filter section is toggled
    $('#filterSection').on('shown.bs.collapse shown', function () {
        initSelect2();
    });
    
    // Initialize everything
    initTable();
    initSelect2();
    checkAndShowFilters();
});
