$(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 type = 'All';
    let table;
    let summaryData = {};
    
    // Get route paths
    let supplierBalanceReportRoute;
    try {
        supplierBalanceReportRoute = route('report.supplier-balance-report', {}, false, Ziggy);
    } catch (e) {
        // Fallback if route helper doesn't work
        supplierBalanceReportRoute = '/reports/supplier-balance-report';
    }
    
    // Store filter info for exports
    let currentFilterInfo = {
        type: 'All',
        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.SupplierBalanceReport || 'Supplier Balance Report') + '</strong></p>';
        
        if (filterInfo.type && filterInfo.type !== 'All') {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.Type || 'Type') + ': </strong> ' + filterInfo.type + '</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.SupplierBalanceReport || 'Supplier Balance Report') + '</h3>';
        
        if (currentFilterInfo.type && currentFilterInfo.type !== 'All') {
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.Type || 'Type') + ': </strong> ' + currentFilterInfo.type + '</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) {
            $('#totalBalance').text(summary.total_balance || '0.00');
            $('#totalSuppliers').text(summary.total_suppliers || '0');
        }
    }
  
    // 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('#supplierBalanceReportTable')) {
            $('#supplierBalanceReportTable').DataTable().destroy();
        }
      
        table = $('#supplierBalanceReportTable').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: 'supplier_name' },
                { data: 'current_balance' }
            ],
            order: [[2, 'desc']], // Order by balance 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.SupplierBalanceReport || 'Supplier Balance Report') + '\n\n';
                                if (currentFilterInfo.type && currentFilterInfo.type !== 'All') {
                                    header += (language_key.Type || 'Type') + ': ' + currentFilterInfo.type + '\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.SupplierBalanceReport || 'Supplier Balance Report') + '\n\n';
                                if (currentFilterInfo.type && currentFilterInfo.type !== 'All') {
                                    header += (language_key.Type || 'Type') + ': ' + currentFilterInfo.type + '\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 Type Select2
        if ($('#type').length && !$('#type').hasClass('select2-hidden-accessible')) {
            $('#type').select2({
                dropdownParent: $('#filterSection'),
                width: '100%',
                placeholder: language_key.Type || 'Type',
                allowClear: false
            });
        }
    }
  
    // Load report data
    function loadReportData() {
        $.ajax({
            url: base_url + supplierBalanceReportRoute,
            type: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            data: {
                type: type
            },
            success: function(response) {
                if (response.success && response.data && response.data.suppliers) {
                    // Store summary data from controller
                    summaryData = response.data.summary || {};
                    
                    // Update filter info for exports
                    if (response.data.filter_info) {
                        currentFilterInfo = response.data.filter_info;
                        currentFilterInfo.type = type || currentFilterInfo.type || 'All';
                        updateFilteredInformation(currentFilterInfo);
                    } else {
                        currentFilterInfo = {
                            type: type,
                            generated_at: null,
                            generated_by: null
                        };
                        updateFilteredInformation(currentFilterInfo);
                    }
                    
                    table.clear();
                    table.rows.add(response.data.suppliers);
                    table.draw();
                    
                    // Update footer totals from controller summary
                    updateFooterTotals(summaryData);
                } else {
                    table.clear().draw();
                    $('#filteredInformation').hide();
                    updateFooterTotals({
                        total_balance: '0.00',
                        total_suppliers: '0'
                    });
                }
            },
            error: function(xhr) {
                let errorMessage = language_key.ErrorLoadingData || 'Error loading data';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }
                Swal.fire({
                    icon: 'error',
                    title: language_key.Error || 'Error',
                    text: errorMessage,
                    confirmButtonText: language_key.OK || 'OK'
                });
            }
        });
    }
  
    // 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();
        type = $('#type').val() || 'All';
        loadReportData();
        return false;
    });
  
    
    
    // Show filter section if filters are applied (on page load)
    function checkAndShowFilters() {
        let typeVal = $('#type').val() || 'All';
        
        // Set global variables before loading data
        type = typeVal;
        
        if (typeVal && typeVal !== 'All') {
            $('#filterSection').show();
        }
        
        initSelect2();
        // Always load data initially
        loadReportData();
    }
    
    // Reinitialize Select2 when filter section is toggled
    $('#filterSection').on('shown.bs.collapse shown', function () {
        initSelect2();
    });
    
    // Initialize everything
    initTable();
    initSelect2();
    checkAndShowFilters();
});
