<?php
  if( !hasPermission($_SESSION['user_detail']['role_id'], 'commission_add') ) {
    echo '<script>window.location.href="index.php?page=no_permission.php"</script>';die();
  }

$result = mysqli_query($conn, "SELECT MAX(code) AS code FROM `mst_commission`");
$row = mysqli_fetch_array($result, MYSQLI_BOTH);

if ($row && isset($row['code']) && preg_match('/^\d{4}$/', $row['code'])) {
    $current_no = intval($row['code']);
    $new_no = $current_no + 1;
    $code = str_pad($new_no, 4, '0', STR_PAD_LEFT);
} else {
    $code = '0001';
}

?>

<link rel="stylesheet" href="assets/plugins/toaster/jquery.toast.css">
<link rel="stylesheet" href="assets/plugins/toaster/jquery.toast.min.css">
<script src="assets/plugins/toaster/jquery.toast.js"></script>
<section class="content-header">
  <div class="row">
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 bottom20">
        <h3 class="capital font15 padding5 bold">ADD NEW COMMISSION</h3>
      </div>
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 text-right bottom20">
        <h3>
          <?php if( hasPermission($_SESSION['user_detail']['role_id'], 'commission_list') ) { ?>
          <a href="index.php?page=commission_Flag/list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW COMMISSION DETAILS</a>
          <?php } ?>
        </h3>
      </div>
  </div>
