$(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 date = '';
    let table;
    let summaryData = {};
    
    // Get route paths
    let dailySummaryReportRoute;
    try {
        dailySummaryReportRoute = route('report.daily-summary-report', {}, false, Ziggy);
    } catch (e) {
        // Fallback if route helper doesn't work
        dailySummaryReportRoute = '/reports/daily-summary-report';
    }
    
    // Store filter info for exports
    let currentFilterInfo = {
        outlet: null,
        date: ''
    };
  
    // Function to update filtered information header
    function updateFilteredInformation(filterInfo) {
        let html = '';
        
        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.date) {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.Date || 'Date') + ': </strong> ' + filterInfo.date + '</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>';
        }
        
        if (html) {
            $('#filterInfoContent').html(html);
            $('#filteredInformation').show();
        } else {
            $('#filteredInformation').hide();
        }
    }
  
    // 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.DailySummaryReport || 'Daily Summary 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.date) {
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.Date || 'Date') + ': </strong> ' + currentFilterInfo.date + '</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) {
            $('#totalAmount').text(summary.total_amount || '0.00');
            $('#totalTransactions').text(summary.total_transactions || '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);
        }
    }
  
    // Function to format row data based on transaction type
    function formatRowData(row) {
        if (row.is_section_header) {
            // Section header row - show section name and column headers
            return {
                sn: '<strong>' + row.section_name + ':</strong>',
                reference_no: row.col2 || '',
                supplier_customer_category: row.col3 || '',
                amount_subtotal: row.col4 || '',
                tax_paid_responsible: row.col5 || '',
                charge_due_payment: row.col6 || '',
                discount_items: row.col7 || '',
                total_payable: row.col8 || '',
                paid: row.col9 || '',
                due: row.col10 || '',
                is_header: true
            };
        }
        
        // Data row - format based on transaction type
        let formattedRow = {
            sn: row.sn || '',
            reference_no: '',
            supplier_customer_category: '',
            amount_subtotal: '',
            tax_paid_responsible: '',
            charge_due_payment: '',
            discount_items: '',
            total_payable: '',
            paid: '',
            due: ''
        };
        
        switch(row.transaction_type) {
            case 'Purchase':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.supplier || '-';
                formattedRow.amount_subtotal = row.grand_total || '-';
                formattedRow.tax_paid_responsible = row.paid || '-';
                formattedRow.charge_due_payment = row.due || '-';
                break;
            case 'Purchase Return':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.supplier || '-';
                formattedRow.amount_subtotal = row.amount || '-';
                break;
            case 'Supplier Due Payment':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.supplier || '-';
                formattedRow.amount_subtotal = row.amount || '-';
                break;
            case 'Sale':
                formattedRow.reference_no = row.invoice_no || '-';
                formattedRow.supplier_customer_category = row.customer || '-';
                formattedRow.amount_subtotal = row.sub_total || '-';
                formattedRow.tax_paid_responsible = row.tax || '-';
                formattedRow.charge_due_payment = row.charge || '-';
                formattedRow.discount_items = row.discount || '-';
                formattedRow.total_payable = row.total_payable || '-';
                formattedRow.paid = row.paid || '-';
                formattedRow.due = row.due || '-';
                break;
            case 'Sale Return':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.customer || '-';
                formattedRow.amount_subtotal = row.return_amount || '-';
                formattedRow.tax_paid_responsible = row.paid || '-';
                formattedRow.charge_due_payment = row.due || '-';
                break;
            case 'Customer Due Receive':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.customer || '-';
                formattedRow.amount_subtotal = row.amount || '-';
                break;
            case 'Expense':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.expense_category || '-';
                formattedRow.amount_subtotal = row.responsible_person || '-'; // Responsible Person in Amount/Sub Total column
                formattedRow.tax_paid_responsible = row.amount || '-'; // Amount in Tax/Paid/Responsible Person column
                formattedRow.charge_due_payment = row.payment_method || '-'; // Payment Method in Charge/Due/Payment Method column
                break;
            case 'Income':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.income_category || '-';
                formattedRow.amount_subtotal = row.responsible_person || '-'; // Responsible Person in Amount/Sub Total column
                formattedRow.tax_paid_responsible = row.amount || '-'; // Amount in Tax/Paid/Responsible Person column
                formattedRow.charge_due_payment = row.payment_method || '-'; // Payment Method in Charge/Due/Payment Method column
                break;
            case 'Damage':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.damage_amount || '-'; // Damage Amount in Supplier/Customer/Category column
                formattedRow.amount_subtotal = row.responsible_person || '-'; // Responsible Person in Amount/Sub Total column
                formattedRow.tax_paid_responsible = row.items || '-'; // Items in Tax/Paid/Responsible Person column
                break;
            case 'Installment Collection':
                formattedRow.reference_no = row.invoice_no || '-';
                formattedRow.supplier_customer_category = row.customer || '-';
                formattedRow.amount_subtotal = row.amount || '-';
                break;
            case 'Installment Down Payment':
                formattedRow.reference_no = row.reference_no || '-';
                formattedRow.supplier_customer_category = row.customer || '-';
                formattedRow.amount_subtotal = row.amount || '-';
                break;
            case 'Servicing':
                formattedRow.reference_no = row.customer || '-';
                formattedRow.supplier_customer_category = row.servicing_charge || '-';
                formattedRow.amount_subtotal = row.paid_amount || '-';
                formattedRow.tax_paid_responsible = row.due_amount || '-';
                break;
        }
        
        return formattedRow;
    }
  
    // Initialize DataTable (without loading data initially)
    function initTable() {
        if ($.fn.DataTable.isDataTable('#dailySummaryReportTable')) {
            $('#dailySummaryReportTable').DataTable().destroy();
        }
      
        table = $('#dailySummaryReportTable').DataTable({
            processing: true,
            serverSide: false,
            paging: false,
            searching: true,
            ordering: false, // Disable sorting for section headers
            info: true,
            autoWidth: false,
            responsive: true,
            data: [], // Start with empty data
            columns: [
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.sn;
                        }
                        return row.sn || '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.reference_no;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.supplier_customer_category;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.amount_subtotal;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.tax_paid_responsible;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.charge_due_payment;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.discount_items;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.total_payable;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.paid;
                        }
                        return '';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (type === 'display') {
                            let formatted = formatRowData(row);
                            return formatted.due;
                        }
                        return '';
                    }
                }
            ],
            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.DailySummaryReport || 'Daily Summary 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.date) {
                                    header += (language_key.Date || 'Date') + ': ' + currentFilterInfo.date + '\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.DailySummaryReport || 'Daily Summary 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.date) {
                                    header += (language_key.Date || 'Date') + ': ' + currentFilterInfo.date + '\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');
                    }
                }
            ],
          
            createdRow: function(row, data, dataIndex) {
                // Add styling for section headers
                if (data.is_section_header) {
                    $(row).addClass('section-header-row');
                    $(row).css({
                        'background-color': '#f0f0f0',
                        'font-weight': 'bold'
                    });
                    // Make all cells in header row bold
                    $(row).find('td').css('font-weight', 'bold');
                }
            },
          
            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.SelectOutlet || 'Select Outlet',
                allowClear: false
            });
        }
    }
  
    // Load report data
    function loadReportData() {
        // Validate required fields
        if (!date || !outletId) {
            Swal.fire({
                icon: 'warning',
                title: language_key.Warning || 'Warning',
                text: language_key.DateAndOutletRequired || 'Date and Outlet are required',
                confirmButtonText: language_key.OK || 'OK'
            });
            return;
        }
        
        $.ajax({
            url: base_url + dailySummaryReportRoute,
            type: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            data: {
                date: date,
                outlet_id: outletId
            },
            success: function(response) {
                if (response.success && response.data && response.data.transactions) {
                    // Store summary data from controller
                    summaryData = response.data.summary || {};
                    
                    // Update filter info for exports (use server-formatted date e.g. Y/m/d from company setting)
                    if (response.data.filter_info) {
                        currentFilterInfo = response.data.filter_info;
                        updateFilteredInformation(currentFilterInfo);
                    } else {
                        // If no filter_info in response, create it from current values
                        currentFilterInfo = {
                            outlet: null,
                            date: date
                        };
                        updateFilteredInformation(currentFilterInfo);
                    }
                    
                    table.clear();
                    table.rows.add(response.data.transactions);
                    table.draw();
                    
                    // Update footer totals from controller summary
                    updateFooterTotals(summaryData);
                } else {
                    table.clear().draw();
                    $('#filteredInformation').hide();
                    updateFooterTotals({
                        total_amount: '0.00',
                        total_transactions: '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();
        date = $('#date').val();
        outletId = $('#outlet_id').val();
        
        if (!date || !outletId) {
            Swal.fire({
                icon: 'warning',
                title: language_key.Warning || 'Warning',
                text: language_key.DateAndOutletRequired || 'Date and Outlet are required',
                confirmButtonText: language_key.OK || 'OK'
            });
            return false;
        }
        
        loadReportData();
        return false;
    });
  
    
    
    // Show filter section if filters are applied (on page load)
    function checkAndShowFilters() {
        let dateVal = $('#date').val();
        let outletIdVal = $('#outlet_id').val();
        
        if (dateVal && outletIdVal) {
            // Set global variables before loading data
            date = dateVal;
            outletId = outletIdVal;
            
            $('#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();
});
