<!DOCTYPE html>
<html>

<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css_datatable.php"; ?>

<!-- Lightbox -->
<link rel="stylesheet" href="<?php echo $theme_link; ?>plugins/lightbox/ekko-lightbox.css">
</head>

<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <!-- Left side column. contains the logo and sidebar -->
  
  <?php include"sidebar.php"; ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        <?=$page_title;?>
      </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">
                        <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">
                        <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">
                        <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') );  $date->modify('-30 day'); 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 class="col-md-4">
                      <br>
                        <label id="f_lbl_amt" class="control-label"></label>
                    </div> 
                    
                  </div>
              </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body">
              <table id="example2" class="table table-bordered table-striped" width="100%">
                <thead class="bg-primary ">
                    <tr>
                    <th class="text-center">#</th>
                    <th>Invoice No.</th>
                    <th>Sale Date</th>
                    <th>Waybill</th>
                    <th>Coustmer</th>
                    <th>SKU</th>
                    <th>Sale Agent</th>
                    <!-- <th>Sale Price</th>
                    <th>Delivery Charge</th> -->
                    <th>Sale Price</th>
                    <th>Agent Commissions</th>
                    <?php if($this->session->userdata('role_id')=='1'){ ?>
                    <th>Admin Profit</th>
                    <?php } ?>
                    </tr>
                </thead>
                <tbody>
                    
                </tbody>
                <tfoot>
                    <tr class="bg-gray">
                        <th colspan="7" style="text-align:right">Total</th><!-- 6 -->
                        <th><b> <label id="lbl_sum_salePrice">0.00</label> </b></th><!-- 8 -->
                        <th><b> <label id="lbl_sum_commision"></label> </b></th><!-- 8 -->
                        <?php if($this->session->userdata('role_id')=='1'){ ?>
                          <th><b> <label id="lbl_sum_profit"></label> </b></th>
                        <?php } ?>
                    </tr>
                </tfoot>
              </table>


              <br>

              <table id="example3" class="table table-bordered table-striped" width="100%">
                <thead class="bg-primary ">
                    <tr>
                    <th class="text-center">#</th>
                    <th>Invoice No.</th>
                    <th>Sale Date</th>
                    <th>Return No.</th>
                    <th>Return Date</th>
                    <th>Agent</th>
                    <th>Return Fee</th>
                    </tr>
                </thead>
                <tbody>
                    
                </tbody>
                <tfoot>
                    <tr class="bg-gray">
                        <th colspan="6" style="text-align:right">Total</th><!-- 6 -->
                        <th><b> <label id="lbl_sum_returnfee"></label> </b></th><!-- 8 -->
                    </tr>
                </tfoot>
              </table>

              <br>
              
                <div class="row">
                    <div class="col-md-12">
                      <input type="hidden" id="agent_commision" name="agent_commision" value="0.00" class="form-control">
                      <input type="hidden" id="r_fee_total" name="r_fee_total" value="0.00" class="form-control">
                      <label for="blance" id="lbl_balance"></label>
                      <?php if($this->session->userdata('role_id')=='1'){ ?>
                        <button type="button" class="btn btn-success" id="pay_commision" style="float: right;"> Commision Paid </button>
                      <?php } ?>
                    </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_datatable.php"; ?>
<!-- Lightbox -->
<script src="<?php echo $theme_link; ?>plugins/lightbox/ekko-lightbox.js"></script>
<script type="text/javascript">
  $(document).on('click', '[data-toggle="lightbox"]', function(event) {
            event.preventDefault();
            $(this).ekkoLightbox();
        });
</script>
<script>
  $(document).ready(function() {
    $('#example2').DataTable();
  });