</section>
<hr class="bottom35"> 
<section class="hitz-top-header">
  <div class="row bottom40">
    <div class="col-xs-12">
       <div class="box box-success">
          <div class="box-body">
            <form enctype="multipart/form-data" class="common-frm-validation" id="signupForm">
              <div class="row">
                 <div class="col-md-2">
                    <div class="form-group">
                      <label class="capital">CODE </label><span style="color: red">*</span>
                        <input type="text" size="35" id="code" name="code" class="form-control lr_number required" autocomplete="off" placeholder="CODE" autofocus="" onChange="CheckCode(this.value);" value="<?php echo $code; ?>" readonly />
                    </div>
                 </div>

                 <div class="col-md-3">
                    <div class="form-group">
                       <label class="capital">vendor</label><span style="color: red">*</span>
                       <select class="form-control select2 required product-name" name="vendor_id" id="vendor_id" onchange="productAutoComplete(this);">
                          <option value></option>
                          <?php 
                          $ven      = "SELECT * FROM `vendor_master` WHERE `status` = '0'";
                          $ven_res  = mysqli_query($conn,$ven);
                          while ($ven_row = mysqli_fetch_assoc($ven_res)) { ?>
                          <option value="<?php echo $ven_row['id'];?>"><?php echo $ven_row['name'];?></option>
                          <?php }  ?>
                       </select>
                       <input type="hidden" name="v_id" id="v_id">
                    </div>
                 </div>
                 
                 <div class="col-md-2">
                    <div class="form-group">
                        <label class="capital">DATE</label><span style="color: red">*</span>
                        <div class="input-group date date-picker" data-date-format="dd-mm-yyyy">
                          <div class="input-group-addon">
                             <i class="fa fa-calendar"></i>
                          </div>
                          <input type="text" size="35" id="comission_date" name="comission_date" class="form-control date-picker required" placeholder="DATE" autocomplete="off" value="<?php echo date('d-m-Y')?>" />
                       </div>
                    </div>
                 </div>
              </div><br/>
              <div class="row">
                <div class="col-xs-12 col-sm-12">
                  <div id="product-wapper">
                    <table class="table table-bordered table-responsive">
                      <thead>
                        <tr>
                          <th class="text-center" width="3%">#</th>
                          <th class="text-center" width="10%">BILL NO</th>
                          <th class="text-center" width="10%">DATE</th>
                          <th class="text-center" width="10%">FROM</th>
                          <th class="text-center" width="10%">TO</th>
                          <th class="text-center" width="10%">VEHICLE NO</th>
                          <th class="text-center" width="10%">NET AMOUNT</th>
                          <th class="text-center" width="10%">COMMISSION %</th>
                          <th class="text-center" width="10%">COMMISSION AMOUNT</th>
                        </tr>
                      </thead>
                      <tbody>
                        <?php $i = 0;?>
                        <tr>
                          <td>
                            <a href="javascript:;" class="btn green btn-block add-more" style="display: block;"><i class="fa fa-plus"></i></a>
                            <a href="javascript:;" class="btn red btn-block remove-me" style="display: none;"><i class="fa fa-minus"></i></a>
                          </td>
                          <td id="billno">
                            <input type="text" name="product[<?php echo $i; ?>][bill_no]" value="" class="form-control product-name top bill_no add-more-table bill_cal" placeholder="Search By BILL NO" data-count="<?php echo $i;?>" onchange="CheckDuplicateRow(this);CheckBill(this)">
                           </td>
                          <td><input type="text" name="product[<?php echo $i; ?>][bill_date]" class="form-control bill_date top add-more-table bill_cal" readonly></td>
                          
                          <td><input type="text" name="product[<?php echo $i; ?>][bill_from]" class="form-control bill_from top add-more-table bill_cal" readonly></td>

                          <td><input type="text" name="product[<?php echo $i; ?>][bill_to]" class="form-control bill_to top add-more-table bill_cal" readonly></td>   

                          <td><input type="text" name="product[<?php echo $i; ?>][vehicle_no]" class="form-control vehicle_no calc-amt top add-more-table bill_cal" autocomplete="off"></td>                       

                          <td><input type="text" name="product[<?php echo $i; ?>][bill_net_amount]" class="form-control bill_net_amount calc-amt top add-more-table bill_cal" autocomplete="off"></td>

                          <td><input type="text" name="product[<?php echo $i; ?>][comission_per]" class="form-control calc-amt comission_per top number add-more-table bill_cal" autocomplete="off"></td>

                          <td><input type="text" name="product[<?php echo $i; ?>][comission_amount]" class="form-control comission_amount calc-amt top add-more-table bill_cal" autocomplete="off"></td>
                        </tr>
                        <?php $i++; ?>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <input type="hidden" value="<?php echo $_SESSION['branch_id'];?>" name="branch_id" id="branch_id">
              <input type="hidden" value="BILL" name="module" id="module">
              <input type="hidden" value="" name="id" id="id">
              <hr>
              <div class="row" align="center">
                <button id="btn" class="btn btn-primary capital save_btn" type="submit"> Save & List</button>
                <a href="index.php?page=commission_Flag/list.php" class="btn btn-success capital  view_bn" style="display:none;">VIEW ALL Bills</a>
                <a class="btn btn-danger delete_btn delete_data" style="display:none;" onclick="confirmDelete(this);"> Delete</a>
              </div>
            </form>
            
          </div>
       </div>
    </div>
  </div>
</section>
<div id="product-template" style="display:none;">
   <table>
      <tr>
          <td>
            <a href="javascript:;" class="btn green btn-block add-more" style="display: block;"><i class="fa fa-plus"></i></a>
            <a href="javascript:;" class="btn red btn-block remove-me" style="display: none;"><i class="fa fa-minus"></i></a>
          </td>
          <td id="billno"><input type="text" name="product[%i%][bill_no]" class="form-control product-name top bill_no add-more-table bill_cal" placeholder="Search By BILL NO" onchange="CheckBill(this);CheckDuplicateRow(this);"></td>

          <td><input type="text" name="product[%i%][bill_date]" class="add-more-table bill_cal form-control bill_date top" readonly></td>

          <td><input type="text" name="product[%i%][bill_from]" class="add-more-table bill_cal form-control bill_from top" readonly></td>
          <td><input type="text" name="product[%i%][bill_to]" class="add-more-table bill_cal form-control bill_to top" readonly></td>

          <td><input type="text" name="product[%i%][vehicle_no]" class="form-control vehicle_no calc-amt top add-more-table bill_cal" autocomplete="off"></td>

          <td><input type="text" name="product[%i%][bill_net_amount]" class="form-control bill_net_amount calc-amt top add-more-table bill_cal" autocomplete="off"></td>

          <td><input type="text" name="product[%i%][comission_per]" class="add-more-table bill_cal form-control form-control calc-amt comission_per top" autocomplete="off"></td>

          <td><input type="text" name="product[%i%][comission_amount]" class="add-more-table bill_cal form-control form-control calc-amt comission_amount top" autocomplete="off"></td>

      </tr>
   </table>
