<!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="Reference No">
                                    <span id="reference_no_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 <label for="item_id" class="col-sm-2 control-label"><?= $this->lang->line('item_name'); ?></label>
                                 <div class="col-sm-3">
                                    <select class="form-control select2 " id="item_id" name="item_id" >
                                    </select>
                                    <span id="item_id_msg" style="display:none" class="text-danger"></span>
                                 </div>

                              </div>

                              <div class="form-group">
                                 <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" >
                                    </select>
                                    <span id="category_id_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 <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" >
                                    </select>
                                    <span id="brand_id_msg" style="display:none" class="text-danger"></span>
                                 </div>

                              </div>

                              <div class="form-group">
                                 <label for="created_by" class="col-sm-2 control-label">Created By</label>
                                 <div class="col-sm-3">
                                    <select class="form-control select2 " id="created_by" name="created_by" >
                                    </select>
                                    <span id="created_by_msg" style="display:none" class="text-danger"></span>
                                 </div>

                              </div>

                           </div>
                           <!-- /.box-body -->
                           <div class="box-footer">
                              <div class="form-group">
                                 <div class="col-sm-4">
                                    <button type="button" id="view_report" class=" btn btn-block btn-success" title="Save Data">Show</button>
                                 </div>
                                 <div class="col-sm-3">
                                    <button type="button" id="reset-btn" class="col-sm-3 btn btn-block btn-warning close_btn" title="Reset">Reset</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">Categorywise 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('category'); ?></th>
                                    <th>Item Count</th>
                                    <th>Total Qty</th>
                                    <th>Total Amount</th>
                                    <th>Total Tax</th>
                                    <th>Total Discount</th>
                                    <th>Total Profit</th>
                                    <th>Invoice Count</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"; ?>

      <style type="text/css">
         .table>thead>tr>th, .table>tbody>tr>th, .table>tfoot>tr>th, .table>thead>tr>td, .table>tbody>tr>td, .table>tfoot>tr>td{
         border-left: 1px solid #ddd;
         }
         .table-bordered{
         border-left: 1px solid #ddd;
         }
         table.table.table-bordered.table-hover.dataTable.no-footer {
         border-left: 1px solid #ddd;
         border-right: 1px solid #ddd;
         }
         @media only screen and (max-width: 767px) {
         .table-responsive {
         border: none;
         }
         }
      </style>

      <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 } ?>
             
             // Load items list
             get_items_select_list();
             
             // Load categories list  
             get_categories_select_list();
             
             // Load brands list
             get_brands_select_list();
             
             // Load users list
             get_users_select_list();
         });
         
         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');
             }
         }

         function get_items_select_list(item_id=''){
         	$("#item_id").html('<option value="">-All Items-</option>');
         	$.post("<?php echo site_url('items/get_items_select_list')?>",{item_id:item_id},function(result){
               $("#item_id").append(result);
             });
             if(item_id!=''){
             	$('#item_id').val(item_id).trigger('change');
             }
         }

         function get_categories_select_list(category_id=''){
         	$("#category_id").html('<option value="">-All Categories-</option>');
         	$.post("<?php echo site_url('category/get_categories_select_list')?>",{category_id:category_id},function(result){
               $("#category_id").append(result);
             });
             if(category_id!=''){
             	$('#category_id').val(category_id).trigger('change');
             }
         }

         function get_brands_select_list(brand_id=''){
         	$("#brand_id").html('<option value="">-All Brands-</option>');
         	$.post("<?php echo site_url('brand/get_brands_select_list')?>",{brand_id:brand_id},function(result){
               $("#brand_id").append(result);
             });
             if(brand_id!=''){
             	$('#brand_id').val(brand_id).trigger('change');
             }
         }

         function get_users_select_list(user_id=''){
         	$("#created_by").html('<option value="">-All Users-</option>');
         	$.post("<?php echo site_url('users/get_users_select_list')?>",{user_id:user_id},function(result){
               $("#created_by").append(result);
             });
             if(user_id!=''){
             	$('#created_by').val(user_id).trigger('change');
             }
         }
        
         $('#view_report').click(function() {
           if($("#from_date").val()==''){
             toastr["error"]("From Date is Required");
             return;
           }
           if($("#to_date").val()==''){
             toastr["error"]("To Date is Required");
             return;
           }
           
           $("#tbody_data").html('<tr><td colspan="50"><div class="overlay"><i class="fa fa-refresh fa-spin"></i></div></td></tr>');
           
           $.post("<?= $base_url;?>reports/show_categorywise_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() || '',
             item_id: $("#item_id").val() || '',
             category_id: $("#category_id").val() || '',
             brand_id: $("#brand_id").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);
           }).fail(function(xhr, status, error) {
             console.error("Error:", error);
             console.error("Response:", xhr.responseText);
             toastr["error"]("Error loading report: " + error);
             $("#tbody_data").html('<tr><td colspan="50" class="text-center text-danger">Error loading report</td></tr>');
           }); 
         });

         // CSV Export functionality
         $('#export_csv').click(function() {
             var table = document.getElementById('report-data');
             var csv = [];
             var rows = table.querySelectorAll('tr');
             
             for (var i = 0; i < rows.length; i++) {
                 var row = [], cols = rows[i].querySelectorAll('td, th');
                 
                 for (var j = 0; j < cols.length; j++) {
                     var cellText = cols[j].innerText.replace(/"/g, '""');
                     row.push('"' + cellText + '"');
                 }
                 
                 csv.push(row.join(','));
             }
             
             var csvFile = new Blob([csv.join('\n')], {type: 'text/csv'});
             var downloadLink = document.createElement('a');
             downloadLink.download = 'categorywise_report_' + new Date().toISOString().slice(0,10) + '.csv';
             downloadLink.href = window.URL.createObjectURL(csvFile);
             downloadLink.style.display = 'none';
             document.body.appendChild(downloadLink);
             downloadLink.click();
             document.body.removeChild(downloadLink);
         });

         // Print functionality for regular print
         $('.print_it1').click(function() {
             var printWindow = window.open('', '_blank');
             var printContent = `
                 <html>
                 <head>
                     <title>Categorywise Report</title>
                     <style>
                         body { font-family: Arial, sans-serif; margin: 20px; }
                         table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                         th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                         th { background-color: #f2f2f2; font-weight: bold; }
                         .text-right { text-align: right; }
                         .bg-gray { background-color: #f9f9f9; }
                         h2 { color: #333; }
                     </style>
                 </head>
                 <body>
                     <h2>Categorywise Report</h2>
                     <p>Report Date: ${new Date().toLocaleDateString()}</p>
                     ${document.getElementById('report-data').outerHTML}
                 </body>
                 </html>
             `;
             printWindow.document.write(printContent);
             printWindow.document.close();
             printWindow.print();
         });

         // Print functionality for 3-inch thermal print
         $('.print_it').click(function() {
             var table = document.getElementById('report-data');
             var printContent = '<html><head><title>Categorywise Report</title>';
             printContent += '<style>';
             printContent += 'body { font-family: monospace; font-size: 10px; margin: 5px; }';
             printContent += 'table { width: 100%; border-collapse: collapse; }';
             printContent += 'th, td { padding: 2px; font-size: 8px; border: none; }';
             printContent += 'th { font-weight: bold; }';
             printContent += '.text-right { text-align: right; }';
             printContent += 'h3 { font-size: 12px; margin: 5px 0; text-align: center; }';
             printContent += '</style></head><body>';
             printContent += '<h3>CATEGORYWISE REPORT</h3>';
             printContent += '<p style="font-size: 8px; text-align: center;">Date: ' + new Date().toLocaleDateString() + '</p>';
             
             // Create simplified table for thermal printing
             var rows = table.querySelectorAll('tr');
             printContent += '<table>';
             
             for (var i = 0; i < rows.length; i++) {
                 var cols = rows[i].querySelectorAll('td, th');
                 if (cols.length > 0) {
                     printContent += '<tr>';
                     
                     // Only include essential columns for thermal print
                     var essentialColumns = [];
                     for (var j = 0; j < cols.length; j++) {
                         var cellText = cols[j].innerText;
                         // Skip store/warehouse columns for thermal print to save space
                         if (j === 0 || (cellText.includes('Store') || cellText.includes('Warehouse'))) {
                             if (j === 0) essentialColumns.push(cellText); // Keep row number
                         } else {
                             essentialColumns.push(cellText);
                         }
                     }
                     
                     // Limit to most important columns for thermal
                     var maxCols = Math.min(essentialColumns.length, 5);
                     for (var k = 0; k < maxCols; k++) {
                         var cellClass = '';
                         if (essentialColumns[k].match(/^\d+(\.\d+)?$/) || essentialColumns[k].includes('Total')) {
                             cellClass = 'text-right';
                         }
                         printContent += '<td class="' + cellClass + '">' + essentialColumns[k] + '</td>';
                     }
                     
                     printContent += '</tr>';
                 }
             }
             
             printContent += '</table></body></html>';
             
             var printWindow = window.open('', '_blank');
             printWindow.document.write(printContent);
             printWindow.document.close();
             printWindow.print();
         });

         // Reset form functionality
         $('#reset-btn').click(function() {
             document.getElementById('report-form').reset();
             $("#tbody_data").html('');
             $('#customer_id').val('').trigger('change');
             $('#item_id').val('').trigger('change');
             $('#category_id').val('').trigger('change');
             $('#brand_id').val('').trigger('change');
             $('#created_by').val('').trigger('change');
             $('#from_date').val("<?php echo show_date(date('d-m-Y'));?>");
             $('#to_date').val("<?php echo show_date(date('d-m-Y'))?>");
             $('#from_time').val('00:00');
             $('#to_time').val('23:59');
         });

      </script>
      <!-- Make sure to load these scripts -->
      <script src="<?php echo $theme_link; ?>js/customers.js"></script>
      <script src="<?php echo $theme_link; ?>js/items.js"></script>
      <script src="<?php echo $theme_link; ?>js/category.js"></script>
      <script src="<?php echo $theme_link; ?>js/brand.js"></script>
      <script src="<?php echo $theme_link; ?>js/users.js"></script>
   </body>
</html>
