<?php
// Get store information for print functions - no hardcoded values
$store = get_store_details();
$store_name = get_store_name();

// Ensure we have a proper store name
if (empty($store_name) || $store_name === true || $store_name === 1) {
    $store_name = isset($store->store_name) ? $store->store_name : '';
}

$store_address = isset($store->address) ? $store->address : '';
$store_phone = isset($store->mobile) ? $store->mobile : '';
$store_email = isset($store->email) ? $store->email : '';
?>
<!DOCTYPE html>
<html>
   <head>
      <!-- TABLES CSS CODE -->
      <?php include"comman/code_css.php"; ?>
      <style>
        @media print {
            .no-print { display: none !important; }
            body { 
                font-size: 11px; 
                margin: 0; 
                padding: 0; 
                background: white !important;
                color: #000 !important;
            }
            .report-container { 
                margin: 0; 
                padding: 15px; 
                box-shadow: none;
                border: none;
                max-width: 100%;
            }
            .company-header {
                text-align: center;
                margin-bottom: 20px;
                page-break-after: avoid;
            }
            .company-header h2 {
                margin: 0 0 10px 0;
                font-size: 18px;
                font-weight: bold;
            }
            .pl-section {
                page-break-inside: avoid;
                margin-bottom: 15px;
            }
            .pl-section-header {
                background: #3c8dbc !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .pl-total {
                background: #e8f4f8 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .pl-subtotal {
                background: #f5f5f5 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .summary-box {
                page-break-inside: avoid;
                border: 2px solid #3c8dbc !important;
            }
            .pl-profit {
                color: #000 !important;
            }
            .pl-loss {
                color: #000 !important;
            }
        }
        @page {
            margin: 1cm;
            size: A4;
        }
        .pl-section {
            margin-bottom: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
        }
        .pl-section-header {
            background: #3c8dbc;
            color: white;
            padding: 10px 15px;
            font-weight: bold;
            font-size: 16px;
        }
        .pl-row {
            display: flex;
            border-bottom: 1px solid #eee;
            padding: 8px 15px;
        }
        .pl-row:last-child {
            border-bottom: none;
        }
        .pl-label {
            flex: 1;
            font-weight: 500;
        }
        .pl-value {
            flex: 1;
            text-align: right;
            font-weight: 500;
        }
        .pl-subtotal {
            background: #f5f5f5;
            font-weight: bold;
        }
        .pl-total {
            background: #e8f4f8;
            font-weight: bold;
            font-size: 16px;
            border-top: 2px solid #3c8dbc;
        }
        .pl-profit {
            color: #28a745;
        }
        .pl-loss {
            color: #dc3545;
        }
        .summary-box {
            background: #f9f9f9;
            border: 2px solid #3c8dbc;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        .company-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #3c8dbc;
        }
        .company-header h2 {
            margin: 0 0 10px 0;
            color: #3c8dbc;
            font-size: 24px;
            font-weight: bold;
        }
        .company-header p {
            margin: 5px 0;
            color: #666;
            font-size: 14px;
        }
        .report-actions {
            margin-top: 20px;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 4px;
            text-align: center;
        }
        .report-actions .btn {
            margin: 0 5px;
        }
      </style>  
   </head>
   <body class="hold-transition skin-blue sidebar-mini">
      <div class="wrapper">
         <?php include"sidebar.php"; ?>
         <!-- Content Wrapper. Contains page content -->
         <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
               <h1>
                  <?=$page_title;?>
                  <small></small>
               </h1>
               <ol class="breadcrumb">
                  <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
                  <li class="active"><?=$page_title;?></li>
               </ol>
            </section>
            <!-- Main content -->
            <section class="content">
               <div class="row">
                  <!-- right column -->
                  <div class="col-md-12">
                     <!-- Horizontal Form -->
                     <div class="box box-primary">
                        <div class="box-header with-border">
                           <h3 class="box-title">Please Enter Valid Information</h3>
                        </div>
                        <!-- /.box-header -->
                        <!-- form start -->
                        <form class="form-horizontal" id="report-form" onkeypress="return event.keyCode != 13;">
                           <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                           <input type="hidden" id="base_url" value="<?php echo $base_url; ?>">
                           <div class="box-body">
                              <div class="form-group">
                                 <!-- Store Code -->
                                 <?php if(store_module() && is_admin()) {$this->load->view('store/store_code',array('show_store_select_box'=>true,'store_id'=>get_current_store_id(),'div_length'=>'col-sm-3','show_all'=>'true','form_group_remove' => 'true')); }else{
                                    echo "<input type='hidden' name='store_id' id='store_id' value='".get_current_store_id()."'>";
                                    }?>
                                 <!-- Store Code end -->

                                 <!-- Warehouse Code -->
                                 <?php 
                                 if(warehouse_module() && warehouse_count()>0) {$this->load->view('warehouse/warehouse_code',array('show_warehouse_select_box'=>true,'div_length'=>'col-sm-3','show_all'=>'true','form_group_remove' => 'true','show_all_option'=>true)); }else{
                                    echo "<input type='hidden' name='warehouse_id' id='warehouse_id' value='".get_store_warehouse_id()."'>";
                                  }
                                 ?>
                                 <!-- Warehouse Code end -->
                              </div>
                              <div class="form-group">
                                 <label for="from_date" class="col-sm-2 control-label"><?= $this->lang->line('from_date'); ?></label>
                                 <div class="col-sm-3">
                                    <div class="input-group date">
                                       <div class="input-group-addon">
                                          <i class="fa fa-calendar"></i>
                                       </div>
                                       <input type="text" class="form-control pull-right datepicker" id="from_date" name="from_date" value="<?php echo show_date(date('d-m-Y', strtotime('-30 days')));?>" >
                                    </div>
                                    <span id="from_date_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 <label for="to_date" class="col-sm-2 control-label"><?= $this->lang->line('to_date'); ?></label>
                                 <div class="col-sm-3">
                                    <div class="input-group date">
                                       <div class="input-group-addon">
                                          <i class="fa fa-calendar"></i>
                                       </div>
                                       <input type="text" class="form-control pull-right datepicker" id="to_date" name="to_date" value="<?php echo show_date(date('d-m-Y'))?>" >
                                    </div>
                                    <span id="to_date_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <label class="col-sm-2 control-label">Show Details:</label>
                                 <div class="col-sm-10">
                                    <label style="font-weight: normal; margin-right: 20px;">
                                       <input type="checkbox" id="show_items_sold" name="show_items_sold" value="1"> Show Items Sold Details
                                    </label>
                                    <label style="font-weight: normal;">
                                       <input type="checkbox" id="show_expenses" name="show_expenses" value="1"> Show Expense List
                                    </label>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-body -->
                           <div class="box-footer">
                              <div class="col-sm-8 col-sm-offset-2 text-center">
                                 <div class="col-md-2 col-md-offset-2">
                                    <button type="button" id="view" class=" btn btn-block btn-success" title="Show Report">
                                       <i class="fa fa-eye"></i> Show Report
                                    </button>
                                 </div>
                                 <div class="col-sm-2">
                                    <button type="button" class="btn btn-block btn-info no-print" onclick="printProfitLossReport()" title="Print">
                                       <i class="fa fa-print"></i> Print
                                    </button>
                                 </div>
                                 <div class="col-sm-2">
                                    <button type="button" id="export-excel" class="btn btn-block btn-success no-print" title="Export to Excel" disabled>
                                       <i class="fa fa-file-excel-o"></i> Export Excel
                                    </button>
                                 </div>
                                 <div class="col-sm-2">
                                    <button type="button" class="btn btn-block btn-warning" id="toggle-form-btn" title="Toggle Form">
                                       <i class="fa fa-chevron-up"></i> <span id="toggle-form-text">Hide Form</span>
                                    </button>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-footer -->
                        </form>
                     </div>
                     <!-- /.box -->
                  </div>
                  <!--/.col (right) -->
               </div>
               <!-- /.row -->
            </section>
            <!-- /.content -->
            <section class="content">
               <div class="row">
                  <div class="col-md-12">
                     <div class="box">
                        <div class="box-header">
                           <h3 class="box-title">Profit & Loss Statement</h3>
                           <div class="box-tools pull-right">
                              <span id="report-period" class="text-muted"></span>
                           </div>
                        </div>
                        <!-- /.box-header -->
                        <div class="box-body">
                           <div id="report-content">
                              <div class="text-center text-muted" style="padding: 50px;">
                                 <i class="fa fa-info-circle fa-3x"></i>
                                 <p style="margin-top: 20px;">Please select date range and click "Show Report" to generate the Profit & Loss Statement</p>
                              </div>
                           </div>
                        </div>
                        <!-- /.box-body -->
                     </div>
                  </div>
               </div>
            </section>
         </div>
         <!-- /.content-wrapper -->
         <?php include"footer.php"; ?>
         <!-- Add the sidebar's background. This div must be placed
            immediately after the control sidebar -->
         <div class="control-sidebar-bg"></div>
      </div>
      <!-- ./wrapper -->
      <!-- SOUND CODE -->
      <?php include"comman/code_js_sound.php"; ?>
      <!-- TABLES CODE -->
      <?php include"comman/code_js.php"; ?>
      
      <script type="text/javascript">
         // Ensure base_url is set properly
         var base_url = $("#base_url").val() || <?php echo json_encode($base_url, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
         
         // Toggle form visibility - keep preview visible
         $("#toggle-form-btn").on("click", function(){
            // Find the form section (the first section.content which contains the form box-primary)
            var formSection = $("section.content").has(".box-primary").first();
            var isVisible = formSection.is(":visible");
            
            if(isVisible){
               formSection.slideUp(300);
               $(this).find("i").removeClass("fa-chevron-up").addClass("fa-chevron-down");
               $("#toggle-form-text").text("Show Form");
            } else {
               formSection.slideDown(300);
               $(this).find("i").removeClass("fa-chevron-down").addClass("fa-chevron-up");
               $("#toggle-form-text").text("Hide Form");
            }
         });
         
         $("#store_id").on("change",function(){
           var store_id=$(this).val();
           //Ajax to load warehouses
           if(typeof load_warehouse_list === 'function'){
             load_warehouse_list();
           } else {
             $.post(base_url+"sales/get_warehouse_select_list",{store_id:store_id},function(result){
                result='<option value="">All</option>'+result;
                $("#warehouse_id").html('').append(result).select2();
            });
           }
         });

         function load_report(){
            $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
            
            var from_date = $("#from_date").val();
            var to_date = $("#to_date").val();
            var store_id = $("#store_id").val();
            var warehouse_id = $("#warehouse_id").val();
            
            // Validate dates
            if(!from_date || !to_date){
               alert("Please select both From Date and To Date");
               $(".overlay").remove();
               return;
            }
            
            $("#view").attr('disabled',true);
            
            var show_items_sold = $('#show_items_sold').is(':checked') ? 1 : 0;
            var show_expenses = $('#show_expenses').is(':checked') ? 1 : 0;
            
            $.ajax({
               type: 'POST',
               url: base_url+'reports/get_profit_loss_statement',
               data: {
                  from_date: from_date,
                  to_date: to_date,
                  store_id: store_id,
                  warehouse_id: warehouse_id,
                  show_items_sold: show_items_sold,
                  show_expenses: show_expenses
               },
               dataType: 'json',
               success: function(result){
                  if(result.error){
                     $("#report-content").html('<div class="alert alert-danger">' + result.message + '</div>');
                  } else {
                     display_report(result);
                  }
                  $("#view").attr('disabled',false);
                  $(".overlay").remove();
               },
               error: function(xhr, status, error){
                  var msg = 'Error loading report. Please try again.';
                  try {
                     var res = (xhr && xhr.responseText) ? JSON.parse(xhr.responseText) : null;
                     if (res && res.message) msg = res.message;
                  } catch (e) {}
                  $("#report-content").html('<div class="alert alert-danger">' + msg + '</div>');
                  $("#view").attr('disabled',false);
                  $(".overlay").remove();
               }
            });
         }
         
         function display_report(data){
            // Safety check
            if (!data || typeof data !== 'object') {
               console.error('Invalid data received:', data);
               $("#report-content").html('<div class="alert alert-danger">Error: Invalid report data received.</div>');
               return;
            }
            var currency = data.currency || {};
            var symbol = currency.symbol || '';
            var position = currency.position || 'before';
            
            function formatCurrency(amount){
               var formatted = Math.abs(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
               var sign = amount < 0 ? '-' : '';
               if(position == 'before'){
                  return sign + symbol + ' ' + formatted;
               } else {
                  return sign + formatted + ' ' + symbol;
               }
            }
            
            var html = '<div class="report-container">';
            
            // Use same store information as at top of page (no hardcoded values)
            var companyName = <?php echo json_encode($store_name, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            var companyAddress = <?php echo json_encode($store_address, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            var companyPhone = <?php echo json_encode($store_phone, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            var companyEmail = <?php echo json_encode($store_email, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            
            // Report Header with Company Information
            html += '<div class="company-header">';
            html += '<h2>' + companyName + '</h2>';
            if(companyAddress) html += '<p style="margin: 3px 0; font-size: 12px;">' + companyAddress + '</p>';
            if(companyPhone) html += '<p style="margin: 3px 0; font-size: 12px;">Phone: ' + companyPhone + '</p>';
            if(companyEmail) html += '<p style="margin: 3px 0; font-size: 12px;">Email: ' + companyEmail + '</p>';
            html += '<div style="margin-top: 15px; padding-top: 15px; border-top: 2px solid #3c8dbc;">';
            html += '<h3 style="margin: 0; color: #3c8dbc; font-size: 20px;">PROFIT & LOSS STATEMENT</h3>';
            html += '<p style="margin: 8px 0 0 0;"><strong>Period:</strong> ' + data.period.from_date + ' to ' + data.period.to_date + '</p>';
            html += '<p style="margin: 5px 0;"><strong>Currency:</strong> ' + currency.code + ' (' + symbol + ')</p>';
            html += '</div>';
            html += '</div>';
            
            // ================== COMPACT T-STYLE P&L TABLE ==================
            var netSales = data.revenue.net_sales || 0;
            var netCogs = data.cost_of_goods_sold.net_cogs || 0;
            var operatingExp = data.operating_expenses.total_operating_expenses || 0;
            var netProfit = data.net_profit || 0;
            
            html += '<div class="pl-section">';
            html += '<div class="pl-section-header">PROFIT & LOSS (T - FORMAT)</div>';
            html += '<div class="table-responsive">';
            html += '<table class="table table-bordered table-striped" style="margin-bottom:0;">';
            html += '<thead>';
            html += '<tr class="bg-info">';
            html += '<th style="width:50%;">Particulars</th>';
            html += '<th style="width:25%; text-align:right;">Debit</th>';
            html += '<th style="width:25%; text-align:right;">Credit</th>';
            html += '</tr>';
            html += '</thead>';
            html += '<tbody>';
            
            // Net Sales on credit side
            html += '<tr>';
            html += '<td>Net Sales (Sales - Sales Returns)</td>';
            html += '<td style="text-align:right;"></td>';
            html += '<td style="text-align:right;">' + formatCurrency(netSales) + '</td>';
            html += '</tr>';
            
            // Cost of Goods Sold on debit side (cost of items actually sold)
            html += '<tr>';
            html += '<td>Net Cost of Goods Sold</td>';
            html += '<td style="text-align:right;">' + formatCurrency(netCogs) + '</td>';
            html += '<td style="text-align:right;"></td>';
            html += '</tr>';
            
            // Operating Expenses on debit side
            html += '<tr>';
            html += '<td>Operating Expenses (Expenses + Sales Tax)</td>';
            html += '<td style="text-align:right;">' + formatCurrency(operatingExp) + '</td>';
            html += '<td style="text-align:right;"></td>';
            html += '</tr>';
            
            // Calculate Gross Profit (for display only, not in T-account)
            var grossProfit = netSales - netCogs;
            
            // Add Gross Profit row (informational, highlighted)
            html += '<tr class="pl-subtotal" style="background-color: #e8f4f8; border-top: 1px solid #3c8dbc;">';
            html += '<td><strong>Gross Profit (Net Sales - Net COGS)</strong></td>';
            html += '<td style="text-align:right;"></td>';
            html += '<td style="text-align:right;"><strong>' + formatCurrency(grossProfit) + '</strong></td>';
            html += '</tr>';
            
            // Net Profit / Loss = balancing figure so that Total Debit = Total Credit
            // Net Profit on DEBIT side => Total Debit = COGS + OpExp + Net Profit = Net Sales = Total Credit
            // Net Loss on CREDIT side => Total Credit = Net Sales + |Net Loss| = COGS + OpExp = Total Debit
            var totalDebit = netCogs + operatingExp;
            var totalCredit = netSales;
            
            if(netProfit >= 0){
               // Net Profit on debit side (balances: Debit = COGS + OpExp + Net Profit = Net Sales = Credit)
               totalDebit += netProfit;
               html += '<tr class="pl-total" style="background-color: #d4edda; border-top: 2px solid #28a745;">';
               html += '<td><strong>Net Profit transferred to Capital</strong></td>';
               html += '<td style="text-align:right;"><strong>' + formatCurrency(netProfit) + '</strong></td>';
               html += '<td style="text-align:right;"></td>';
               html += '</tr>';
            } else {
               // Net Loss on credit side (balances: Credit = Net Sales + |Net Loss| = COGS + OpExp = Debit)
               totalCredit += Math.abs(netProfit);
               html += '<tr class="pl-total" style="background-color: #f8d7da; border-top: 2px solid #dc3545;">';
               html += '<td><strong>Net Loss transferred to Capital</strong></td>';
               html += '<td style="text-align:right;"></td>';
               html += '<td style="text-align:right;"><strong>' + formatCurrency(Math.abs(netProfit)) + '</strong></td>';
               html += '</tr>';
            }
            
            // Total row - Debit and Credit must be equal
            var calculatedDebit = parseFloat(netCogs) + parseFloat(operatingExp);
            var calculatedCredit = parseFloat(netSales);
            
            if(netProfit >= 0){
               calculatedDebit += parseFloat(netProfit);
            } else {
               calculatedCredit += Math.abs(parseFloat(netProfit));
            }
            
            // Round to 2 decimal places for display
            calculatedDebit = Math.round(calculatedDebit * 100) / 100;
            calculatedCredit = Math.round(calculatedCredit * 100) / 100;
            
            var balanceCheck = Math.abs(calculatedDebit - calculatedCredit) < 0.01;
            
            html += '<tr class="bg-warning" style="font-weight: bold; font-size: 14px; border-top: 3px solid #333;">';
            html += '<td style="padding: 12px;"><strong>TOTAL</strong></td>';
            html += '<td style="text-align:right; padding: 12px;"><strong>' + formatCurrency(calculatedDebit) + '</strong></td>';
            html += '<td style="text-align:right; padding: 12px;"><strong>' + formatCurrency(calculatedCredit) + '</strong></td>';
            html += '</tr>';
            
            // Balance verification removed - not needed for this system
            
            html += '</tbody>';
            html += '</table>';
            html += '</div>'; // table-responsive
            html += '</div>'; // pl-section (T-format)
            
            // ================== PURCHASES & PURCHASE RETURNS (REFERENCE) ==================
            var purchases = (data.purchase && data.purchase.purchases != null) ? data.purchase.purchases : 0;
            var purchaseReturn = (data.purchase && data.purchase.purchase_return != null) ? data.purchase.purchase_return : 0;
            var netPurchases = (data.purchase && data.purchase.net_purchases != null) ? data.purchase.net_purchases : (purchases - purchaseReturn);
            html += '<div class="pl-section" style="margin-top: 16px;">';
            html += '<div class="pl-section-header">PURCHASES &amp; PURCHASE RETURNS (REFERENCE)</div>';
            html += '<p class="text-muted" style="margin-bottom: 10px; font-size: 12px;">Period totals. Net COGS above is cost of items actually sold.</p>';
            html += '<div class="table-responsive">';
            html += '<table class="table table-bordered table-condensed" style="margin-bottom:0; font-size: 13px;">';
            html += '<thead><tr class="bg-light"><th style="width:50%;">Particulars</th><th style="width:25%; text-align:right;">Debit</th><th style="width:25%; text-align:right;">Credit</th></tr></thead><tbody>';
            html += '<tr><td>Purchases (period)</td><td style="text-align:right;">' + formatCurrency(purchases) + '</td><td style="text-align:right;"></td></tr>';
            html += '<tr><td>Purchase Returns (period)</td><td style="text-align:right;"></td><td style="text-align:right;">' + formatCurrency(purchaseReturn) + '</td></tr>';
            html += '<tr class="bg-light"><td><strong>Net Purchases</strong></td><td style="text-align:right;"><strong>' + formatCurrency(netPurchases) + '</strong></td><td style="text-align:right;"></td></tr>';
            html += '</tbody></table></div></div>';
            
            // ================== DETAILED ITEMS SOLD (IF ENABLED) ==================
            if(data.show_items_sold && data.items_sold && data.items_sold.length > 0){
               html += '<div class="pl-section" style="margin-top: 20px;">';
               html += '<div class="pl-section-header">ITEMS SOLD DETAILS</div>';
               html += '<div class="table-responsive">';
               html += '<table class="table table-bordered table-striped table-sm" style="margin-bottom:0; font-size: 12px;">';
               html += '<thead>';
               html += '<tr class="bg-info">';
               html += '<th>#</th>';
               html += '<th>Item Name</th>';
               html += '<th style="text-align:right;">Quantity</th>';
               html += '<th style="text-align:right;">Unit Price</th>';
               html += '<th style="text-align:right;">Total Sales</th>';
               html += '<th style="text-align:right;">Cost</th>';
               html += '<th style="text-align:right;">Profit</th>';
               html += '</tr>';
               html += '</thead>';
               html += '<tbody>';
               
               var itemsTotalSales = 0;
               var itemsTotalCost = 0;
               var itemsTotalProfit = 0;
               
               data.items_sold.forEach(function(item, index){
                  var itemProfit = (item.total_sales || 0) - (item.total_cost || 0);
                  itemsTotalSales += item.total_sales || 0;
                  itemsTotalCost += item.total_cost || 0;
                  itemsTotalProfit += itemProfit;
                  
                  html += '<tr>';
                  html += '<td>' + (index + 1) + '</td>';
                  html += '<td>' + (item.item_name || 'N/A') + '</td>';
                  html += '<td style="text-align:right;">' + parseFloat(item.total_qty || 0).toFixed(2) + '</td>';
                  html += '<td style="text-align:right;">' + formatCurrency(item.avg_price || 0) + '</td>';
                  html += '<td style="text-align:right;">' + formatCurrency(item.total_sales || 0) + '</td>';
                  html += '<td style="text-align:right;">' + formatCurrency(item.total_cost || 0) + '</td>';
                  html += '<td style="text-align:right; color: ' + (itemProfit >= 0 ? '#28a745' : '#dc3545') + ';">' + formatCurrency(itemProfit) + '</td>';
                  html += '</tr>';
               });
               
               html += '<tr class="bg-warning" style="font-weight: bold;">';
               html += '<td colspan="4"><strong>TOTAL</strong></td>';
               html += '<td style="text-align:right;"><strong>' + formatCurrency(itemsTotalSales) + '</strong></td>';
               html += '<td style="text-align:right;"><strong>' + formatCurrency(itemsTotalCost) + '</strong></td>';
               html += '<td style="text-align:right; color: ' + (itemsTotalProfit >= 0 ? '#28a745' : '#dc3545') + ';"><strong>' + formatCurrency(itemsTotalProfit) + '</strong></td>';
               html += '</tr>';
               html += '</tbody>';
               html += '</table>';
               html += '</div>';
               html += '</div>';
            }
            
            // ================== DETAILED EXPENSE LIST (IF ENABLED) ==================
            if(data.show_expenses && data.expenses_list && data.expenses_list.length > 0){
               html += '<div class="pl-section" style="margin-top: 20px;">';
               html += '<div class="pl-section-header">EXPENSE DETAILS</div>';
               html += '<div class="table-responsive">';
               html += '<table class="table table-bordered table-striped table-sm" style="margin-bottom:0; font-size: 12px;">';
               html += '<thead>';
               html += '<tr class="bg-info">';
               html += '<th>#</th>';
               html += '<th>Date</th>';
               html += '<th>Expense Category</th>';
               html += '<th>Description</th>';
               html += '<th style="text-align:right;">Amount</th>';
               html += '</tr>';
               html += '</thead>';
               html += '<tbody>';
               // Expense Loop
               var expensesTotal = 0;
               
               data.expenses_list.forEach(function(expense, index){
                  var amt = parseFloat(expense.expense_amt);
amt = isNaN(amt) ? 0 : amt;
expensesTotal += amt;
                  
                  html += '<tr>';
                  html += '<td>' + (index + 1) + '</td>';
                  html += '<td>' + (expense.expense_date || 'N/A') + '</td>';
                  html += '<td>' + (expense.category_name || 'N/A') + '</td>';
                  html += '<td>' + (expense.expense_note || 'N/A') + '</td>';
                  html += '<td style="text-align:right;">' + formatCurrency(amt) + '</td>';
                  html += '</tr>';
               });
               
               html += '<tr class="bg-warning" style="font-weight: bold;">';
               html += '<td colspan="4"><strong>TOTAL EXPENSES</strong></td>';
               html += '<td style="text-align:right;"><strong>' + formatCurrency(expensesTotal) + '</strong></td>';
               html += '</tr>';
               html += '</tbody>';
               html += '</table>';
               html += '</div>';
               html += '</div>';
            } //End of expense loop
            
            // ================== CASH SUMMARY ==================
            html += '<div class="pl-section" style="margin-top: 20px;">';
            html += '<div class="pl-section-header">CASH SUMMARY</div>';
            html += '<div class="table-responsive">';
            html += '<table class="table table-bordered table-striped" style="margin-bottom:0;">';
            html += '<tbody>';
            html += '<tr>';
            html += '<td style="width:60%;"><strong>Opening Cash Balance</strong></td>';
            html += '<td style="width:40%; text-align:right;">' + formatCurrency(data.cash.opening_balance) + '</td>';
            html += '</tr>';
            html += '<tr>';
            html += '<td><strong>Net Cash Flow (Period)</strong></td>';
            html += '<td style="text-align:right;">' + formatCurrency(data.cash.net_cash_flow) + '</td>';
            html += '</tr>';
            html += '<tr class="bg-warning" style="font-weight: bold; border-top: 2px solid #333;">';
            html += '<td><strong>Closing Cash Balance</strong></td>';
            html += '<td style="text-align:right;"><strong>' + formatCurrency(data.cash.closing_balance) + '</strong></td>';
            html += '</tr>';
            html += '</tbody>';
            html += '</table>';
            html += '</div>';
            html += '</div>';
            
            // Report Footer
            html += '<div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; text-align: center; color: #666; font-size: 12px;">';
            html += '<p>Generated on: ' + new Date().toLocaleString() + '</p>';
            html += '<p>Transaction Counts - Sales: ' + data.details.sales_count + ' | Purchases: ' + data.details.purchase_count + ' | Expenses: ' + data.details.expense_count + '</p>';
            html += '</div>';
            
            html += '</div>';
            
            // Add export actions
            html += '<div class="report-actions no-print">';
            html += '<button type="button" class="btn btn-info" onclick="printProfitLossReport()"><i class="fa fa-print"></i> Print Report</button>';
            html += '<button type="button" class="btn btn-success" id="export-excel-btn"><i class="fa fa-file-excel-o"></i> Export to Excel</button>';
            html += '</div>';
            
            $("#report-content").html(html);
            $("#report-period").text(data.period.from_date + ' to ' + data.period.to_date);
            
            // Store report data for export
            window.currentReportData = data;
            
            // Enable export button
            $("#export-excel").prop('disabled', false);
            
            // Export button handler
            $("#export-excel-btn, #export-excel").off('click').on('click', function(){
               exportToExcel();
            });
         }
         
         function exportToExcel(){
            if(!window.currentReportData){
               alert('Please generate the report first');
               return;
            }
            
            var from_date = $("#from_date").val();
            var to_date = $("#to_date").val();
            var store_id = $("#store_id").val();
            var warehouse_id = $("#warehouse_id").val();
            
            var show_items_sold = $('#show_items_sold').is(':checked') ? 1 : 0;
            var show_expenses = $('#show_expenses').is(':checked') ? 1 : 0;
            
            var url = base_url + 'reports/export_profit_loss_excel';
            var params = [];
            if(from_date) params.push('from_date=' + encodeURIComponent(from_date));
            if(to_date) params.push('to_date=' + encodeURIComponent(to_date));
            if(store_id) params.push('store_id=' + encodeURIComponent(store_id));
            if(warehouse_id) params.push('warehouse_id=' + encodeURIComponent(warehouse_id));
            if(show_items_sold) params.push('show_items_sold=' + show_items_sold);
            if(show_expenses) params.push('show_expenses=' + show_expenses);
            
            if(params.length > 0){
               url += '?' + params.join('&');
            }
            
            window.open(url, '_blank');
         }

         $("#view").on("click",function(){
            check_field("from_date");
            check_field("to_date");
            load_report();
         });

         function check_field(id){
            if(!$("#"+id).val()){
               $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
               return false;
            } else {
               $('#'+id+'_msg').fadeOut(200).hide();
               return true;
            }
         }
         
         // Professional A4 Print Function for Profit & Loss Statement
         function printProfitLossReport() {
            // Check if report data exists
            if (!window.currentReportData || typeof window.currentReportData !== 'object') {
               alert('Please generate the Profit & Loss Statement first before printing.');
               return;
            }
            
            var data = window.currentReportData;
            
            // Safety check for required data properties
            if (!data.currency || !data.period || !data.revenue || !data.cost_of_goods_sold || !data.operating_expenses) {
               alert('Error: Report data is incomplete. Please regenerate the report.');
               return;
            }
            
            // Create print window - don't close on cancel
            var printWindow = window.open('', '_blank', 'width=800,height=600');
            if (!printWindow) {
               alert('Please allow popups to print the report');
               return;
            }
            
            // Get company information
            var companyName = <?php echo json_encode($store_name, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            var companyAddress = <?php echo json_encode($store_address, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            var companyPhone = <?php echo json_encode($store_phone, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            var companyEmail = <?php echo json_encode($store_email, JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
            
            // Get current date
            var currentDate = new Date().toLocaleDateString();
            
            // Get report filters
            var storeName = $('#store_id option:selected').text() || 'All Stores';
            var warehouseName = $('#warehouse_id option:selected').text() || 'All Warehouses';
            var fromDate = data.period.from_date;
            var toDate = data.period.to_date;
            
            // Currency formatting
            var currency = data.currency;
            var symbol = currency.symbol || '';
            var position = currency.position || 'before';
            
            function formatCurrency(amount){
               var formatted = Math.abs(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
               var sign = amount < 0 ? '-' : '';
               if(position == 'before'){
                  return sign + symbol + ' ' + formatted;
               } else {
                  return sign + formatted + ' ' + symbol;
               }
            }
            
            // Build print content
            var printContent = `
               <!DOCTYPE html>
               <html>
               <head>
                  <title>Profit & Loss Statement</title>
                  <style>
                     body { font-family: Arial, sans-serif; font-size: 11px; margin: 0; padding: 15px; color: #000; font-weight: bold; }
                     .print-header { text-align: center; margin-bottom: 25px; border-bottom: 2px solid #000; padding-bottom: 15px; }
                     .print-header h1 { font-size: 22px; font-weight: bold; margin: 0 0 8px 0; color: #000; }
                     .print-header .company-info { font-size: 12px; color: #000; font-weight: bold; margin: 3px 0; }
                     .print-header .report-title { font-size: 16px; font-weight: bold; margin: 12px 0 8px 0; color: #000; }
                     .print-header .report-filters { font-size: 11px; color: #000; font-weight: bold; margin: 3px 0; }
                     .pl-section { margin-bottom: 15px; border: 1px solid #000; page-break-inside: avoid; }
                     .pl-section-header { background-color: #d0d0d0; color: #000; font-weight: bold; padding: 3px 5px; text-align: center; font-size: 11px; border: 1px solid #000; border-left: 3px solid #000; }
                     table { width: 100%; border-collapse: collapse; margin: 0; }
                     th { background-color: #d0d0d0; color: #000; font-weight: bold; padding: 8px; border: 1px solid #000; }
                     td { padding: 6px; border: 1px solid #000; color: #000; font-weight: bold; }
                     .text-right { text-align: right; }
                     .text-left { text-align: left; }
                     .text-center { text-align: center; }
                     .summary-box { border: 2px solid #000; padding: 12px; margin-top: 15px; background-color: #f9f9f9; page-break-inside: avoid; }
                     .summary-box h4 { margin-top: 0; color: #000; font-size: 14px; font-weight: bold; }
                     .print-footer { margin-top: 20px; text-align: center; font-size: 9px; color: #000; font-weight: bold; border-top: 1px solid #000; padding-top: 8px; }
                     th, td, .print-header *, .summary-box * { color: #000 !important; font-weight: bold !important; }
                     @page { margin: 1cm; size: A4; }
                     @media print {
                        body { font-size: 10px; padding: 10px; color: #000; font-weight: bold; }
                        .pl-section { page-break-inside: avoid; }
                        .summary-box { page-break-inside: avoid; }
                     }
                  </style>
               </head>
               <body>
                  <div class="print-header">
                     <h1>${companyName}</h1>
                     ${companyAddress ? '<div class="company-info">' + companyAddress + '</div>' : ''}
                     ${companyPhone ? '<div class="company-info">' + companyPhone + '</div>' : ''}
                     ${companyEmail ? '<div class="company-info">' + companyEmail + '</div>' : ''}
                     <div class="report-title">PROFIT & LOSS STATEMENT</div>
                     <div class="report-filters"><strong>Store:</strong> ${storeName}</div>
                     <div class="report-filters"><strong>Warehouse:</strong> ${warehouseName || 'All Warehouses'}</div>
                     <div class="report-filters"><strong>Period:</strong> ${fromDate} to ${toDate}</div>
                     <div class="report-filters"><strong>Currency:</strong> ${currency.code} (${symbol})</div>
                     <div class="report-filters"><strong>Generated:</strong> ${currentDate}</div>
                  </div>
                  
                  <!-- COMPACT T-STYLE PROFIT & LOSS TABLE -->
                  <div class="pl-section">
                     <div class="pl-section-header">PROFIT &amp; LOSS (T - FORMAT)</div>
                     <table style="width: 100%; border-collapse: collapse; margin-top: 5px; font-size: 9px;">
                        <thead>
                           <tr style="background-color: #34495e; color: white; font-weight: bold;">
                              <th style="width:50%; padding: 4px; border: 1px solid #000; text-align: left; font-size: 9px; color: #fff;">Particulars</th>
                              <th style="width:25%; padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #fff;">Debit</th>
                              <th style="width:25%; padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #fff;">Credit</th>
                           </tr>
                        </thead>
                        <tbody>
                           <tr>
                              <td style="padding: 3px; border: 1px solid #000; font-size: 9px; color: #000;">Net Sales (Sales - Sales Returns)</td>
                              <td style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"></td>
                              <td style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;">${formatCurrency(data.revenue.net_sales)}</td>
                           </tr>
                           <tr>
                              <td style="padding: 3px; border: 1px solid #000; font-size: 9px; color: #000;">Net Cost of Goods Sold</td>
                              <td style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;">${formatCurrency(data.cost_of_goods_sold.net_cogs)}</td>
                              <td style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"></td>
                           </tr>
                           <tr>
                              <td style="padding: 3px; border: 1px solid #000; font-size: 9px; color: #000;">Operating Expenses (Expenses + Sales Tax)</td>
                              <td style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;">${formatCurrency(data.operating_expenses.total_operating_expenses)}</td>
                              <td style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"></td>
                           </tr>
                           <tr style="background-color: #e8f4f8; font-weight: bold; border-top: 1px solid #000;">
                              <td style="padding: 4px; border: 1px solid #000; font-size: 9px; color: #000;"><strong>Gross Profit (Net Sales - Net COGS)</strong></td>
                              <td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"></td>
                              <td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"><strong>${formatCurrency(data.gross_profit)}</strong></td>
                           </tr>
                           ${(() => {
                              var netProfit = parseFloat(data.net_profit) || 0;
                              var netCogs = parseFloat(data.cost_of_goods_sold.net_cogs) || 0;
                              var operatingExp = parseFloat(data.operating_expenses.total_operating_expenses) || 0;
                              var netSales = parseFloat(data.revenue.net_sales) || 0;
                              
                              var totalDebit = netCogs + operatingExp;
                              var totalCredit = netSales;
                              
                              if(netProfit >= 0){
                                 totalDebit += netProfit;
                                 return '<tr style="background-color: #d4edda; font-weight: bold; border-top: 1px solid #000;"><td style="padding: 4px; border: 1px solid #000; font-size: 9px; color: #000;"><strong>Net Profit transferred to Capital</strong></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"><strong>' + formatCurrency(netProfit) + '</strong></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"></td></tr>';
                              } else {
                                 totalCredit += Math.abs(netProfit);
                                 return '<tr style="background-color: #f8d7da; font-weight: bold; border-top: 1px solid #000;"><td style="padding: 4px; border: 1px solid #000; font-size: 9px; color: #000;"><strong>Net Loss transferred to Capital</strong></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"><strong>' + formatCurrency(Math.abs(netProfit)) + '</strong></td></tr>';
                              }
                           })()}
                           ${(() => {
                              var netProfit = parseFloat(data.net_profit) || 0;
                              var netCogs = parseFloat(data.cost_of_goods_sold.net_cogs) || 0;
                              var operatingExp = parseFloat(data.operating_expenses.total_operating_expenses) || 0;
                              var netSales = parseFloat(data.revenue.net_sales) || 0;
                              
                              var totalDebit = netCogs + operatingExp;
                              var totalCredit = netSales;
                              
                              if(netProfit >= 0){
                                 totalDebit += netProfit;
                              } else {
                                 totalCredit += Math.abs(netProfit);
                              }
                              
                              // Round to 2 decimals
                              totalDebit = Math.round(totalDebit * 100) / 100;
                              totalCredit = Math.round(totalCredit * 100) / 100;
                              
                              var balanceCheck = Math.abs(totalDebit - totalCredit) < 0.01;
                              
                              var html = '<tr style="background-color: #ffc107; font-weight: bold; font-size: 10px; border-top: 2px solid #000;">';
                              html += '<td style="padding: 5px; border: 1px solid #000; font-size: 9px; color: #000;"><strong>TOTAL</strong></td>';
                              html += '<td style="padding: 5px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"><strong>' + formatCurrency(totalDebit) + '</strong></td>';
                              html += '<td style="padding: 5px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"><strong>' + formatCurrency(totalCredit) + '</strong></td>';
                              html += '</tr>';
                              
                              // Balance verification removed - not needed for this system
                              
                              return html;
                           })()}
                        </tbody>
                     </table>
                  </div>
                  
                  <div class="pl-section" style="margin-top: 10px;">
                     <div class="pl-section-header">PURCHASES &amp; PURCHASE RETURNS (REFERENCE)</div>
                     <p style="margin: 3px 0 6px 0; font-size: 8px; color: #333;">Period totals. Net COGS above is cost of items actually sold.</p>
                     <table style="width: 100%; border-collapse: collapse; font-size: 9px;">
                        <tr><td style="padding: 3px; border: 1px solid #000;">Purchases (period)</td><td style="padding: 3px; border: 1px solid #000; text-align: right;">${formatCurrency(data.purchase && data.purchase.purchases != null ? data.purchase.purchases : 0)}</td><td style="padding: 3px; border: 1px solid #000; text-align: right;"></td></tr>
                        <tr><td style="padding: 3px; border: 1px solid #000;">Purchase Returns (period)</td><td style="padding: 3px; border: 1px solid #000; text-align: right;"></td><td style="padding: 3px; border: 1px solid #000; text-align: right;">${formatCurrency(data.purchase && data.purchase.purchase_return != null ? data.purchase.purchase_return : 0)}</td></tr>
                        <tr style="font-weight: bold;"><td style="padding: 3px; border: 1px solid #000;">Net Purchases</td><td style="padding: 3px; border: 1px solid #000; text-align: right;">${formatCurrency(data.purchase && data.purchase.net_purchases != null ? data.purchase.net_purchases : ((data.purchase && data.purchase.purchases != null ? data.purchase.purchases : 0) - (data.purchase && data.purchase.purchase_return != null ? data.purchase.purchase_return : 0)))}</td><td style="padding: 3px; border: 1px solid #000;"></td></tr>
                     </table>
                  </div>
                  
                  ${data.show_items_sold && data.items_sold && data.items_sold.length > 0 ? `
                  <div class="pl-section" style="margin-top: 10px;">
                     <div class="pl-section-header">ITEMS SOLD DETAILS</div>
                     <table style="width: 100%; border-collapse: collapse; margin-top: 5px; font-size: 8px;">
                        <thead>
                           <tr style="background-color: #34495e; color: white; font-weight: bold;">
                              <th style="padding: 3px; border: 1px solid #000; font-size: 8px; color: #fff;">#</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: left; font-size: 8px; color: #fff;">Item Name</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 8px; color: #fff;">Quantity</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 8px; color: #fff;">Unit Price</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 8px; color: #fff;">Total Sales</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 8px; color: #fff;">Cost</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 8px; color: #fff;">Profit</th>
                           </tr>
                        </thead>
                        <tbody>
                           ${(() => {
                              var itemsTotalSales = 0;
                              var itemsTotalCost = 0;
                              var itemsTotalProfit = 0;
                              var rows = data.items_sold.map((item, index) => {
                                 var itemProfit = (item.total_sales || 0) - (item.total_cost || 0);
                                 itemsTotalSales += item.total_sales || 0;
                                 itemsTotalCost += item.total_cost || 0;
                                 itemsTotalProfit += itemProfit;
                                 return '<tr><td style="padding: 2px; border: 1px solid #000; font-size: 8px; color: #000;">' + (index + 1) + '</td><td style="padding: 2px; border: 1px solid #000; font-size: 8px; color: #000;">' + (item.item_name || 'N/A') + '</td><td style="padding: 2px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;">' + parseFloat(item.total_qty || 0).toFixed(2) + '</td><td style="padding: 2px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;">' + formatCurrency(item.avg_price || 0) + '</td><td style="padding: 2px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;">' + formatCurrency(item.total_sales || 0) + '</td><td style="padding: 2px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;">' + formatCurrency(item.total_cost || 0) + '</td><td style="padding: 2px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;">' + formatCurrency(itemProfit) + '</td></tr>';
                              }).join('');
                              // Add totals row
                              rows += '<tr style="background-color: #ffc107; font-weight: bold; border-top: 1px solid #000;"><td colspan="3" style="padding: 4px; border: 1px solid #000; font-size: 8px; color: #000;"><strong>TOTAL</strong></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;"></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;"><strong>' + formatCurrency(itemsTotalSales) + '</strong></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;"><strong>' + formatCurrency(itemsTotalCost) + '</strong></td><td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 8px; color: #000;"><strong>' + formatCurrency(itemsTotalProfit) + '</strong></td></tr>';
                              return rows;
                           })()}
                        </tbody>
                     </table>
                  </div>
                  ` : ''}
                  
                  ${data.show_expenses && data.expenses_list && data.expenses_list.length > 0 ? `
                  <div class="pl-section" style="margin-top: 10px;">
                     <div class="pl-section-header">EXPENSE DETAILS</div>
                     <table style="width: 100%; border-collapse: collapse; margin-top: 5px; font-size: 8px;">
                        <thead>
                           <tr style="background-color: #34495e; color: white; font-weight: bold;">
                              <th style="padding: 3px; border: 1px solid #000; font-size: 8px; color: #fff;">#</th>
                              <th style="padding: 3px; border: 1px solid #000; font-size: 8px; color: #fff;">Date</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: left; font-size: 8px; color: #fff;">Category</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: left; font-size: 8px; color: #fff;">Description</th>
                              <th style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 8px; color: #fff;">Amount</th>
                           </tr>
                        </thead>
                        <tbody>
                           ${(() => {
   var total = 0;

   var rows = data.expenses_list.map((expense, index) => {
      var amt = parseFloat(expense.expense_amt);
      amt = isNaN(amt) ? 0 : amt;

      total += amt;

      return '<tr>' +
         '<td style="padding: 2px; border: 1px solid #000; font-size: 8px;">' + (index + 1) + '</td>' +
         '<td style="padding: 2px; border: 1px solid #000; font-size: 8px;">' + (expense.expense_date || 'N/A') + '</td>' +
         '<td style="padding: 2px; border: 1px solid #000; font-size: 8px;">' + (expense.category_name || 'N/A') + '</td>' +
         '<td style="padding: 2px; border: 1px solid #000; font-size: 8px;">' + (expense.expense_note || 'N/A') + '</td>' +
         '<td style="padding: 2px; border: 1px solid #000; text-align: right; font-size: 8px;">' + formatCurrency(amt) + '</td>' +
      '</tr>';
   }).join('');

   // ADD TOTAL ROW
   rows += '<tr style="background-color: #ffc107; font-weight: bold;">' +
      '<td colspan="4" style="padding: 4px; border: 1px solid #000;">TOTAL EXPENSES</td>' +
      '<td style="padding: 4px; border: 1px solid #000; text-align: right;">' + formatCurrency(total) + '</td>' +
   '</tr>';

   return rows;
})()}
                        </tbody>
                     </table>
                  </div>
                  ` : ''}
                  
                  <!-- CASH SUMMARY -->
                  <div class="pl-section" style="margin-top: 10px;">
                     <div class="pl-section-header">CASH SUMMARY</div>
                     <table style="width: 100%; border-collapse: collapse; margin-top: 5px; font-size: 9px;">
                        <tbody>
                           <tr>
                              <td style="width:60%; padding: 3px; border: 1px solid #000; font-size: 9px; color: #000;"><strong>Opening Cash Balance</strong></td>
                              <td style="width:40%; padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;">${formatCurrency(data.cash.opening_balance)}</td>
                           </tr>
                           <tr>
                              <td style="padding: 3px; border: 1px solid #000; font-size: 9px; color: #000;"><strong>Net Cash Flow (Period)</strong></td>
                              <td style="padding: 3px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;">${formatCurrency(data.cash.net_cash_flow)}</td>
                           </tr>
                           <tr style="background-color: #ffc107; font-weight: bold; border-top: 1px solid #000;">
                              <td style="padding: 4px; border: 1px solid #000; font-size: 9px; color: #000;"><strong>Closing Cash Balance</strong></td>
                              <td style="padding: 4px; border: 1px solid #000; text-align: right; font-size: 9px; color: #000;"><strong>${formatCurrency(data.cash.closing_balance)}</strong></td>
                           </tr>
                        </tbody>
                     </table>
                  </div>
                  
                  <div class="print-footer">
                     <p>Transaction Counts - Sales: ${data.details.sales_count} | Purchases: ${data.details.purchase_count} | Expenses: ${data.details.expense_count}</p>
                     <p>This report was generated on ${currentDate} by ${companyName} System</p>
                     ${companyEmail ? '<p>For any queries, please contact us at ' + companyEmail + '</p>' : ''}
                  </div>
               </body>
               </html>
            `;
            
            // Write content and print
            printWindow.document.write(printContent);
            printWindow.document.close();
            
            // Wait for content to load, then print
            printWindow.onload = function() {
               printWindow.focus();
               // Don't auto-close - let user close manually after printing/canceling
               printWindow.print();
            };
         }
      </script>
      
      <!-- Make sidebar menu highlighter/selector -->
      <script>
         $(document).ready(function(){
            $(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");
         });
      </script>
   </body>
</html>