</div>
<script type="text/javascript">
$(document).ready(function() {
    $('#signupForm').on('submit', function(e) {
        e.preventDefault();
        var rowsData = [];
        $('.add-more-table').each(function(index, element) {
            var row = $(this).closest('tr');
            var billNo = row.find('.bill_no').val();
            if (!billNo) {
                return true; // Equivalent to "continue" in a regular loop
            }
            var rowData = row.find("input, select").serialize();
            rowsData.push(rowData);
        });
        //console.log("Processing " + rowsData.length + " row(s).");
        var formData = $(this).serialize();
        formData += '&' + $.param({ rowsData: rowsData }, true);
        $.ajax({
            url: "commission_Flag/insert.php",
            type: "post",
            data: formData,
            success: function(data) {
                
                
                var response = JSON.parse(data);
               // alert(data);
                
                
                $('.add-more-table').each(function(index, element) {
                    var row = $(this).closest('tr');
                    var billNo = row.find('.bill_no').val();
                    var result = response.find(function(item) {
                        return item.message.includes(billNo);
                    });
                    
                    if (result) {

                        if (result.status === "success") {
                            row.find('.mr_status').val('Yes');
                            row.find('.mr_status').css({backgroundColor: 'green', color:'#fff' });
                            $(".delete_btn").attr('id', result.bill_no);
                            $(".save_btn").hide();
                            $(".view_bn").show();
                            
                        } else {                          
                            //alert(result.mr_no);
                            row.find('.mr_status').val("No");
                            row.find('.mr_status').css({backgroundColor: 'Red', color:'#fff' });
                            $(".save_btn").hide();
                            $(".delete_btn").show();
                            $(".delete_btn").attr('id', result.bill_no);
                            $(".cancel_btn").hide();
                            $(".view_bn").hide();
                        }
                    }
                });
            },
            error: function() {
                
                console.log("Error inserting Commission data.");
                
            }
        });
    });
});

