<?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';
}

$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();?>">
                           <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(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="item_id" class="col-sm-2 control-label">Item</label>
                                 <div class="col-sm-3">
                                    <select class="form-control select2 " id="item_id" name="item_id"  style="width: 100%;">
                                       <option value="">-All Items-</option>
                                       <?= get_items_select_list('', get_current_store_id(), 'Items');  ?>
                                    </select>
                                    <span id="item_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="<?php echo show_date(date('d-m-Y'));?>">
                                    <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="<?php echo show_date(date('d-m-Y'));?>">
                                    <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="Show Report">Show</button>
                                 </div>
                                 <div class="col-sm-2">
                                    <button type="button" class="btn btn-block btn-info" onclick="printReconciliationReport()" 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">
                        <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 } ?>
                                              <?php if(warehouse_module() && warehouse_count() > 0){ ?>
                                              <th style="text-align:left; width:8%;">Warehouse</th>
                                              <?php } ?>
                                              <th style="text-align:left; width:10%;">Item Code</th>
                                              <th style="text-align:left; width:20%;">Item Name</th>
                                              <th style="text-align:right; width:15%;">Total Purchased</th>
                                              <th style="text-align:right; width:15%;">Total Sold</th>
                                              <th style="text-align:right; width:15%;">Remaining Stock</th>
                                            </tr>
                                            </thead>
                                            <tbody id="tbodyid">
                                            
                                          </tbody>
                                          </table>
                                          </div>
                                       <!-- /.box-body -->
                                 </div>
                                 <!--/.col (right) -->
                              </div>
                              <!-- /.row -->
                           </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;
    text-align: center;
    padding: 10px 8px;
}
#report-data tbody td {
    vertical-align: middle;
    padding: 8px;
}
#report-data tbody td.text-right {
    text-align: right !important;
    padding-right: 15px;
}
#report-data tbody td.text-right small {
    display: block;
    margin-top: 3px;
    font-size: 11px;
    color: #000;
    font-weight: bold;
}
#report-data .text-center {
    text-align: center !important;
}
#report-data .text-left {
    text-align: left !important;
}
#report-data tbody tr.bg-gray,
#report-data tbody tr.total-row {
    background-color: #e8e8e8 !important;
    font-weight: bold;
}
#report-data tbody tr.bg-gray td,
#report-data tbody tr.total-row td {
    border-top: 2px solid #000;
    padding: 10px 8px;
    vertical-align: middle !important;
}
#report-data tbody tr.bg-gray td.total-label,
#report-data tbody tr.total-row td.total-label,
#report-data tbody tr.bg-gray td[colspan],
#report-data tbody tr.total-row td[colspan] {
    text-align: right !important;
    padding-right: 15px !important;
    vertical-align: middle !important;
}
#report-data tbody tr.bg-gray td.total-label span,
#report-data tbody tr.total-row td.total-label span {
    display: inline-block !important;
    text-align: right !important;
    width: 100% !important;
}
#report-data tbody tr.bg-gray td.text-right,
#report-data tbody tr.total-row td.text-right,
#report-data tbody tr.bg-gray td.total-value,
#report-data tbody tr.total-row td.total-value {
    text-align: right !important;
    padding-right: 15px !important;
    vertical-align: middle !important;
}
#report-data tbody tr.bg-gray td.text-right small,
#report-data tbody tr.total-row td.text-right small,
#report-data tbody tr.bg-gray td.total-value small,
#report-data tbody tr.total-row td.total-value small {
    display: block;
    text-align: right !important;
    margin-top: 3px;
    font-size: 11px;
    color: #000;
    font-weight: bold;
}
</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 Reconciliation Report
  function printReconciliationReport() {
      // Check if report data exists
      if (!$('#tbodyid').html() || $('#tbodyid').html().trim() === '') {
          alert('Please generate the reconciliation 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 itemName = $('#item_id option:selected').text() || 'All Items';
      var fromDate = $('#from_date').val() || 'All Time';
      var toDate = $('#to_date').val() || 'All Time';
      
      // Get table data
      var tableHeaders = $('#report-data thead').html();
      var tableData = $('#tbodyid').html();
      
      // Build print content
      var printContent = `
          <!DOCTYPE html>
          <html>
          <head>
              <title>Daily Reconciliation Report</title>
              <style>
                  body { font-family: Arial, sans-serif; font-size: 12px; margin: 0; padding: 20px; color: #000; font-weight: bold; }
                  .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">Daily Reconciliation Report</div>
                  <div class="report-filters"><strong>Store:</strong> ${storeName}</div>
                  <div class="report-filters"><strong>Warehouse:</strong> ${warehouseName}</div>
                  <div class="report-filters"><strong>Item:</strong> ${itemName}</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_reconciliation_report(){
   var store_id=$("#store_id").val();
   var warehouse_id=$("#warehouse_id").val();
   var item_id=$("#item_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/show_daily_reconciliation_report",{
     warehouse_id:warehouse_id,
     store_id:store_id,
     item_id:item_id,
     from_date:from_date,
     to_date:to_date
   })
   .done(function(result){
     try {
       $("#tbodyid").empty().append(result);
     } catch(e) {
       console.error('Error parsing response:', e);
       console.log('Raw response:', result);
       
       // Show error message
       var errorMsg = '<tr><td class="text-center text-danger" colspan="7">Error loading report data. Please try again.</td></tr>';
       $("#tbodyid").empty().append(errorMsg);
     }
   })
   .fail(function(xhr, status, error) {
     console.error('AJAX request failed:', status, error);
     console.log('Response:', xhr.responseText);
     
     // Show error message
     var errorMsg = '<tr><td class="text-center text-danger" colspan="7">Network error: ' + error + '. Please check your connection and try again.</td></tr>';
     $("#tbodyid").empty().append(errorMsg);
   })
   .always(function() {
     // Always remove overlay, regardless of success or failure
     $(".overlay").remove();
   });

  }//function end
</script>
<script>
    // Initialize date pickers
    $('.datepicker').datepicker({
        autoclose: true,
        format: 'yyyy-mm-dd'
    });

    $("#view").on("click",function(){
      load_reconciliation_report();
    });
    $("#store_id,#warehouse_id,#item_id").on("change",function(){
      load_reconciliation_report();
    });
</script>
<script type="text/javascript">
        var base_url=$("#base_url").val();
        $("#store_id").on("change",function(){
          var store_id=$(this).val();
          //Load Items
          $.post(base_url+"sales/get_items_select_list",{store_id:store_id,item_type:'Items'},function(result){
              result='<option value="">-All Items-</option>'+result;
              $("#item_id").html('').append(result).select2();
          });
          
          //Ajax to load warehouses
          $.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();
          });
        });
</script>

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

