<!DOCTYPE html>
<html>
<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css_form.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 -->
    <?= form_open('#', array('class' => '', 'id' => 'table_form')); ?>
    <input type="hidden" id='base_url' value="<?=$base_url;?>">

    <section class="content">
      <div class="row">
        <!-- ********** ALERT MESSAGE START******* -->
        <?php include"comman/code_flashdata.php"; ?>
        <!-- ********** ALERT MESSAGE END******* -->
        <div class="col-xs-12">
          <div class="box">
            <div class="box-header with-border">
              <div class="row">
                  <div class="col-md-12">
                    <div class="col-md-4" hidden>
                        <label for="payment_type" class=" control-label">Payment</label>
                          <select class="form-control select2" id="payment_type" name="payment_type"  style="width: 100%;">
                            <option value="Paid">Paid</option>
                            <option value="Unpaid">Unpaid</option>
                         </select>
                    </div>
                    <div class="col-md-4" hidden>
                        <label for="agent_id" class=" control-label">Agent</label>
                        <?php if(($this->session->userdata('role_id')=='3')||($this->session->userdata('role_id')=='4')){ ?>
                              <select class="form-control select2" id="agent_id" name="agent_id"  style="width: 100%;" disabled>
                                 <?php
                                 $log_UID = $this->session->userdata('inv_userid');
                                 $query1="select * from db_agent where status='1' and user_id='$log_UID' limit 1";
                                 $q1=$this->db->query($query1);
                                 if($q1->num_rows($q1)>0)
                                 {
                                    foreach($q1->result() as $res1)
                                    {
                                    $selected = ($res1->id==$id)? 'selected' : '';
                                    echo "<option selected value='".$res1->id."'>".$res1->agent."</option>";
                                    }
                                 }
                                 else
                                 {
                                    ?>
                                 <option value="">No Records Found</option>
                                 <?php }} ?>
                                 <?php if($this->session->userdata('role_id')=='1'){ ?>
                              <select class="form-control select2" id="agent_id" name="agent_id"  style="width: 100%;">
                                 <option value="all">All</option>
                                 <?php
                                 $log_UID = $this->session->userdata('inv_userid');
                                 $query1="select * from db_agent where status='1'";
                                 $q1=$this->db->query($query1);
                                 if($q1->num_rows($q1)>0)
                                 {
                                 echo '<option value="">-Select-</option>'; 
                                    foreach($q1->result() as $res1)
                                    {
                                    $selected = ($res1->id==$id)? 'selected' : '';
                                    echo "<option $selected value='".$res1->id."'>".$res1->agent."</option>";
                                    }
                                 }
                                 else
                                 {
                                    ?>
                                 <option value="">No Records Found</option>
                                 <?php }} ?>
                              </select>
                    </div>
                    <div class="col-md-4" hidden>
                        <label for="platform_id" class=" control-label">Platform</label>
                          <select class="form-control select2" id="platform_id" name="platform_id"  style="width: 100%;">
                              <option value="all">All</option>
                            <?php
                               $query1="select * from db_platform where status='1'";
                               $q1=$this->db->query($query1);
                               if($q1->num_rows($q1)>0)
                                {  
                                    foreach($q1->result() as $res1)
                                  { 
                                    echo "<option value='".$res1->id."'>".$res1->platform."</option>";
                                  }
                                }
                                else
                                {
                                   ?>
                            <?php
                               }
                               ?>
                         </select>
                    </div>
                  </div>
                  <div class="col-md-12">
                    <div class="col-md-4">
                        <label for="from_date" class=" control-label">From Date</label>
                          <input type="date" name="from_date" id="from_date" class="form-control" value="<?php $date = new DateTime("now", new DateTimeZone('Asia/Colombo') ); echo $date->format('Y-m-d');?>">
                    </div>
                    <div class="col-md-4">
                        <label for="to_date" class=" control-label">To Date</label>
                          <input type="date" name="to_date" id="to_date" class="form-control" value="<?php $date = new DateTime("now", new DateTimeZone('Asia/Colombo') ); echo $date->format('Y-m-d');?>">
                    </div>                 
                    
                  </div>
              </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body" style="overflow-y: scroll;">
              <table id="example2" class="table table-bordered table-striped" width="100%">
              <?php if($this->session->userdata('role_id')=='1'||$this->session->userdata('role_id')=='2'){ ?>
                <thead class="bg-primary ">
                <tr>
                  <th class="text-center">#</th>
                  <th>Sale Date</th>
                  <th>Coustmer</th>
                  <th>Payment <br> Status</th>
                  <th>Item Name</th>
                  <th>SKU</th>
                  <th>Qty</th>
                  <th>Unit Cost <br> Price</th>
                  <th>Total Cost <br> Price</th>
                  <th>Total Sold <br> Price</th>                  
                  <th>Admin Profit</th>
                </tr>
                </thead>
                <tbody>
				
                </tbody>
                <tfoot>
                  <tr class="bg-gray">
                      <th colspan="10" style="text-align:right">Total</th><!-- 6 -->
                      <th><b> <label id="lbl_sum_profit"></label> </b></th><!-- 8 -->
                  </tr>
               </tfoot>
              <?php } ?> 
              <?php if($this->session->userdata('role_id')=='3'){ ?>
                <thead class="bg-primary ">
                <tr>
                  <th class="text-center">#</th>
                  <th>Sale Date</th>
                  <th>Coustmer</th>
                  <th>Payment <br> Status</th>
                  <th>Item Name</th>
                  <th>SKU</th>
                  <th>Qty</th>
                  <th>Unit Cost <br> Price</th>
                  <th>Total Cost <br> Price</th>
                  <th>Total Sold <br> Price</th>                  
                </tr>
                </thead>
                <tbody>
				
                </tbody>
                <tfoot>
                  <tr class="bg-gray">
                      <th colspan="9" style="text-align:right">Total</th><!-- 6 -->
                      <th><b> <label id="lbl_sum_commision"></label> </b></th><!-- 8 -->
                  </tr>
               </tfoot>
                <?php } ?>         
              </table>

              <!-- <div class="row">
                 <div class="col-xs-12">
                    <button type="button" class="btn btn-success" id="btn_platform" name="btn_platform"> Platform</button>
                    
                 </div>
              </div> -->
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
     <?= form_close();?>
  
  </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_form.php"; ?>