document.addEventListener('input', function (e) {
    if (e.target.matches('.bill_net_amount, .comission_per')) {
        const row = e.target.closest('tr');
        const netAmount = parseFloat(row.querySelector('.bill_net_amount').value) || 0;
        const commissionPercent = parseFloat(row.querySelector('.comission_per').value) || 0;
        const commissionAmount = (netAmount * commissionPercent) / 100;
        row.querySelector('.comission_amount').value = commissionAmount.toFixed(2);
    }
});





  jQuery(document).ready(function() {
    $('#vendor_id').select2();
    $(".chosen-select").chosen({disable_search_threshold: 1});
    $(document).on('change', '.hitz-del', function() {
      var $tr = jQuery(this).closest('tr').find('.deduction').attr('data-count');
      jQuery('input[name="sub[' + $tr + '][tax_per]"]').removeAttr("readonly", "readonly");
      jQuery('input[name="sub[' + $tr + '][amount]"]').removeAttr("readonly", "readonly");
    });

    $(document).on('change', '.hitz-add', function() {
      var $trs = jQuery(this).closest('tr').find('.addition').attr('data-count');
      console.log($trs);
      jQuery('input[name="add[' + $trs + '][amount]"]').removeAttr("readonly", "readonly");
    });

   
    var $length = 0;
    productAutoComplete();

    jQuery(document).on('click', '.add-more', function(e) {
       $length = jQuery('#product-wapper').find('table tbody tr').length;
       var $clone = jQuery('#product-template table tr').clone();

       $clone.find('input').each(function() {
           this.name = this.name.replace('[%i%]', '[' + $length + ']');
       });

       $clone.find('.product-name').attr('data-count', $length);

       jQuery('#product-wapper table tbody').append($clone);

       productAutoComplete();
       calculateFinalAmount();
       jQuery('#product-wapper table tbody').find('.remove-me').show();
       jQuery('#product-wapper table tbody').find('.add-more').hide();

       jQuery('#product-wapper table tbody').find('.remove-me:last').hide();
       jQuery('#product-wapper table tbody').find('.add-more:last').show();
    });

    jQuery(document).on('click', '.remove-me', function(e) {
      e.preventDefault();
      jQuery(this).closest('tr').remove();
      calculateFinalAmount();
    });

    $(document).on('keyup', ".calc-amt", function() {
      calculateFinalAmount();
    });

    $(document).on('keyup', ".gst-cal", function() {
      calculateFinalAmount();
    });

    $(document).on('keyup', '.hitz_add', function() {
      calculateFinalAmount();
    });

    $(document).on('keyup', '.hitz_subs', function() {
      calculateFinalAmount();
    });

    
    /*$(document).on('keyup', 'input[name="adv_amnt"]', function() {
      var dv = $(this).val();
      var net_payable_amt = $('input[name="total"]').val();
      var due_amnt = net_payable_amt - dv;
      $('input[name="balance"]').val(due_amnt);
    });*/
  });
  function productAutoComplete(ele) {
    
    var $vendor_id      = $("#vendor_id").val();
    $( ".product-name" ).autocomplete({
      position: { my: "left bottom", at: "left top", collision: "flip" },
      source: function( request, response ) {
        $.ajax({
          url: "commission_Flag/get_bill_no.php",
          type: 'post',
          dataType: "json",
          data: {
            search: request.term,
            vendor_id:$vendor_id,
          },
          success: function( data ) {
            response( data );
          }
        });
      },
      select: function (event, ui) {
        var $parent = jQuery(this).parents('tr');
        var $i = jQuery(this).attr('data-count');
        $checkpoint = false;
        $checkpoint = CheckDuplicateRow(ui.item.invoice_no, ui.item.id);
        if( $checkpoint ) {
          $parent.find('.product-name').val(ui.item.invoice_no);
          $parent.find('.bill_date').val(ui.item.bill_date);
          $parent.find('.bill_from').val(ui.item.bill_from);
          $parent.find('.bill_to').val(ui.item.bill_to);
          $parent.find('.bill_net_amount').val(ui.item.bill_net_amount);
          //$parent.find('.bill_pending').val(ui.item.balance);
        }else{
          var $this = jQuery(this);
          setTimeout(function(){
            $this.focus();
            $this.select();
          }, 100);
        }
        //calculateFinalAmount();
        //checknagative();
        return false;
      }
    }).each(function() {
       $(this).autocomplete( 'instance' )._renderItem = function( ul, item ) {
          return $( "<li>" )
             .append( "<a><span>" + item.invoice_no + '</span></a>' )
             .appendTo( ul );
        };
    });
  }
  
   function CheckBill(ele){
     
    var bill_no = $(ele).val();
    var $tr = jQuery(ele).closest('tr');
    $.ajax({
      'type': 'POST',
      'url': 'commission_Flag/check_bill.php',
      'data': {
        'bill_no' : bill_no,
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 0) {
          $tr.find('.bill_no').val(result.bill_no);
          $.toast({
            heading: 'Error',
            text: 'INVALID BILL...',
            showHideTransition: 'fade',
            position: 'top-right',
            icon: 'error'
          })  
          $tr.find('.bill_no').focus(); 
        }else{
          jQuery('.submit').attr('enable', true);
        }
      }
    });
  }


