<!-- Export -->
      <script type="text/javascript" src="<?php echo $theme_link; ?>plugins/tableExporter/libs/js-xlsx/xlsx.core.min.js"></script>
      <script type="text/javascript" src="<?php echo $theme_link; ?>plugins/tableExporter/libs/jsPDF/jspdf.min.js"></script>
      <script type="text/javascript" src="<?php echo $theme_link; ?>plugins/tableExporter/libs/jsPDF-AutoTable/jspdf.plugin.autotable.js"></script>
      <script type="text/javascript" src="<?php echo $theme_link; ?>plugins/tableExporter/tableExport.min.js"></script>
<script>
      function downloadPdf(tableId){
            $('#'+tableId).tableExport({
                  type: 'pdf',
                  escape: 'false',
                  jspdf: {
                        autotable: {
                              styles: {
                                    textColor: 0,
                                    fontSize: 10,
                                    rowHeight: 14,
                                    cellPadding: 4,
                                    fontStyle: 'normal'
                              },
                              headerStyles: {
                                    textColor: 0,
                                    fillColor: [220, 220, 220],
                                    fontStyle: 'bold',
                                    fontSize: 10
                              },
                              alternateRowStyles: {
                                    fillColor: 248,
                                    textColor: 0
                              }
                        }
                  }
            });
      }
      function downloadExcel(tableId){
            // Generate filename with current date and time
            var now = new Date();
            var dateStr = now.getFullYear() + '-' + 
                         String(now.getMonth() + 1).padStart(2, '0') + '-' + 
                         String(now.getDate()).padStart(2, '0');
            var timeStr = String(now.getHours()).padStart(2, '0') + '-' + 
                         String(now.getMinutes()).padStart(2, '0');
            
            // Get filter information for filename
            var storeName = $('#store_id option:selected').text() || 'AllStores';
            var warehouseName = $('#warehouse_id option:selected').text() || 'AllWarehouses';
            var brandName = $('#brand_id option:selected').text() || 'AllBrands';
            var categoryName = $('#category_id option:selected').text() || 'AllCategories';
            
            // Clean names for filename
            storeName = storeName.replace(/[^a-zA-Z0-9]/g, '');
            warehouseName = warehouseName.replace(/[^a-zA-Z0-9]/g, '');
            brandName = brandName.replace(/[^a-zA-Z0-9]/g, '');
            categoryName = categoryName.replace(/[^a-zA-Z0-9]/g, '');
            
            // Determine report type based on table ID and current page
            var reportType = '';
            var currentUrl = window.location.href;
            var isStockReportPage = currentUrl.indexOf('reports/stock') !== -1 || currentUrl.indexOf('reports/stock/') !== -1;
            
            // Only use stock-specific report types if we're on the stock report page
            if(isStockReportPage) {
                switch(tableId) {
                    case 'report-data':
                        reportType = 'ItemWiseStock';
                        break;
                    case 'brand_wise_stock':
                        reportType = 'BrandWiseStock';
                        break;
                    case 'stock_aging':
                        reportType = 'StockAging';
                        break;
                    case 'most_moving':
                        reportType = 'MostMovingStock';
                        break;
                    case 'less_moving':
                        reportType = 'LessMovingStock';
                        break;
                    default:
                        reportType = 'StockReport';
                }
            } else {
                // Comprehensive report type detection based on URL
                // Check more specific URLs first to avoid conflicts
                if(currentUrl.indexOf('reports/supplier_items') !== -1) {
                    reportType = 'SupplierItemsReport';
                } else if(currentUrl.indexOf('reports/payment_method_breakdown') !== -1) {
                    reportType = 'PaymentMethodBreakdownReport';
                } else if(currentUrl.indexOf('reports/sales_return_payments') !== -1) {
                    reportType = 'SalesReturnPaymentsReport';
                } else if(currentUrl.indexOf('reports/sales_payments') !== -1) {
                    reportType = 'SalesPaymentsReport';
                } else if(currentUrl.indexOf('reports/purchase_payments') !== -1) {
                    reportType = 'PurchasePaymentsReport';
                } else if(currentUrl.indexOf('reports/purchase_return') !== -1) {
                    reportType = 'PurchaseReturnReport';
                } else if(currentUrl.indexOf('reports/sales_return') !== -1) {
                    reportType = 'SalesReturnReport';
                } else if(currentUrl.indexOf('reports/sales_tax') !== -1) {
                    reportType = 'SalesTaxReport';
                } else if(currentUrl.indexOf('reports/purchase_tax') !== -1) {
                    reportType = 'PurchaseTaxReport';
                } else if(currentUrl.indexOf('reports/sales_gst_report') !== -1) {
                    reportType = 'SalesGSTReport';
                } else if(currentUrl.indexOf('reports/purchase_gst_report') !== -1) {
                    reportType = 'PurchaseGSTReport';
                } else if(currentUrl.indexOf('reports/gstr_1') !== -1) {
                    reportType = 'GSTR1Report';
                } else if(currentUrl.indexOf('reports/gstr_2') !== -1) {
                    reportType = 'GSTR2Report';
                } else if(currentUrl.indexOf('reports/item_sales') !== -1) {
                    reportType = 'ItemSalesReport';
                } else if(currentUrl.indexOf('reports/return_item') !== -1) {
                    reportType = 'ReturnItemReport';
                } else if(currentUrl.indexOf('reports/expired_items') !== -1) {
                    reportType = 'ExpiredItemsReport';
                } else if(currentUrl.indexOf('reports/seller_points') !== -1) {
                    reportType = 'SellerPointsReport';
                } else if(currentUrl.indexOf('reports/customer_orders') !== -1) {
                    reportType = 'CustomerOrdersReport';
                } else if(currentUrl.indexOf('reports/delivery_sheet') !== -1) {
                    reportType = 'DeliverySheetReport';
                } else if(currentUrl.indexOf('reports/load_sheet') !== -1) {
                    reportType = 'LoadSheetReport';
                } else if(currentUrl.indexOf('reports/sales_and_payments') !== -1) {
                    reportType = 'SalesAndPaymentsReport';
                } else if(currentUrl.indexOf('reports/stock_transfer') !== -1) {
                    reportType = 'StockTransferReport';
                } else if(currentUrl.indexOf('reports/sales_summary') !== -1) {
                    reportType = 'SalesSummaryReport';
                } else if(currentUrl.indexOf('reports/gross_profit_per_sale') !== -1) {
                    reportType = 'GrossProfitPerSaleReport';
                } else if(currentUrl.indexOf('reports/customer_statement') !== -1) {
                    reportType = 'CustomerStatementReport';
                } else if(currentUrl.indexOf('reports/supplier_statement') !== -1) {
                    reportType = 'SupplierStatementReport';
                } else if(currentUrl.indexOf('reports/cash_flow_statement') !== -1) {
                    reportType = 'CashFlowStatement';
                } else if(currentUrl.indexOf('reports/profit_loss_statement') !== -1) {
                    reportType = 'ProfitLossStatement';
                } else if(currentUrl.indexOf('reports/expiry_report') !== -1) {
                    reportType = 'ExpiryReport';
                } else if(currentUrl.indexOf('reports/daily_reconciliation') !== -1) {
                    reportType = 'DailyReconciliationReport';
                } else if(currentUrl.indexOf('reports/expense') !== -1) {
                    reportType = 'ExpenseReport';
                } else if(currentUrl.indexOf('reports/sales') !== -1) {
                    reportType = 'SalesReport';
                } else if(currentUrl.indexOf('reports/purchase') !== -1) {
                    reportType = 'PurchaseReport';
                } else {
                    // Generic report name if URL doesn't match any known pattern
                    reportType = 'Report';
                }
            }
            
            var filename = reportType + '_' + storeName + '_' + warehouseName + '_' + 
                          brandName + '_' + categoryName + '_' + dateStr + '_' + timeStr;
            
            // Use the filename in the export
            // 🔥 Ensure table is fully rendered before export
setTimeout(function(){

    var table = $('#'+tableId);

    // 🔍 Debug: check if TOTAL row exists
    if(table.find('tr:contains("TOTAL")').length === 0){
        console.warn('⚠ TOTAL row not found in table before export');
    }

    // ✅ Clone table to avoid UI issues
    var clonedTable = table.clone();

    // ✅ Export cloned table (safer)
    clonedTable.tableExport({
        type:'xlsx',
        escape:'false',
        fileName: filename
    });

}, 300); // wait 300ms to ensure DOM is updated
      }
      $(".downloadPdf").on("click",function(){
            var tableId=$(this).attr("data-table-id");
            downloadPdf(tableId);
      });
      $(".downloadExcel").on("click",function(){
            var tableId=$(this).attr("data-table-id");
            // Use dedicated Excel export ONLY for stock report page
            // Check if we're on the stock report page by checking the current URL
            var currentUrl = window.location.href;
            var isStockReportPage = currentUrl.indexOf('reports/stock') !== -1 || currentUrl.indexOf('reports/stock/') !== -1;
            
            if(tableId === 'report-data' && isStockReportPage){
                exportStockReportToExcel();
            } else {
                downloadExcel(tableId);
            }
      });
      
      // Dedicated Excel export function for stock report
      function exportStockReportToExcel(){
            var store_id = $('#store_id').val() || '';
            var warehouse_id = $('#warehouse_id').val() || '';
            var brand_id = $('#brand_id').val() || '';
            var category_id = $('#category_id').val() || '';
            var from_date = $('#from_date').val() || '';
            var to_date = $('#to_date').val() || '';
            
            var url = base_url + 'reports/export_stock_excel?';
            if(store_id) url += 'store_id=' + store_id + '&';
            if(warehouse_id) url += 'warehouse_id=' + warehouse_id + '&';
            if(brand_id) url += 'brand_id=' + brand_id + '&';
            if(category_id) url += 'category_id=' + category_id + '&';
            if(from_date) url += 'from_date=' + from_date + '&';
            if(to_date) url += 'to_date=' + to_date + '&';
            
            // Remove trailing &
            url = url.replace(/&$/, '');
            
            window.open(url, '_blank');
      }
</script>