</script>
<!-- <script type="text/javascript">
function load_datatable(){
    //datatables
   var table = $('#example2').DataTable({ 

      /* FOR EXPORT BUTTONS START*/
  dom:'<"row margin-bottom-12"<"col-sm-12"<"pull-left"l><"pull-right"fr><"pull-right margin-left-10 "B>>>tip',
 /* dom:'<"row"<"col-sm-12"<"pull-left"B><"pull-right">>> <"row margin-bottom-12"<"col-sm-12"<"pull-left"l><"pull-right"fr>>>tip',*/
      buttons: {
        buttons: [
            {
                className: 'btn bg-red color-palette btn-flat hidden delete_btn pull-left',
                text: 'Delete',
                action: function ( e, dt, node, config ) {
                    multi_delete();
                }
            },
            { extend: 'copy', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [2,3,4,5,6,7]} },
            { extend: 'excel', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [2,3,4,5,6,7]} },
            { extend: 'pdf', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [2,3,4,5,6,7]} },
            { extend: 'print', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [2,3,4,5,6,7]} },
            { extend: 'csv', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [2,3,4,5,6,7]} },
            { extend: 'colvis', className: 'btn bg-teal color-palette btn-flat',text:'Columns' },  

            ]
        },
        /* FOR EXPORT BUTTONS END */

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.
        "responsive": true,
        language: {
            processing: '<div class="text-primary bg-primary" style="position: relative;z-index:100;overflow: visible;">Processing...</div>'
        },
        // Load data for the table's content from an Ajax source
        "ajax": {
            "url": "<?php echo site_url('items/ajax_list')?>",
            "type": "POST",
            "data":{
              brand_id : $("#brand_id").val(),
              category_id : $("#category_id").val(),
            },
            
            complete: function (data) {
             $('.column_checkbox').iCheck({
                checkboxClass: 'icheckbox_square-orange',
                /*uncheckedClass: 'bg-white',*/
                radioClass: 'iradio_square-orange',
                increaseArea: '10%' // optional
              });
             call_code();
              //$(".delete_btn").hide();
             },

        },

        //Set column definition initialisation properties.
        "columnDefs": [
        { 
            "targets": [ 0 ], //first column / numbering column
            "orderable": false, //set not orderable
        },
        {
            "targets" :[0],
            "className": "text-center",
        },
        
        ],
    });
    new $.fn.dataTable.FixedHeader( table );
} 

