<?php
// Get store information for print functions
$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 : 'NCS Billing Book';
}

// Debug logging
log_message('debug', 'Store Name: ' . $store_name);
log_message('debug', 'Store Details: ' . json_encode($store));

$store_address = isset($store->address) ? $store->address : "123 Main Street, New York, NY 10001";
$store_phone = isset($store->mobile) ? "Phone: " . $store->mobile : "Phone: 9999999999";
$store_email = isset($store->email) ? "Email: " . $store->email : "Email: billingbook@email.com";
?>
<!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>

    <!-- /.content -->
    <section class="content">
      <div class="row">
        <div class="col-md-12">
                     <!-- Horizontal Form -->
                     <div class="box box-info ">
                        <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();?>">
                           <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(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 -->

                                </div>

                              <div class="form-group">
                                 <label for="brand_id" class="col-sm-2 control-label"><?= $this->lang->line('brand'); ?></label>
                                 <div class="col-sm-3">
                                    <select class="form-control select2 " id="brand_id" name="brand_id"  style="width: 100%;">
                                       <option value="">-Select-</option>
                                       <?= get_brands_select_list();  ?>
                                    </select>
                                    <span id="brand_id_msg" style="display:none" class="text-danger"></span>
                                 </div>

                                 <label for="category_id" class="col-sm-2 control-label"><?= $this->lang->line('category'); ?></label>
                                 <div class="col-sm-3">
                                    <select class="form-control select2 " id="category_id" name="category_id"  style="width: 100%;">
                                       <option value="">-Select-</option>
                                      <?= get_categories_select_list();  ?>
                                    </select>
                                    <span id="category_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">From Date</label>
                                 <div class="col-sm-3">
                                    <input type="text" class="form-control datepicker" id="from_date" name="from_date" placeholder="From Date" value="">
                                    <span id="from_date_msg" style="display:none" class="text-danger"></span>
                                 </div>

                                 <label for="to_date" class="col-sm-2 control-label">To Date</label>
                                 <div class="col-sm-3">
                                    <input type="text" class="form-control datepicker" id="to_date" name="to_date" placeholder="To Date" value="">
                                    <span id="to_date_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-2 col-md-offset-2">
                                    <button type="button" id="view" class=" btn btn-block btn-success" title="Save Data">Show</button>
                                 </div>
                                 <div class="col-sm-2">
                                    <button type="button" class="btn btn-block btn-info" onclick="printStockReport()" title="Print Report">
                                       <i class="fa fa-print"></i> Print A4
                                    </button>
                                 </div>
                                 <div class="col-sm-2">
                                    <a href="<?=base_url('dashboard');?>">
                                    <button type="button" class="btn btn-block btn-warning close_btn" title="Go Dashboard">Close</button>
                                    </a>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-footer -->
                        </form>
                     </div>
                     <!-- /.box -->
                  </div>

                  <div class="col-md-12">
                     <!-- Custom Tabs -->
                     <div class="nav-tabs-custom">
                       
                        <ul class="nav nav-tabs">
                           <li class="active"><a href="#tab_1" data-toggle="tab"><?= $this->lang->line('item_wise'); ?></a></li>
                           <li><a href="#tab_2" data-toggle="tab"><?= $this->lang->line('brand_wise'); ?></a></li>
                           <li><a href="#tab_3" data-toggle="tab">Stock Aging</a></li>
                           <li><a href="#tab_4" data-toggle="tab">Most Moving</a></li>
                           <li><a href="#tab_5" data-toggle="tab">Less Moving</a></li>
                           <li><a href="#tab_6" data-toggle="tab"><i class="fa fa-exclamation-triangle text-warning"></i> Low Stock Alert</a></li>
                        </ul>
                        <div class="tab-content">
                           <div class="tab-pane active" id="tab_1">
                            
                              <div class="row">
                                 <!-- right column -->
                                 <div class="col-md-12">
                                    <!-- form start -->
                                       <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                                          <?php $this->load->view('components/export_btn',array('tableId' => 'report-data'));?>
                                          <br><br>
                                          <div class="table-responsive">
                                          <table class="table table-bordered table-hover table-striped" id="report-data" style="width:100%;">
                                            <thead>
                                            <tr class="bg-blue" style="background-color:#3c8dbc !important; color:#fff;">
                                              <th style="text-align:center; width:3%;">#</th>
                                              <?php if(store_module() && is_admin()){ ?>
                                              <th style="text-align:left; width:8%;"><?= $this->lang->line('store_name'); ?></th>
                                              <?php } ?>
                                              <th style="text-align:left; width:8%;"><?= $this->lang->line('item_code'); ?></th>
                                              <th style="text-align:left; width:12%;"><?= $this->lang->line('item_name'); ?></th>
                                              <th style="text-align:left; width:8%;"><?= $this->lang->line('brand'); ?></th>
                                              <th style="text-align:left; width:8%;"><?= $this->lang->line('category'); ?></th>
                                              <th style="text-align:right; width:7%;"><?= $this->lang->line('unit_price'); ?></th>
                                              <th style="text-align:center; width:8%;"><?= $this->lang->line('tax'); ?></th>
                                              <th style="text-align:right; width:7%;"><?= $this->lang->line('purchase_cost'); ?></th>
                                              <th style="text-align:right; width:7%;"><?= $this->lang->line('sales_price'); ?></th>
                                              <th style="text-align:center; width:8%;">Main Unit</th>
                                              <th style="text-align:center; width:8%;">Alternate Unit</th>
                                              <th style="text-align:right; width:8%;">
                                                <?= $this->lang->line('stock_value'); ?>
                                                <br>
                                                <small style="font-size:10px;">(<?= $this->lang->line('by_sale_price');?>)</small>
                                              </th>
                                              <th style="text-align:right; width:8%;">
                                                <?= $this->lang->line('stock_value'); ?>
                                                <br>
                                                <small style="font-size:10px;">(<?= $this->lang->line('by_purchase_price');?>)</small>
                                              </th>
                                            </tr>
                                            </thead>
                                            <tbody id="tbodyid">
                                            
                                          </tbody>
                                          </table>
                                          </div>
                                       <!-- /.box-body -->
                                 </div>
                                 <!--/.col (right) -->
                              </div>
                              <!-- /.row -->
                           </div>
                           <!-- /.tab-pane -->
                          
                           <div class="tab-pane" id="tab_2">
                              <div class="row">
                                 <!-- right column -->
                                 <div class="col-md-12">
                                    <!-- form start -->
                                       <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                                          <?php $this->load->view('components/export_btn',array('tableId' => 'brand_wise_stock'));?>
                                          <br><br>
                                          <div class="table-responsive">
                                          <table class="table table-bordered table-hover " id="brand_wise_stock" >
                                              <thead>
                                              <tr class="bg-blue">
                                                <th style="">#</th>
                                                <?php if(store_module() && is_admin()){ ?>
                                                  <th style=""><?= $this->lang->line('store_name'); ?></th>
                                                  <?php } ?>
                                                <th style=""><?= $this->lang->line('brand_name'); ?></th>
                                                <th style=""><?= $this->lang->line('current_stock'); ?></th>
                                                <th style=""><?= $this->lang->line('stock_value'); ?></th>
                                              </tr>
                                              </thead>
                                              <tbody id="brand_wise_tbody">
                                              
                                              </tbody>
                                            </table>
                                          </div>
                                       <!-- /.box-body -->
                                 </div>
                                 <!--/.col (right) -->
                              </div>
                              <!-- /.row -->
                           </div>
                           <!-- /.tab-pane -->

                           <!-- Stock Aging Tab -->
                           <div class="tab-pane" id="tab_3">
                              <div class="row">
                                 <div class="col-md-12">
                                    <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                                    <?php $this->load->view('components/export_btn',array('tableId' => 'stock_aging'));?>
                                    <br><br>
                                    <div class="table-responsive">
                                       <table class="table table-bordered table-hover" id="stock_aging">
                                          <thead>
                                             <tr class="bg-blue">
                                                <th>#</th>
                                                <?php if(store_module() && is_admin()){ ?>
                                                   <th><?= $this->lang->line('store_name'); ?></th>
                                                <?php } ?>
                                                <th>Item Code</th>
                                                <th>Item Name</th>
                                                <th>Brand</th>
                                                <th>Category</th>
                                                <th>Current Stock</th>
                                                <th>Days in Stock</th>
                                                <th>Age Category</th>
                                                <th>Stock Value</th>
                                             </tr>
                                          </thead>
                                          <tbody id="stock_aging_tbody">
                                          </tbody>
                                       </table>
                                    </div>
                                 </div>
                              </div>
                           </div>
                           <!-- /.tab-pane -->

                           <!-- Most Moving Tab -->
                           <div class="tab-pane" id="tab_4">
                              <div class="row">
                                 <div class="col-md-12">
                                    <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                                    <?php $this->load->view('components/export_btn',array('tableId' => 'most_moving'));?>
                                    <br><br>
                                    <div class="table-responsive">
                                       <table class="table table-bordered table-hover" id="most_moving">
                                          <thead>
                                             <tr class="bg-blue">
                                                <th>#</th>
                                                <?php if(store_module() && is_admin()){ ?>
                                                   <th><?= $this->lang->line('store_name'); ?></th>
                                                <?php } ?>
                                                <th>Item Code</th>
                                                <th>Item Name</th>
                                                <th>Brand</th>
                                                <th>Category</th>
                                                <th>Quantity Sold</th>
                                                <th>Sales Value</th>
                                                <th>Movement Rate</th>
                                                <th>Days to Sell Out</th>
                                             </tr>
                                          </thead>
                                          <tbody id="most_moving_tbody">
                                          </tbody>
                                       </table>
                                    </div>
                                 </div>
                              </div>
                           </div>
                           <!-- /.tab-pane -->

                           <!-- Less Moving Tab -->
                           <div class="tab-pane" id="tab_5">
                              <div class="row">
                                 <div class="col-md-12">
                                    <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                                    <?php $this->load->view('components/export_btn',array('tableId' => 'less_moving'));?>
                                    <br><br>
                                    <div class="table-responsive">
                                       <table class="table table-bordered table-hover" id="less_moving">
                                          <thead>
                                             <tr class="bg-blue">
                                                <th>#</th>
                                                <?php if(store_module() && is_admin()){ ?>
                                                   <th><?= $this->lang->line('store_name'); ?></th>
                                                <?php } ?>
                                                <th>Item Code</th>
                                                <th>Item Name</th>
                                                <th>Brand</th>
                                                <th>Category</th>
                                                <th>Current Stock</th>
                                                <th>Last Sale Date</th>
                                                <th>Days Since Last Sale</th>
                                                <th>Stock Value</th>
                                             </tr>
                                          </thead>
                                          <tbody id="less_moving_tbody">
                                          </tbody>
                                       </table>
                                    </div>
                                 </div>
                              </div>
                           </div>
                           <!-- /.tab-pane -->

                           <!-- Low Stock Alert Tab -->
                           <div class="tab-pane" id="tab_6">
                              <div class="row">
                                 <div class="col-md-12">
                                    <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                                    <?php $this->load->view('components/export_btn',array('tableId' => 'low_stock_alert'));?>
                                    <br><br>
                                    <div class="alert alert-warning">
                                       <i class="fa fa-exclamation-triangle"></i>
                                       <strong>Low Stock Alert:</strong> Items below minimum stock levels are highlighted below. Consider reordering these items.
                                    </div>
                                    <div class="table-responsive">
                                       <table class="table table-bordered table-hover" id="low_stock_alert">
                                          <thead>
                                             <tr class="bg-warning">
                                                <th>#</th>
                                                <?php if(store_module() && is_admin()){ ?>
                                                   <th><?= $this->lang->line('store_name'); ?></th>
                                                <?php } ?>
                                                <th>Item Code</th>
                                                <th>Item Name</th>
                                                <th>Brand</th>
                                                <th>Category</th>
                                                <th>Current Stock</th>
                                                <th>Minimum Stock</th>
                                                <th>Stock Status</th>
                                                <th>Stock Value</th>
                                                <th>Days to Run Out</th>
                                                <th class="no-print">Actions</th>
                                             </tr>
                                          </thead>
                                          <tbody id="low_stock_alert_tbody">
                                          </tbody>
                                       </table>
                                    </div>
                                 </div>
                              </div>
                           </div>
                           <!-- /.tab-pane -->
                      
                        </div>
                        <!-- /.tab-content -->
                     </div>
                     <!-- nav-tabs-custom -->
                  </div>
                  <!-- /.col -->
     
      
      </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"; ?>

<!-- Table Alignment CSS -->
<style>
#report-data {
    font-size: 12px;
}
#report-data thead th {
    white-space: nowrap;
    vertical-align: middle;
}
#report-data tbody td {
    vertical-align: middle;
}
#report-data .text-right {
    text-align: right !important;
}
#report-data .text-center {
    text-align: center !important;
}
#report-data .text-left {
    text-align: left !important;
}
</style>