<?php include"comman/code_js_datatable.php"; ?>

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

<script>
  function fill_tbData(){
      var payment_type = $('#payment_type').val();
      var agent_id = $('#agent_id').val();
      var from_date    = $('#from_date').val();
      var to_date    = $('#to_date').val();
      var platform_id   = $('#platform_id').val();

      //alert(fromDate+"           "+toDate);
      $.ajax({
        url:"<?php echo site_url('agent/profit_details_get_2')?>",
        type: 'post',
        data: {payment_type:payment_type,agent_id:agent_id,from_date:from_date,to_date:to_date,platform_id:platform_id},
        dataType: 'json',
        success: function (data) {

          var table;
          table = $('#example2').DataTable();
          table.clear();
          <?php if($this->session->userdata('role_id')=='1'||$this->session->userdata('role_id')=='2'){ ?>
            $.each(data.data_count_info, function(){
              var dataCount =parseInt(this['d_count']);
              //console.log(dataCount);
              if(dataCount>0) { 
                var indexNo = 1;           
                var commision_sum = 0;
                var ad_profit =0;
                $.each(data.itm_info, function(){
                      // var s_commision =parseFloat(this['AgentCommition']);
                      var s_id = this['id'];
                      var itm_s_id = this['itm_s_id'];
                      // var s_waybill = this['waybill'];
                      var s_agent_id = this['agent_id'];
                      var s_TotalInvoiceAmount = this['TotalInvoiceAmount'];
                      var s_Total_AdminProfit = parseFloat(this['AdminProfit']);
                      var s_qty = parseFloat(this['sales_qty']);
                      var s_cost = parseFloat(this['cost_price']);
                      var tot_cost = (s_qty*s_cost).toFixed(2);

                      table.row.add(['<div class="custom-checkbox custom-control"><input type="checkbox" data-checkboxes="mygroup" class="custom-control-input cus_credit"  name="cus_credit" id="checkbox-'+itm_s_id+'" value="'+itm_s_id+'" data-sales_id="'+s_id+'" data-sales_item_id="'+itm_s_id+'" data-agent_id="'+s_agent_id+'" data-total_amount="'+s_TotalInvoiceAmount+'"><label for="checkbox-'+itm_s_id+'" class="custom-control-label">&nbsp;</label></div>',this['sales_date'], this['customer_name'],this['payment_status'], this['item_name'], this['sku'], s_qty, this['cost_price'],tot_cost, this['TotalSaleAmount'], this['AdminProfit']]);
                      indexNo++;
                      // commision_sum  += s_commision;
                      ad_profit += s_Total_AdminProfit;
                });
                table.draw();
                $('#lbl_sum_profit').empty();
                $('#lbl_sum_profit').append(ad_profit.toFixed(2));
              }else {
                  $('#example2').DataTable().destroy();
                toastr["warning"]("Something Wrong! , Data Not Found. ");
              }
            });

          <?php } else if(($this->session->userdata('role_id')=='3')){ ?>
            $.each(data.data_count_info, function(){
              var dataCount =parseInt(this['d_count']);
              //console.log(dataCount);
              if(dataCount>0) { 
                var indexNo = 1;           
                var commision_sum = 0;
                $.each(data.itm_info, function(){
                      // var s_commision =parseFloat(this['AgentCommition']);
                      var s_id = this['id'];
                      var itm_s_id = this['itm_s_id'];
                      var s_waybill = this['waybill'];
                      var s_agent_id = this['agent_id'];
                      var s_TotalInvoiceAmount = this['TotalInvoiceAmount'];
                      var s_qty = parseInt(this['sales_qty']);
                      var s_cost = parseFloat(this['cost_price']);
                      var tot_cost = (s_qty*s_cost).toFixed(2);

                      table.row.add(['<div class="custom-checkbox custom-control"><input type="checkbox" data-checkboxes="mygroup" class="custom-control-input cus_credit"  name="cus_credit" id="checkbox-'+itm_s_id+'" value="'+itm_s_id+'" data-sales_id="'+s_id+'" data-sales_item_id="'+itm_s_id+'" data-agent_id="'+s_agent_id+'" data-total_amount="'+s_TotalInvoiceAmount+'"><label for="checkbox-'+itm_s_id+'" class="custom-control-label">&nbsp;</label></div>',this['sales_date'],this['waybill'], this['customer_name'],this['payment_status'], this['item_name'], this['sku'], s_qty, this['cost_price'],tot_cost, this['TotalSaleAmount']]);
                      indexNo++;
                      // commision_sum  += s_commision;
                });
                table.draw();
              }else {
                  $('#example2').DataTable().destroy();
                toastr["warning"]("Something Wrong! , Data Not Found. ");
              }
            });
          <?php } ?>

          
          
        },
        error: function (xhr, ajaxOptions, thrownError) {
          console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
  }
</script>
<script>
    $(document).ready(function(){
      fill_tbData();
    });
</script>
<script>
    $('#payment_type').on('change',function(){
      fill_tbData();
    });
</script>
<script>
    $('#agent_id').on('change',function(){
      fill_tbData();
    });
</script>
<script>
    $('#to_date').on('change',function(){
      fill_tbData();
    });
</script>
<script>
    $('#from_date').on('change',function(){
      fill_tbData();
    });
</script>
<script>
    $('#platform_id').on('change',function(){
      fill_tbData();
    });
</script>
<script>
// function convert_excel(type,file_name,table_name) {
//     var fn; var dl;
//     var elt = document.getElementById(table_name);
//     var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
//     return dl ?
//         XLSX.write(wb, {bookType:type, bookSST:true, type: 'base64'}) :
//         XLSX.writeFile(wb, fn || (file_name+'.' + (type || 'xlsx')));
// }
// $(".btnExport").click(function(event) {
//  convert_excel('xlsx','Porfit-Report-1','report-data');
// });
// $(".btnExport_2").click(function(event) {
//  convert_excel('xlsx','Profit-Report-2','report-data-2');
// });
// $(".btnExport_3").click(function(event) {
//  convert_excel('xlsx','Profit-by-items-Report','profit_by_item_table');
// });
// $(".btnExport_4").click(function(event) {
//  convert_excel('xlsx','Profit-by-invoice-Report','profit_by_invoice_table');
// });
// $(".btnExport_5").click(function(event) {
//  convert_excel('xlsx','Profit-Report-4','report-data-3');
// });
// $(".btnExport_6").click(function(event) {
//  convert_excel('xlsx','Profit-Report-3','report-data-4');
// });

// function get_reports(report_type,table_name){
//   $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
//   var base_url=$("#base_url").val();
//   return $.post(base_url+'reports/'+report_type, {from_date: get_start_date('pl2-daterange-btn'), to_date: get_end_date('pl2-daterange-btn')}, function(result) {
//     //console.log(result);
//     $("#"+table_name+" tbody").html(result);
//     $(".overlay").remove();
//   });
// }
// function get_all_reports(){
//   get_reports('get_profit_by_item','profit_by_item_table');
//   get_reports('get_profit_by_invoice','profit_by_invoice_table');
// }
// jQuery(document).ready(function($) {
//   get_pl_values();
//    get_all_reports();
// });

// function get_pl_values(){
//   var base_url=$("#base_url").val();
//   $.post(base_url+"reports/get_profit_loss_report",{from_date: get_start_date('pl-daterange-btn'), to_date: get_end_date('pl-daterange-btn')},function(result){
//       var data = jQuery.parseJSON(result);
//       $.each(data, function(index, element) {
//               $("."+index).html(element);
//       });
//   });
// }

/*Date Range picker event 1*/
// $('#pl-daterange-btn').on('apply.daterangepicker', function(ev, picker) {
//   get_pl_values();
// });
/*end*/
/*Date Range picker event 2*/
// $('#pl2-daterange-btn').on('apply.daterangepicker', function(ev, picker) {
//   get_all_reports();
// });
/*end*/

// $(function() {
//     var start = moment().subtract(29, 'days');
//     var end = moment();
//     function cb(start, end) {
//         $('#pl-daterange-btn, #pl2-daterange-btn span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
//     }
//     cb(start, end);
// });

</script>


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