$(document).ready(function() {
//     //datatables
//    load_datatable();
// });
// $("#brand_id,#category_id").change(function(){
//     $('#example2').DataTable().destroy();
//     load_datatable();
// });

 </script> -->

<script>
    $(document).ready(function() {
        $("[data-checkboxes]").each(function () {
        var me = $(this),
          group = me.data('checkboxes'),
          role = me.data('checkbox-role');

        me.change(function () {
          var all = $('[data-checkboxes="' + group + '"]:not([data-checkbox-role="dad"])'),
            checked = $('[data-checkboxes="' + group + '"]:not([data-checkbox-role="dad"]):checked'),
            dad = $('[data-checkboxes="' + group + '"][data-checkbox-role="dad"]'),
            total = all.length,
            checked_length = checked.length;

          if (role == 'dad') {
            if (me.is(':checked')) {
              all.prop('checked', true);
              calAmount(this);
            } else {
              all.prop('checked', false);
              calAmount(this);
            }
          } else {
            if (checked_length >= total) {
              dad.prop('checked', true);
            } else {
              dad.prop('checked', false);
            }
          }
        });
      });
    });
</script>


<script src="<?php echo $theme_link; ?>js/items.js"></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')?>",
        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) {

          $('#lbl_sum_returnfee').empty();
          $('#lbl_balance').empty();
          $('#f_lbl_amt').empty();
          $('#lbl_sum_profit').empty();
          $('#lbl_sum_commision').empty();
          $('#agent_commision').val(0.00);
          $('#r_fee_total').val(0.00);
          $('#lbl_sum_profit').val(0.00);
          $('#lbl_sum_commision').val(0.00);

          var table;
          table = $('#example2').DataTable();
          table.clear();
          <?php if($this->session->userdata('role_id')=='1'){ ?>
            $.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;
                var total_salePrice = 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 = parseFloat(this['TotalInvoiceAmount']);
                      var s_Total_AdminProfit = parseFloat(this['AdminProfit']);

                      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-waybill="'+s_waybill+'" data-agent_id="'+s_agent_id+'" data-total_amount="'+s_TotalInvoiceAmount+'" data-commission_amount="'+s_commision+'"><label for="checkbox-'+itm_s_id+'" class="custom-control-label">&nbsp;</label></div>',this['sales_code'],this['sales_date'],this['waybill'], this['customer_name'], this['sku'], this['agent'], this['TotalInvoiceAmount'], this['AgentCommition'], this['AdminProfit']]);
                      indexNo++;
                      commision_sum  += s_commision;
                      ad_profit += s_Total_AdminProfit;
                      total_salePrice  += s_TotalInvoiceAmount;
                });
                table.draw();
                $('#lbl_sum_commision').empty();
                $('#lbl_sum_commision').append(commision_sum.toFixed(2));
                $('#agent_commision').val(commision_sum.toFixed(2));
                $('#lbl_sum_profit').empty();
                $('#lbl_sum_profit').append(ad_profit.toFixed(2));
                $('#lbl_sum_salePrice').empty();
                $('#lbl_sum_salePrice').append(total_salePrice.toFixed(2));
              }else {
                  $('#example2').DataTable().destroy();
                toastr["warning"]("Something Wrong! , Data Not Found. ");
              }
            });

          <?php } else if($this->session->userdata('role_id')!='1'){ ?>
            $.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 total_salePrice = 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 = parseFloat(this['TotalInvoiceAmount']);

                      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-waybill="'+s_waybill+'" data-agent_id="'+s_agent_id+'" data-total_amount="'+s_TotalInvoiceAmount+'" data-commission_amount="'+s_commision+'"><label for="checkbox-'+itm_s_id+'" class="custom-control-label">&nbsp;</label></div>',this['sales_code'],this['sales_date'],this['waybill'], this['customer_name'], this['sku'], this['agent'], this['TotalInvoiceAmount'], this['AgentCommition']]);
                      indexNo++;
                      commision_sum  += s_commision;
                      total_salePrice  += s_TotalInvoiceAmount;
                });
                table.draw();
                $('#lbl_sum_commision').empty();
                $('#lbl_sum_commision').append(commision_sum.toFixed(2));
                $('#agent_commision').val(commision_sum.toFixed(2));
                $('#lbl_sum_salePrice').empty();
                $('#lbl_sum_salePrice').append(total_salePrice.toFixed(2));
                
              }else {
                  $('#example2').DataTable().destroy();
                toastr["warning"]("Something Wrong! , Data Not Found. ");
              }
            });
          <?php } ?>

          var table2;
          table2 = $('#example3').DataTable();
          table2.clear();

            $.each(data.data_free_count, function(){
              var da_count =parseInt(this['free_count']);
              //console.log(dataCount);
              if(da_count>0) { 
                var indexNo_2 = 1;           
                var r_fee = 0;
                $.each(data.return_info, function(){
                      var s_other_charge = parseFloat(this['other_charge']);

                      table2.row.add(['<div class="custom-checkbox custom-control"><input type="checkbox" data-checkboxes="mygroup_2" class="custom-control-input return_credit"  name="return_credit" id="checkbox-'+this['id']+'" value="'+this['id']+'" data-sales_id="'+this['id']+'" data-sales_id="'+this['sales_id']+'"><label for="checkbox-'+this['id']+'" class="custom-control-label">&nbsp;</label></div>',this['sales_code'],this['sales_date'], this['return_code'], this['return_date'], this['agent'], this['other_charge']]);
                      indexNo_2++;
                      r_fee  += s_other_charge;
                });
                table2.draw();
  
                $('#lbl_sum_returnfee').append(r_fee.toFixed(2));
                $('#r_fee_total').val(r_fee.toFixed(2));
              }else {
                  $('#example3').DataTable().destroy();
                //toastr["warning"]("Something Wrong! , Data Not Found. ");
              }
            });

            var r_fee_total = parseFloat($('#r_fee_total').val());
            var agent_commision = parseFloat($('#agent_commision').val());
            var finalTOT = agent_commision-r_fee_total;

            $('#lbl_balance').append('Final Agent Commision = '+agent_commision.toFixed(2)+' - '+r_fee_total.toFixed(2)+' = '+finalTOT.toFixed(2));
            $('#f_lbl_amt').append('Final Agent Commision = '+finalTOT.toFixed(2));
            

        },
        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>
    $('#pay_commision').on('click',function(){
        var sale_itemSet = [];
        var return_set = [];
        var data_table =[];
        $.each($("input[name='cus_credit']:checked"), function(){
            sale_itemSet.push($(this).val());
            //$(this).attr('data-ID')
            var record = {
                'sales_id' :  $(this).attr('data-sales_id'),
                'sales_item_id' :  $(this).attr('data-sales_item_id'),
                'waybill' :  $(this).attr('data-waybill'),
                'agent_id' :  $(this).attr('data-agent_id'),
                'total_amount' :  $(this).attr('data-total_amount'),
                'commission_amount' :  $(this).attr('data-commission_amount')
			      };

            data_table.push(record);
        });



        $.each($("input[name='return_credit']:checked"), function(){
          return_set.push($(this).val());
        });

        var all_data ={'data_table':data_table,'sale_itemSet':sale_itemSet,'return_set':return_set};

        var sl_len= sale_itemSet.length;

        if(sl_len>0){
        
            $.ajax({
                url:"<?php echo site_url('agent/commission_update')?>",
                type: 'post',
                data: all_data,
                dataType: 'json',
                success: function (data) {
                    if(data=='success'){
                        fill_tbData();
                        toastr["success"]("Payments Added Successfully!");       
                    }else if(data=='failed'){
                        toastr["error"]("Sorry! Failed to save Record.Try again!");
                    } 
                },
                error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }
            });
        }else{
            toastr["warning"]("Something Wrong! , Please select records. ");
        }
    });
</script>

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