<!-- Print-specific CSS -->
<style>
@media print {
    body {
        margin: 0;
        padding: 20px;
        font-family: Arial, sans-serif;
        font-size: 12px;
        line-height: 1.4;
        color: #000;
        background: white;
    }
    
    .no-print {
        display: none !important;
    }
    
    .btn-group, .btn {
        display: none !important;
    }
    
    .print-header {
        text-align: center;
        margin-bottom: 30px;
        border-bottom: 2px solid #000;
        padding-bottom: 20px;
    }
    
    .print-header h1 {
        font-size: 24px;
        font-weight: bold;
        margin: 0 0 10px 0;
        color: #000;
    }
    
    .print-header .company-info {
        font-size: 14px;
        color: #000;
        font-weight: bold;
        margin: 5px 0;
    }
    
    .print-header .report-title {
        font-size: 18px;
        font-weight: bold;
        margin: 15px 0 10px 0;
        color: #000;
    }
    
    .print-header .report-period {
        font-size: 12px;
        color: #000;
        font-weight: bold;
        margin: 5px 0;
    }
    
    .print-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }
    
    .print-table th {
        background-color: #d0d0d0 !important;
        color: #000 !important;
        font-weight: bold;
        padding: 8px 6px;
        text-align: center;
        border: 1px solid #000;
        font-size: 11px;
    }
    
    .print-table td {
        padding: 6px;
        border: 1px solid #000;
        font-size: 11px;
        vertical-align: top;
        color: #000;
        font-weight: bold;
    }
    
    .print-table tr:nth-child(even) {
        background-color: #f8f9fa;
    }
    
    .print-table .text-right {
        text-align: right;
    }
    
    .print-table .text-center {
        text-align: center;
    }
    
    .print-table .text-left {
        text-align: left;
    }
    
    .print-footer {
        margin-top: 30px;
        text-align: center;
        font-size: 10px;
        color: #000;
        font-weight: bold;
        border-top: 1px solid #000;
        padding-top: 10px;
    }
    
    .print-table th, .print-table td, .print-table * { color: #000 !important; font-weight: bold !important; }
    
    .page-break {
        page-break-before: always;
    }
    
    @page {
        margin: 1cm;
        size: A4;
    }
}
</style>

      <!-- TABLE EXPORT CODE -->
      <?php include"comman/code_js_export.php"; ?>

