 <!DOCTYPE html>
<html>
   <head>
      <!-- TABLES CSS CODE -->
      <?php include"comman/code_css.php"; ?>
      <!-- </copy> -->  
   </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 -->
                                </div>
                                <div class="form-group">
                                  <!-- Warehouse Code -->
                                  <?php if(true) {$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 -->
                                 <label for="customer_id" class="col-sm-2 control-label"><?= $this->lang->line('customer_name'); ?></label>
                                 <div class="col-sm-3">
                                    <select class="form-control select2 " id="customer_id" name="customer_id" >
                                    </select>
                                    <span id="customer_id_msg" style="display:none" class="text-danger"></span>
                                 </div>

                              </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'));?>" >
                                    </div>
                                    <span id="Sales_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="Sales_date_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>

                              <div class="form-group">
                                 <label for="from_time" class="col-sm-2 control-label">From Time</label>
                                 <div class="col-sm-3">
                                    <input type="time" class="form-control" id="from_time" name="from_time" value="00:00">
                                    <span id="from_time_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 <label for="to_time" class="col-sm-2 control-label">To Time</label>
                                 <div class="col-sm-3">
                                    <input type="time" class="form-control" id="to_time" name="to_time" value="23:59">
                                    <span id="to_time_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>

                              <div class="form-group">
                                 <label for="reference_no" class="col-sm-2 control-label">Reference No</label>
                                 <div class="col-sm-3">
                                    <input type="text" class="form-control" id="reference_no" name="reference_no" placeholder="Enter Reference Number">
                                    <span id="reference_no_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 <label for="created_by" class="col-sm-2 control-label"><?= $this->lang->line('user'); ?></label>
                                 <div class="col-sm-3">
                                    <select class="form-control select2 " id="created_by" name="created_by">
                                       
                                       <?= get_users_select_list($this->session->userdata("role_id"),get_current_store_id());?>
                                    </select>
                                    <span id="created_by_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>
                              
                           </div>
                           <!-- /.box-body -->
                           <div class="box-footer">
                              <div class="col-sm-8 col-sm-offset-2 text-center">
                                 <div class="col-md-3 col-md-offset-3">
                                    <button type="button" id="view" class=" btn btn-block btn-success" title="Save Data">Show</button>
                                 </div>
                                 <div class="col-sm-3">
                                    <a href="<?=base_url('dashboard');?>">
                                    <button type="button" class="col-sm-3 btn btn-block btn-warning close_btn" title="Go Dashboard">Close</button>
                                    </a>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-footer -->
                        </form>
                     </div>
                     <!-- /.box -->
                  </div>
                  <!--/.col (right) -->
               </div>
               <!-- /.row -->
               <div class="row">
                  <!-- right column -->
                  <div class="col-md-12">
                     <!-- Horizontal Form -->
                     <div class="box box-info ">
                        <div class="box-header with-border">
                           <h3 class="box-title">Billwise Report</h3>
                           <div class="box-tools">
                              <button type="button" class="btn btn-success btn-sm export_csv" id="export_csv"><i class="fa fa-file-excel-o"> </i> Export CSV</button>
                              <button type="button" class="btn btn-info btn-sm print_it1"><i class="fa fa-print"> </i> Print</button>
                              <button type="button" class="btn btn-info btn-sm print_it" id="print_it"><i class="fa fa-print"> </i> 3 Inch Print</button>
                           </div>
                        </div>
                        <!-- /.box-header -->
                        <div class="box-body table-responsive no-padding">
                           
                           <table class="table table-bordered table-hover " id="report-data" >
                              <thead>
                                 <tr class="bg-gray ">
                                    <th style="">#</th>
                                    <?php if(store_module() && is_admin()) { ?> <th><?= $this->lang->line('store'); ?></th> <?php } ?>
                                    <?php if(warehouse_module() && warehouse_count()>0) { ?> <th><?= $this->lang->line('warehouse'); ?></th> <?php } ?>
                                    <th><?= $this->lang->line('sales_code'); ?></th>
                                    <th><?= $this->lang->line('date'); ?></th>
                                    <th>Reference No</th>
                                    <th><?= $this->lang->line('customer_name'); ?></th>
                                    <th><?= $this->lang->line('customer_code'); ?></th>
                                    <th><?= $this->lang->line('grand_total'); ?></th>
                                    <th><?= $this->lang->line('paid_amount'); ?></th>
                                    <th><?= $this->lang->line('due_amount'); ?></th>
                                    <th>Profit</th>
                                    <th><?= $this->lang->line('sales_note'); ?></th>
                                    <th><?= $this->lang->line('created_by'); ?></th>
                                 </tr>
                              </thead>
                              <tbody id="tbody_data">
                                 
                              </tbody>
                           </table>
                        </div>
                        <!-- /.box-body -->
                     </div>
                     <!-- /.box -->
                  </div>
                  <!--/.col (right) -->
               </div>
               <!-- /.row -->
            </section>
            <!-- /.content -->
         </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 src="<?php echo $theme_link; ?>js/report.js"></script>
      <script type="text/javascript">
         $(document).ready(function() {
             //Called on page load
             <?php if(isset($customer_id) && $customer_id!=''){ ?>
             	get_customers_select_list(<?= $customer_id; ?>,'<?= @$customer_name;?>');
             <?php }else{ ?>
             	get_customers_select_list();
             <?php } ?>
         });
         
         
         function get_customers_select_list(customer_id='',customer_name=''){
         	$("#customer_id").html('<option value="">-All Customers-</option>');
         	$.post("<?php echo site_url('customers/get_customers_select_list')?>",{customer_id:customer_id},function(result){
               $("#customer_id").append(result);
             });
             if(customer_id!=''){
             	$('#customer_id').val(customer_id).trigger('change');
             }
         }

         $("#view").click(function(){
           var base_url=$("#base_url").val();
           
           if($("#from_date").val()==''){
             toastr["error"]("From Date is Required");
             return;
           }
           if($("#to_date").val()==''){
             toastr["error"]("To Date is Required");
             return;
           }
           
           // Add loading overlay
           $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
           
           $.post("<?php echo site_url('reports/show_billwise_report')?>",{
             from_date: $("#from_date").val(),
             to_date: $("#to_date").val(),
             from_time: $("#from_time").val() || '00:00',
             to_time: $("#to_time").val() || '23:59',
             reference_no: $("#reference_no").val() || '',
             customer_id: $("#customer_id").val() || '',
             store_id: $("#store_id").val() || '',
             warehouse_id: $("#warehouse_id").val() || '',
             created_by: $("#created_by").val() || '',
             <?php echo $this->security->get_csrf_token_name();?>: $("input[name='<?php echo $this->security->get_csrf_token_name();?>']").val()
           },function(result){
             $("#tbody_data").html(result);
             $(".overlay").remove();
           }).fail(function(xhr, status, error) {
             console.error("Error:", error);
             console.error("Response:", xhr.responseText);
             toastr["error"]("Error loading report: " + error);
             $(".overlay").remove();
           });
         });

         // 3 inch print
         $("#print_it").click(function(){
           if($("#tbody_data tr").length == 0){
             toastr["error"]("Please generate report first");
             return;
           }
           
           var base_url=$("#base_url").val();
           var print_window = window.open('', '_blank');
           
           var print_content = `
           <html>
           <head>
             <title>Billwise Report</title>
             <style>
               @page { size: 80mm auto; margin: 2mm; }
               body { 
                 font-family: 'Arial', 'Helvetica', sans-serif; 
                 font-size: 12px; 
                 margin: 0; 
                 padding: 3mm;
                 width: 74mm;
                 line-height: 1.4;
                 font-weight: normal;
               }
               .header { 
                 text-align: center; 
                 margin-bottom: 12px; 
                 border-bottom: 2px solid #000;
                 padding-bottom: 8px;
               }
               .company-name { 
                 font-size: 16px; 
                 font-weight: bold; 
                 margin-bottom: 4px;
                 text-transform: uppercase;
               }
               .report-title { 
                 font-size: 14px; 
                 margin: 4px 0; 
                 font-weight: bold;
                 text-decoration: underline;
               }
               .filters { 
                 font-size: 11px; 
                 margin-bottom: 8px; 
                 font-weight: normal;
               }
               .bill-item { 
                 margin-bottom: 12px; 
                 padding: 6px 0; 
                 border-bottom: 1px solid #333;
                 page-break-inside: avoid;
               }
               .bill-header { 
                 font-weight: bold; 
                 font-size: 13px; 
                 margin-bottom: 4px;
                 text-align: center;
                 background-color: #f0f0f0;
                 padding: 3px;
                 border: 1px solid #000;
               }
               .bill-row { 
                 display: flex; 
                 justify-content: space-between; 
                 font-size: 11px; 
                 margin: 3px 0;
                 padding: 1px 0;
               }
               .bill-label { 
                 width: 45%; 
                 text-align: left;
                 font-weight: bold;
               }
               .bill-value { 
                 width: 50%; 
                 text-align: right;
                 font-weight: normal;
               }
               .summary { 
                 margin-top: 12px; 
                 padding: 8px 0; 
                 border-top: 3px solid #000;
                 border-bottom: 2px solid #000;
                 font-weight: bold;
                 background-color: #f5f5f5;
               }
               .summary-row { 
                 display: flex; 
                 justify-content: space-between; 
                 margin: 4px 0;
                 font-size: 12px;
                 padding: 2px 0;
               }
               .summary-title {
                 font-size: 14px;
                 text-align: center;
                 margin-bottom: 6px;
                 font-weight: bold;
                 text-transform: uppercase;
               }
               .footer { 
                 text-align: center; 
                 margin-top: 12px; 
                 font-size: 10px;
                 border-top: 2px solid #000;
                 padding-top: 8px;
                 font-weight: bold;
               }
               .center { text-align: center; }
               .right { text-align: right; }
               .bold { font-weight: bold; }
               .amount { 
                 font-weight: bold; 
                 font-size: 12px;
               }
             </style>
           </head>
           <body>
             <div class="header">
               <div class="company-name"><?= $this->session->userdata('store_name'); ?></div>
               <div class="report-title">BILLWISE REPORT</div>
               <div class="filters">
                 From: ${$("#from_date").val()}<br>
                 To: ${$("#to_date").val()}
               </div>
             </div>`;
           
           var totalAmount = 0, totalPaid = 0, totalDue = 0, totalProfit = 0;
           var billCount = 0;
           
           // Calculate column indices dynamically for 3-inch print
           var headerCells = $("#report-data thead tr th");
           var salesCodeCol = -1, dateCol = -1, refNoCol = -1, customerCol = -1;
           var grandTotalCol = -1, paidAmountCol = -1, dueAmountCol = -1, profitCol = -1;
           
           headerCells.each(function(index){
             var headerText = $(this).text().trim().toLowerCase();
             if(headerText.includes('sales') && headerText.includes('code')){
               salesCodeCol = index;
             } else if(headerText.includes('date')){
               dateCol = index;
             } else if(headerText.includes('reference')){
               refNoCol = index;
             } else if(headerText.includes('customer') && headerText.includes('name')){
               customerCol = index;
             } else if(headerText.includes('grand') && headerText.includes('total')){
               grandTotalCol = index;
             } else if(headerText.includes('paid') && headerText.includes('amount')){
               paidAmountCol = index;
             } else if(headerText.includes('due') && headerText.includes('amount')){
               dueAmountCol = index;
             } else if(headerText.includes('profit')){
               profitCol = index;
             }
           });
           
           $("#tbody_data tr").each(function(){
             var $row = $(this);
             if(!$row.hasClass('bg-gray')){
               var cells = $row.find('td');
               if(cells.length > 0){
                 billCount++;
                 var billCode = (salesCodeCol >= 0) ? (cells.eq(salesCodeCol).find('a').text() || cells.eq(salesCodeCol).text()) : '';
                 var date = (dateCol >= 0) ? cells.eq(dateCol).text() : '';
                 var refNo = (refNoCol >= 0) ? cells.eq(refNoCol).text() : '';
                 var customer = (customerCol >= 0) ? cells.eq(customerCol).text() : '';
                 var total = (grandTotalCol >= 0) ? cells.eq(grandTotalCol).text() : '';
                 var paid = (paidAmountCol >= 0) ? cells.eq(paidAmountCol).text() : '';
                 var due = (dueAmountCol >= 0) ? cells.eq(dueAmountCol).text() : '';
                 var profit = (profitCol >= 0) ? cells.eq(profitCol).text() : '';
                 
                 // Clean and parse numbers for totals
                 var totalNum = parseFloat(total.replace(/[^\d.-]/g, '')) || 0;
                 var paidNum = parseFloat(paid.replace(/[^\d.-]/g, '')) || 0;
                 var dueNum = parseFloat(due.replace(/[^\d.-]/g, '')) || 0;
                 var profitNum = parseFloat(profit.replace(/[^\d.-]/g, '')) || 0;
                 
                 totalAmount += totalNum;
                 totalPaid += paidNum;
                 totalDue += dueNum;
                 totalProfit += profitNum;
                 
                 print_content += `
                 <div class="bill-item">
                   <div class="bill-header">${billCode} - ${date}</div>
                   ${refNo !== '-' && refNo !== '' ? '<div class="bill-row"><span class="bill-label">REF:</span><span class="bill-value amount">' + refNo + '</span></div>' : ''}
                   <div class="bill-row"><span class="bill-label">CUSTOMER:</span><span class="bill-value">${customer}</span></div>
                   <div class="bill-row"><span class="bill-label">TOTAL:</span><span class="bill-value amount">${total}</span></div>
                   <div class="bill-row"><span class="bill-label">PAID:</span><span class="bill-value amount">${paid}</span></div>
                   <div class="bill-row"><span class="bill-label">DUE:</span><span class="bill-value amount">${due}</span></div>
                   <div class="bill-row"><span class="bill-label">PROFIT:</span><span class="bill-value amount">${profit}</span></div>
                 </div>`;
               }
             }
           });
           
           print_content += `
             <div class="summary">
               <div class="summary-title">SUMMARY (${billCount} Bills)</div>
               <div class="summary-row"><span>TOTAL SALES:</span><span class="amount">${totalAmount.toFixed(2)}</span></div>
               <div class="summary-row"><span>TOTAL PAID:</span><span class="amount">${totalPaid.toFixed(2)}</span></div>
               <div class="summary-row"><span>TOTAL DUE:</span><span class="amount">${totalDue.toFixed(2)}</span></div>
               <div class="summary-row"><span>TOTAL PROFIT:</span><span class="amount">${totalProfit.toFixed(2)}</span></div>
             </div>
             
             <div class="footer">
               <div>PRINTED: ${new Date().toLocaleString()}</div>
               <div>THANK YOU!</div>
             </div>
           </body>
           </html>`;
           
           print_window.document.write(print_content);
           print_window.document.close();
           print_window.print();
           print_window.close();
         });

         // Regular A4 print
         $(".print_it1").click(function(){
           if($("#tbody_data tr").length == 0){
             toastr["error"]("Please generate report first");
             return;
           }
           
           var print_window = window.open('', '_blank');
           
           var print_content = `
           <html>
           <head>
             <title>Billwise Report - A4 Print</title>
             <style>
               @page { 
                 size: A4; 
                 margin: 15mm; 
               }
               body { 
                 font-family: 'Arial', 'Helvetica', sans-serif; 
                 font-size: 11px; 
                 margin: 0; 
                 padding: 0;
                 line-height: 1.4;
                 color: #333;
               }
               .header { 
                 text-align: center; 
                 margin-bottom: 20px; 
                 border-bottom: 2px solid #000;
                 padding-bottom: 15px;
               }
               .company-name { 
                 font-size: 24px; 
                 font-weight: bold; 
                 margin-bottom: 5px;
                 color: #2c3e50;
               }
               .report-title { 
                 font-size: 18px; 
                 margin: 8px 0; 
                 font-weight: bold;
                 color: #34495e;
               }
               .filters { 
                 font-size: 12px; 
                 margin-bottom: 10px; 
                 color: #7f8c8d;
               }
               .report-info {
                 display: flex;
                 justify-content: space-between;
                 margin-bottom: 15px;
                 font-size: 10px;
                 color: #95a5a6;
               }
               table { 
                 width: 100%; 
                 border-collapse: collapse; 
                 margin-bottom: 20px;
                 font-size: 10px;
               }
               th { 
                 background-color: #34495e; 
                 color: white; 
                 padding: 8px 5px; 
                 text-align: left;
                 font-weight: bold;
                 border: 1px solid #2c3e50;
               }
               td { 
                 padding: 6px 5px; 
                 border: 1px solid #bdc3c7;
                 vertical-align: top;
               }
               tr:nth-child(even) { 
                 background-color: #f8f9fa; 
               }
               tr:hover { 
                 background-color: #e8f4f8; 
               }
               .text-right { 
                 text-align: right; 
               }
               .text-center { 
                 text-align: center; 
               }
               .total-row { 
                 font-weight: bold; 
                 background-color: #ecf0f1 !important;
                 border-top: 2px solid #34495e;
               }
               .total-row td {
                 font-weight: bold;
                 background-color: #ecf0f1;
                 border: 1px solid #34495e;
               }
               .summary-section {
                 margin-top: 20px;
                 padding: 15px;
                 background-color: #f8f9fa;
                 border: 2px solid #34495e;
                 border-radius: 5px;
               }
               .summary-title {
                 font-size: 16px;
                 font-weight: bold;
                 text-align: center;
                 margin-bottom: 10px;
                 color: #2c3e50;
               }
               .summary-grid {
                 display: grid;
                 grid-template-columns: 1fr 1fr;
                 gap: 10px;
                 margin-top: 10px;
               }
               .summary-item {
                 display: flex;
                 justify-content: space-between;
                 padding: 5px;
                 background-color: white;
                 border-radius: 3px;
                 border: 1px solid #bdc3c7;
               }
               .summary-label {
                 font-weight: bold;
                 color: #34495e;
               }
               .summary-value {
                 font-weight: bold;
                 color: #27ae60;
               }
               .footer { 
                 margin-top: 30px;
                 text-align: center; 
                 font-size: 10px;
                 color: #7f8c8d;
                 border-top: 1px solid #bdc3c7;
                 padding-top: 10px;
               }
               .page-break { 
                 page-break-before: always; 
               }
               .no-print { 
                 display: none; 
               }
               @media print {
                 .no-print { display: none !important; }
                 body { font-size: 10px; }
               }
             </style>
           </head>
           <body>
             <div class="header">
               <div class="company-name"><?= $this->session->userdata('store_name'); ?></div>
               <div class="report-title">Billwise Report</div>
               <div class="filters">
                 Report Period: ${$("#from_date").val()} to ${$("#to_date").val()}
                 ${$("#customer_id option:selected").text() !== '-All Customers-' ? '<br>Customer: ' + $("#customer_id option:selected").text() : ''}
                 ${$("#reference_no").val() ? '<br>Reference: ' + $("#reference_no").val() : ''}
               </div>
             </div>
             
             <div class="report-info">
               <div>Generated: ${new Date().toLocaleString()}</div>
               <div>User: <?= $this->session->userdata('inv_username'); ?></div>
             </div>`;
           
           // Create table with all data
           print_content += '<table>';
           print_content += '<thead><tr>';
           
           // Add headers dynamically based on visible columns
           $("#report-data thead tr th").each(function(index){
             var headerText = $(this).text().trim();
             if(headerText) {
               print_content += '<th>' + headerText + '</th>';
             }
           });
           
           print_content += '</tr></thead><tbody>';
           
           var totalAmount = 0, totalPaid = 0, totalDue = 0, totalProfit = 0;
           var billCount = 0;
           
           // Calculate column indices dynamically
           var headerCells = $("#report-data thead tr th");
           var grandTotalCol = -1, paidAmountCol = -1, dueAmountCol = -1, profitCol = -1;
           
           headerCells.each(function(index){
             var headerText = $(this).text().trim().toLowerCase();
             if(headerText.includes('grand') && headerText.includes('total')){
               grandTotalCol = index;
             } else if(headerText.includes('paid') && headerText.includes('amount')){
               paidAmountCol = index;
             } else if(headerText.includes('due') && headerText.includes('amount')){
               dueAmountCol = index;
             } else if(headerText.includes('profit')){
               profitCol = index;
             }
           });
           
           $("#tbody_data tr").each(function(){
             var $row = $(this);
             if($row.hasClass('bg-gray')){
               // Total row
               print_content += '<tr class="total-row">';
               $row.find('td').each(function(){
                 print_content += '<td>' + $(this).text() + '</td>';
               });
               print_content += '</tr>';
             } else {
               var cells = $row.find('td');
               if(cells.length > 0){
                 billCount++;
                 print_content += '<tr>';
                 cells.each(function(){
                   var cellText = $(this).text();
                   var hasLink = $(this).find('a').length > 0;
                   if(hasLink) {
                     cellText = $(this).find('a').text();
                   }
                   print_content += '<td>' + cellText + '</td>';
                 });
                 print_content += '</tr>';
                 
                 // Calculate totals using dynamic column indices
                 if(grandTotalCol >= 0) {
                   var total = parseFloat(cells.eq(grandTotalCol).text().replace(/[^\d.-]/g, '')) || 0;
                   totalAmount += total;
                 }
                 if(paidAmountCol >= 0) {
                   var paid = parseFloat(cells.eq(paidAmountCol).text().replace(/[^\d.-]/g, '')) || 0;
                   totalPaid += paid;
                 }
                 if(dueAmountCol >= 0) {
                   var due = parseFloat(cells.eq(dueAmountCol).text().replace(/[^\d.-]/g, '')) || 0;
                   totalDue += due;
                 }
                 if(profitCol >= 0) {
                   var profit = parseFloat(cells.eq(profitCol).text().replace(/[^\d.-]/g, '')) || 0;
                   totalProfit += profit;
                 }
               }
             }
           });
           
           print_content += '</tbody></table>';
           
           // Add summary section
           print_content += `
             <div class="summary-section">
               <div class="summary-title">Report Summary</div>
               <div class="summary-grid">
                 <div class="summary-item">
                   <span class="summary-label">Total Bills:</span>
                   <span class="summary-value">${billCount}</span>
                 </div>
                 <div class="summary-item">
                   <span class="summary-label">Total Sales:</span>
                   <span class="summary-value">${totalAmount.toFixed(2)}</span>
                 </div>
                 <div class="summary-item">
                   <span class="summary-label">Total Paid:</span>
                   <span class="summary-value">${totalPaid.toFixed(2)}</span>
                 </div>
                 <div class="summary-item">
                   <span class="summary-label">Total Due:</span>
                   <span class="summary-value">${totalDue.toFixed(2)}</span>
                 </div>
                 <div class="summary-item">
                   <span class="summary-label">Total Profit:</span>
                   <span class="summary-value">${totalProfit.toFixed(2)}</span>
                 </div>
                 <div class="summary-item">
                   <span class="summary-label">Profit Margin:</span>
                   <span class="summary-value">${totalAmount > 0 ? ((totalProfit/totalAmount)*100).toFixed(2) + '%' : '0%'}</span>
                 </div>
               </div>
             </div>
             
             <div class="footer">
               <div>This report was generated automatically by the billing system</div>
               <div>© <?= date('Y'); ?> <?= $this->session->userdata('store_name'); ?> - All rights reserved</div>
             </div>
           </body>
           </html>`;
           
           print_window.document.write(print_content);
           print_window.document.close();
           print_window.print();
           print_window.close();
         });

         // CSV Export functionality
         $("#export_csv").click(function(){
           if($("#tbody_data tr").length == 0){
             toastr["error"]("Please generate report first");
             return;
           }
           
           var csv_data = [];
           var headers = [];
           
           // Get headers
           $("#report-data thead tr th").each(function(){
             var headerText = $(this).text().trim();
             if(headerText) {
               headers.push('"' + headerText.replace(/"/g, '""') + '"');
             }
           });
           csv_data.push(headers.join(','));
           
           // Get data rows
           $("#tbody_data tr").each(function(){
             var $row = $(this);
             if(!$row.hasClass('bg-gray')){ // Skip total rows
               var row_data = [];
               $row.find('td').each(function(){
                 var cellText = $(this).text().trim();
                 var hasLink = $(this).find('a').length > 0;
                 if(hasLink) {
                   cellText = $(this).find('a').text().trim();
                 }
                 // Escape quotes and wrap in quotes
                 cellText = cellText.replace(/"/g, '""');
                 row_data.push('"' + cellText + '"');
               });
               if(row_data.length > 0) {
                 csv_data.push(row_data.join(','));
               }
             }
           });
           
           // Create CSV content
           var csv_content = csv_data.join('\n');
           
           // Add BOM for proper Excel encoding
           var bom = '\uFEFF';
           var csv_blob = new Blob([bom + csv_content], { type: 'text/csv;charset=utf-8;' });
           
           // Create download link
           var link = document.createElement('a');
           var url = URL.createObjectURL(csv_blob);
           link.setAttribute('href', url);
           
           // Generate filename with date range
           var from_date = $("#from_date").val().replace(/\//g, '-');
           var to_date = $("#to_date").val().replace(/\//g, '-');
           var filename = 'Billwise_Report_' + from_date + '_to_' + to_date + '.csv';
           link.setAttribute('download', filename);
           
           // Trigger download
           link.style.visibility = 'hidden';
           document.body.appendChild(link);
           link.click();
           document.body.removeChild(link);
           
           toastr["success"]("CSV file downloaded successfully");
         });
      </script>
   </body>
</html>