function confirmDelete(e) {
  var $i = $(e).attr("id");
  swal({
      title: "Are you sure?",
      text: "You will not be able to recover this imaginary file!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, delete it!",
      closeOnConfirm: false
  }, function (isConfirm) {
      if (!isConfirm) return;
      $.ajax({
          url: "mr/delete.php",
          type: "POST",
          data: 'delete='+$i,
          dataType: "json",
          success: function () {
            swal({title: "Deleted!", text: "Data successfully Deleted!", type: "success"},
              function(){ 
                location.reload();
              }
            );
          },

          error: function (xhr, ajaxOptions, thrownError) {
            swal("Error deleting!", "Please try again", "error");
          }
      });
  });
}
  function CheckLr(ele){
    var bill_no = $(ele).val();
    var vendor= $("#vendor_id").val();
    var $tr = jQuery(ele).closest('tr');
    $.ajax({
      'type': 'POST',
      'url': 'commission_Flag/CheckLr.php',
      'data': {
        'bill_no' : bill_no,
        'vendor': vendor
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 1) {
          $tr.find('.bill_no').val(result.bill_no);
          $tr.find('.bill_date').val(result.bill_date);
          $tr.find('.bill_from').val(result.bill_from);
          $tr.find('.bill_to').val(result.bill_to);
          $tr.find('.bill_net_amount').val(result.bill_net_amount);
          calculateFinalAmount();
          $.toast({
            heading: 'Error',
            text: 'OPPS...',
            showHideTransition: 'fade',
            position: 'top-right',
            icon: 'error'
          })  
          $tr.find('.bill_no').focus();
        }else{
          jQuery('.submit').attr('enable', true);
        }
      }
    });
  }

  function calculateFinalAmount() {
    var $product_wapper  = jQuery('#product-wapper').find('table tbody tr');
    var $product_wappers = jQuery('#product-wappers').find('table tbody tr');
    var $sub_wapper      = jQuery('#sub-wapper').find('table tbody tr');
    var $net_amt = 0;
    var $other_amnt = 0;
    $product_wapper.each(function(i, v) {
        $tmp_amt  = parseFloat(jQuery(v).find('.lr-amount').val());
        if ($tmp_amt == '' || $tmp_amt == undefined || isNaN($tmp_amt)) {
          $tmp_amt = 0;
        }
        $net_amt += $tmp_amt;

        $other  = parseFloat(jQuery(v).find('.other_charges').val());
        if ($other == '' || $other == undefined || isNaN($other)) {
          $other = 0;
        }
        $other_amnt += $other;
    });

   
    
    // add
    var $net_amts = 0;
    $product_wappers.each(function(i, v) {
      $add_amnt  = parseFloat(jQuery(v).find('.hitz_add').val());
        if ($add_amnt == '' || $add_amnt == undefined || isNaN($add_amnt)) {
          $add_amnt = 0;
        }
      $net_amts += $add_amnt;
    });
    $other_add  = $net_amts;
    
    // SUB
    var $sub_amnts = 0;
    $sub_wapper.each(function(i, v) {
      $sub_amnt  = parseFloat(jQuery(v).find('.hitz_subs').val());
        if ($sub_amnt == '' || $sub_amnt == undefined || isNaN($sub_amnt)) {
          $sub_amnt = 0;
        }
      $sub_amnts += $sub_amnt;
    });
    /* GST CALCULATION */

    $total_net_amount = $net_amt + $other_add;
    var $sgst = parseFloat(jQuery('#sgst_per').val());
    if ($sgst == '' || $sgst == undefined || isNaN($sgst)) {
      $sgst = 0;
    }
    
    var $cgst = parseFloat(jQuery('#cgst_per').val());
    if ($cgst == '' || $cgst == undefined || isNaN($cgst)) {
      $cgst = 0;
    }

    var $igst = parseFloat(jQuery('#igst_per').val());
    if ($igst == '' || $igst == undefined || isNaN($igst)) {
      $igst = 0;
    }


    if($sgst !='' || $cgst !=''){
      jQuery('input[name="igst_per"]').attr("readonly", "readonly");
    }else{
      jQuery('input[name="igst_per"]').removeAttr("readonly", "readonly");
    }

    if($igst !=''){
      jQuery('input[name="sgst_per"]').attr("readonly", "readonly");
      jQuery('input[name="cgst_per"]').attr("readonly", "readonly");
    }else{
      jQuery('input[name="sgst_per"]').removeAttr("readonly", "readonly");
      jQuery('input[name="cgst_per"]').removeAttr("readonly", "readonly");
    }

    $sgst_amount   = ($sgst * $total_net_amount)/100;
    $cgst_amount   = ($cgst * $total_net_amount)/100;
    $igst_amount   = ($igst * $total_net_amount)/100;
    
    $other_less       = $sub_amnts;
    $net_amount       = $net_amt + $other_add - $other_less + $other_amnt + $sgst_amount + $cgst_amount + $igst_amount;
    $total_amount     = $net_amt + $other_amnt;
    
    jQuery('#sgst_amount').val($sgst_amount.toFixed(2));
    jQuery('#cgst_amount').val($cgst_amount.toFixed(2));
    jQuery('#igst_amount').val($igst_amount.toFixed(2));

    jQuery('#other_add').val($other_add.toFixed(2));
    jQuery('#other_less').val($other_less.toFixed(2));
    jQuery('#total_amnt').val($total_amount.toFixed(2));
    jQuery('#gross_amnt').val($total_amount.toFixed(2));
    jQuery('#net_amnt').val($net_amount.toFixed(2));
  }

  
  function CheckLrData() {
    var vendor    = $("#vendor_id").val();
    $.ajax({
      'type': 'POST',
      'url': 'commission_Flag/CheckLrData.php',
      'data': {
        'vendor': vendor
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 1) {
          swal("Opps !!", "NO LR EXITS...!!!", "info")  
          setTimeout("location.reload(true);",2000);
        }else{
          jQuery('.submit').attr('enable', true);
        }
      }
    });
  };

  function CheckDuplicateRow(bill_no){
    var $container = jQuery('#product-wapper');
    var $check = true;
    jQuery.each($container.find('tbody tr'), function(i, v){
      var $tmp_data_count     = jQuery(v).find('.bill_cal').attr('data-count');
      var $tmp_bill_no        = jQuery('input[name="product['+ $tmp_data_count +'][bill_no]"]').val();
      if( $tmp_bill_no == bill_no) {
        $check = false;
        return false;
      }
    });
    if( $check ) {
            return true;
        } else {
          $.toast({
            heading: 'Error',
            text: 'ALREADY EXISTS ABOVE...',
            showHideTransition: 'fade',
            position: 'top-right',
            icon: 'error'
          })  
          return false;
        }
  }


  function CheckCode() {
    var bill_no      = $("#bill_no").val();
    $.ajax({
      'type': 'POST',
      'url': 'commission_Flag/check-code.php',
      'data': {
        'bill_no': bill_no
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 1) {
          swal("Opps !!", "ALREADY CODE EXIST...!!!", "info");
          setTimeout("location.reload(true);",2000);
          $('#bill_no').val('').trigger('focus');   
        }else{
          jQuery('.ajax-submit').attr('enable', true);
        }
      }
    });
  }

  function CheckNumberSeries() {
    var bill_no = $("#bill_no").val();
    var branch_id  = $("#branch_id").val();
    var module     = $("#module").val();
    $.ajax({
      'type': 'POST',
      'url': 'commission_Flag/check_number_series.php',
      'data': {
        'bill_no': bill_no,
        'branch_id': branch_id,
        'module': module
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 1) {
          jQuery('.ajax-submit').attr('disabled', false);
        }else{
          jQuery('.ajax-submit').attr('disabled', true);
          swal("Opps !!", "Not A Valid Bill Number", "info");
          setTimeout("location.reload(true);",2000);  
        }
      }
    });
  }

</script>