<script src="<?php echo $theme_link; ?>js/sheetjs.js" type="text/javascript"></script>

<script type="text/javascript">
  var base_url=$("#base_url").val();
  
  // Professional A4 Print Function for Stock Report
  function printStockReport() {
      // Check if report data exists
      if (!$('#tbodyid').html() || $('#tbodyid').html().trim() === '') {
          alert('Please generate the stock report first before printing.');
          return;
      }
      
      // Create print window
      var printWindow = window.open('', '_blank', 'width=800,height=600');
      
      // Get company information dynamically
     var companyName = <?php echo json_encode(get_store_name(get_current_store_id())); ?>;
     var storeDetails = <?php echo json_encode(get_store_details(get_current_store_id())); ?>;

     var companyAddress = storeDetails ? storeDetails.address : "";
     var companyPhone   = storeDetails ? storeDetails.mobile : "";
     var companyEmail   = storeDetails ? storeDetails.email : "";
      
      // 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 brandName = $('#brand_id option:selected').text() || 'All Brands';
      var categoryName = $('#category_id option:selected').text() || 'All Categories';
      var fromDate = $('#from_date').val() || 'All Time';
      var toDate = $('#to_date').val() || 'All Time';
      
      // Determine active tab
      var activeTab = 'Item Wise Stock';
      if ($('#tab_2').hasClass('active')) {
          activeTab = 'Brand Wise Stock';
      } else if ($('#tab_3').hasClass('active')) {
          activeTab = 'Stock Aging Report';
      } else if ($('#tab_4').hasClass('active')) {
          activeTab = 'Most Moving Stock';
      } else if ($('#tab_5').hasClass('active')) {
          activeTab = 'Less Moving Stock';
      } else if ($('#tab_6').hasClass('active')) {
          activeTab = 'Low Stock Alert';
      }
      
      // Get table data based on active tab
      var tableData = '';
      var tableHeaders = '';
      
      if (activeTab === 'Item Wise Stock') {
          tableHeaders = $('#report-data thead').html();
          tableData = $('#tbodyid').html();
      } else if (activeTab === 'Brand Wise Stock') {
          tableHeaders = $('#brand_wise_stock thead').html();
          tableData = $('#brand_wise_tbody').html();
      } else if (activeTab === 'Stock Aging Report') {
          tableHeaders = $('#stock_aging thead').html();
          tableData = $('#stock_aging_tbody').html();
      } else if (activeTab === 'Most Moving Stock') {
          tableHeaders = $('#most_moving thead').html();
          tableData = $('#most_moving_tbody').html();
      } else if (activeTab === 'Less Moving Stock') {
          tableHeaders = $('#less_moving thead').html();
          tableData = $('#less_moving_tbody').html();
      } else if (activeTab === 'Low Stock Alert') {
          tableHeaders = $('#low_stock_alert thead').html();
          tableData = $('#low_stock_alert_tbody').html();
      }
      
      // Build print content
      var printContent = `
          <!DOCTYPE html>
          <html>
          <head>
              <title>Stock Report - ${activeTab}</title>
              <style>
                  body { font-family: Arial, sans-serif; font-size: 12px; margin: 0; padding: 20px; }
                  .print-header { text-align: center; margin-bottom: 30px; border-bottom: 2px solid #000; padding-bottom: 20px; }
                  .print-header h1 { font-size: 24px; font-weight: bold; margin: 0 0 10px 0; color: #000; }
                  .print-header .company-info { font-size: 14px; color: #000; font-weight: bold; margin: 5px 0; }
                  .print-header .report-title { font-size: 18px; font-weight: bold; margin: 15px 0 10px 0; color: #000; }
                  .print-header .report-filters { font-size: 12px; color: #000; font-weight: bold; margin: 5px 0; }
                  .print-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                  .print-table th { background-color: #d0d0d0; color: #000; font-weight: bold; padding: 8px 6px; text-align: center; border: 1px solid #000; font-size: 11px; }
                  .print-table td { padding: 6px; border: 1px solid #000; font-size: 11px; vertical-align: top; color: #000; font-weight: bold; }
                  .print-table tr:nth-child(even) { background-color: #f8f9fa; }
                  .print-table .text-right { text-align: right; }
                  .print-table .text-center { text-align: center; }
                  .print-table .text-left { text-align: left; }
                  .print-footer { margin-top: 30px; text-align: center; font-size: 10px; color: #000; font-weight: bold; border-top: 1px solid #000; padding-top: 10px; }
                  .print-table th, .print-table td, .print-table * { color: #000 !important; font-weight: bold !important; }
                  @page { margin: 1cm; size: A4; }
              </style>
          </head>
          <body>
              <div class="print-header">
                  <h1>${companyName}</h1>
                  <div class="company-info">${companyAddress}</div>
                  <div class="company-info">${companyPhone}</div>
                  <div class="company-info">${companyEmail}</div>
                  <div class="report-title">Stock Report - ${activeTab}</div>
                  <div class="report-filters"><strong>Store:</strong> ${storeName}</div>
                  <div class="report-filters"><strong>Warehouse:</strong> ${warehouseName}</div>
                  <div class="report-filters"><strong>Brand:</strong> ${brandName}</div>
                  <div class="report-filters"><strong>Category:</strong> ${categoryName}</div>
                  <div class="report-filters"><strong>Period:</strong> ${fromDate} to ${toDate}</div>
                  <div class="report-filters"><strong>Generated:</strong> ${currentDate}</div>
              </div>
              
              <table class="print-table">
                  <thead>
                      ${tableHeaders}
                  </thead>
                  <tbody>
                      ${tableData}
                  </tbody>
              </table>
              
              <div class="print-footer">
                  <p>This report was generated on ${currentDate} by ${companyName} System</p>
                  <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();
          printWindow.print();
          printWindow.close();
      };
  }

</script>
<script type="text/javascript">
  function load_reports(){
   var store_id=$("#store_id").val();
   var brand_id=$("#brand_id").val();
   var category_id=$("#category_id").val();
   var warehouse_id=$("#warehouse_id").val();
   var from_date=$("#from_date").val();
   var to_date=$("#to_date").val();
   
   // Show loading overlay
   $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
   
   $.post(base_url+"reports/get_stock_report",{
     warehouse_id:warehouse_id,
     store_id:store_id,
     brand_id:brand_id,
     category_id:category_id,
     from_date:from_date,
     to_date:to_date
   })
   .done(function(result){
     try {
       if (result == null || (typeof result === 'string' && result.trim() === '')) {
         throw new Error('Empty response');
       }
       if (typeof result === 'string' && result.trim().indexOf('<') === 0) {
         throw new Error('Server returned HTML instead of JSON');
       }
       var data = typeof result === 'object' ? result : $.parseJSON(result);
       
       // Update each report section
       $.each(data, function(key, val) {
         if(key=='item_wise_report'){
           $("#tbodyid").empty().append(val);
         }
         if(key=='brand_wise_stock'){
           $("#brand_wise_tbody").empty().append(val);     
         }
         if(key=='stock_aging_report'){
           $("#stock_aging_tbody").empty().append(val);
         }
         if(key=='most_moving_report'){
           $("#most_moving_tbody").empty().append(val);
         }
         if(key=='less_moving_report'){
           $("#less_moving_tbody").empty().append(val);
         }
         if(key=='low_stock_alert_report'){
           $("#low_stock_alert_tbody").empty().append(val);
         }
       });
     } catch(e) {
       console.error('Error parsing JSON response:', e);
       console.log('Raw response:', result);
       
       // Show error message in all tables (13 columns if not admin, 14 if admin)
       var errorMsg = '<tr><td class="text-center text-danger" colspan="14">Error loading report data. Please try again.</td></tr>';
       $("#tbodyid").empty().append(errorMsg);
       $("#brand_wise_tbody").empty().append('<tr><td class="text-center text-danger" colspan="4">Error loading report data. Please try again.</td></tr>');
       $("#stock_aging_tbody").empty().append('<tr><td class="text-center text-danger" colspan="9">Error loading report data. Please try again.</td></tr>');
       $("#most_moving_tbody").empty().append('<tr><td class="text-center text-danger" colspan="9">Error loading report data. Please try again.</td></tr>');
       $("#less_moving_tbody").empty().append('<tr><td class="text-center text-danger" colspan="9">Error loading report data. Please try again.</td></tr>');
       $("#low_stock_alert_tbody").empty().append('<tr><td class="text-center text-danger" colspan="10">Error loading report data. Please try again.</td></tr>');
     }
   })
   .fail(function(xhr, status, error) {
     console.error('AJAX request failed:', status, error);
     console.log('Response:', xhr.responseText);
     
     // Show error message in all tables (13 columns if not admin, 14 if admin)
     var errorMsg = '<tr><td class="text-center text-danger" colspan="14">Network error: ' + error + '. Please check your connection and try again.</td></tr>';
     $("#tbodyid").empty().append(errorMsg);
     $("#brand_wise_tbody").empty().append('<tr><td class="text-center text-danger" colspan="4">Network error: ' + error + '</td></tr>');
     $("#stock_aging_tbody").empty().append('<tr><td class="text-center text-danger" colspan="9">Network error: ' + error + '</td></tr>');
     $("#most_moving_tbody").empty().append('<tr><td class="text-center text-danger" colspan="9">Network error: ' + error + '</td></tr>');
     $("#less_moving_tbody").empty().append('<tr><td class="text-center text-danger" colspan="9">Network error: ' + error + '</td></tr>');
     $("#low_stock_alert_tbody").empty().append('<tr><td class="text-center text-danger" colspan="10">Network error: ' + error + '</td></tr>');
   })
   .always(function() {
     // Always remove overlay, regardless of success or failure
     $(".overlay").remove();
   });

  }//function end

  // Add missing function to prevent JavaScript errors
  function updateStockAlertSummary() {
    // This function is called but not needed for stock reports
    // It's likely from dashboard functionality
    return;
  }
</script>
<script>
    // Initialize date pickers
    $('.datepicker').datepicker({
        autoclose: true,
        format: 'yyyy-mm-dd'
    });

    $("#view").on("click",function(){
      load_reports();
    });
    $("#store_id,#warehouse_id").on("change",function(){
      load_reports();
    });
</script>
<script type="text/javascript">
        var base_url=$("#base_url").val();
        $("#store_id").on("change",function(){
          var store_id=$(this).val();
          $.post(base_url+"sales/get_customers_select_list",{store_id:store_id},function(result){
              result='<option value="">All</option>'+result;
              $("#customer_id").html('').append(result).select2();

          });
          $.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();

              load_brands_list();
              load_category_list();
          });
        });


    function load_brands_list(){
     var store_id=$("#store_id").val();
     $.post(base_url+"sales/get_brands_select_list",{store_id:store_id},function(result){
          result='<option value="">All</option>'+result;
          $("#brand_id").html('').append(result).select2();
      });
    }

    function load_category_list(){
     var store_id=$("#store_id").val();
     $.post(base_url+"sales/get_categories_select_list",{store_id:store_id},function(result){
          result='<option value="">All</option>'+result;
          $("#category_id").html('').append(result).select2();
      });
    }

      </script>

<!-- Make sidebar menu hughlighter/selector -->
<script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
    
    
</body>
</html>
