<?php
  if( !hasPermission($_SESSION['user_detail']['role_id'], 'bill_edit') ) {
    echo '<script>window.location.href="index.php?page=no_permission.php"</script>';die();
  }
  if (isset($_REQUEST['eid']) && !empty($_REQUEST['eid'])){
    $select_update     = "SELECT * FROM billing WHERE invoice_no='".$_REQUEST['eid']."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
    $select_update_res = mysqli_query($conn,$select_update);
    $update_row        = mysqli_fetch_array($select_update_res,MYSQLI_BOTH);
  }
  
  $bill     = "SELECT * FROM billing WHERE invoice_no='".$_REQUEST['eid']."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
  $bill_res = mysqli_query($conn,$bill);
?>
<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">UPDATE BILL</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'], 'bill_list') ) { ?>
          <a href="index.php?page=bill/list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW BILL 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">INVOICE NO</label><span style="color: red">*</span>
                        <?php 
                          if($codeType == 1){  ?>
                          <input type="text" size="35" id="invoice_no" name="invoice_no" class="form-control lr_number required" autocomplete="off" placeholder="INVOICE NO" autofocus=""  value="<?php echo $update_row['invoice_no'];?>" onChange="CheckNumberSeries(this.value);CheckCode(this.value);" readonly=""/>

                          <?php }else{ ?>
                          <input type="text" size="35" id="invoice_no" name="invoice_no" class="form-control lr_number" autocomplete="off" placeholder="INVOICE NO" value="<?php echo $update_row['invoice_no'];?>" readonly=""/>

                        <?php } ?>

                      </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);CheckLrData();VerifyLrData(this);">
                            <option></option>
                            <?php 
                              $truck     = "SELECT * FROM `vendor_master` WHERE `status` = '0'";
                              $truck_res = mysqli_query($conn,$truck);
                              while ($truck_row=mysqli_fetch_array($truck_res)) { ?>f
                              <option  <?php if($truck_row['id'] == $update_row['vendor_id']) { echo "selected='selected'"; } ?>  value="<?php echo $truck_row['id'] ?>"><?php echo $truck_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="bill_date" name="bill_date" class="form-control date-picker required" placeholder="DATE" autocomplete="off" value="<?php echo date('d-m-Y', strtotime($update_row['bill_date']));?>"onfocusout="CheckDate(this.value);" />
                          </div>
                      </div>
                   </div>
                </div>
                <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="5%">Status</th>
                            <th class="text-center" width="10%">LR 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%">HSN CODE</th>
                            <th class="text-center" width="10%">WEIGHT</th>
                            <th class="text-center" width="10%">PCS</th>
                            <th class="text-center" width="10%">RATE</th>
                            <th class="text-center" width="10%">AMOUNT</th>
                            <th class="text-center" width="10%">OTHER CHARGES</th>
                            <th class="text-center" width="10%">REMARK</th>
                          </tr>
                        </thead>
                        <tbody>
                        <?php 
                          $i = 0;
                          while ($lr_row   = mysqli_fetch_array($bill_res)) { ?>
                          <tr>
                            <td>
                              <a href="javascript:;" class="btn green btn-block add-more" style="display: none;"><i class="fa fa-plus"></i></a>
                              <a href="javascript:;" class="btn red btn-block remove-me" style="display: block;"><i class="fa fa-minus"></i></a>
                            </td>
                            <td><input type="text" name=""  value="" class="add-more-table form-control top mr_status" autocomplete="off">
                            </td>
                            <td id="lrno">
                              <input type="text" name="product[<?php echo $i; ?>][lr_no]" value="<?php echo $lr_row['lr_no'];?>" class="form-control product-name add-more-table bill_cal lr_no" placeholder="Search By LR NO" data-count="<?php echo $i;?>" onchange="CheckLr(this);CheckDuplicateRow(this);">
                            </td>
                            <td><input type="date" name="product[<?php echo $i; ?>][lr_date]" value="<?php echo $lr_row['lr_date'];?>" class="form-control lr-date add-more-table bill_cal" readonly></td>
                            
                            <td><input type="text" name="product[<?php echo $i; ?>][lr_from]" value="<?php echo $lr_row['lr_from'];?>" class="form-control lr-from add-more-table bill_cal" readonly></td>

                            <td><input type="text" name="product[<?php echo $i; ?>][lr_to]" value="<?php echo $lr_row['lr_to'];?>" class="form-control lr-to add-more-table bill_cal" readonly></td>

                            <td><input type="text" name="product[<?php echo $i; ?>][hsn_code]" value="<?php echo $lr_row['hsn_code'];?>" class="form-control hsn_code add-more-table bill_cal" ></td>
                            
                            <td><input type="text" name="product[<?php echo $i; ?>][lr_weight]" value="<?php echo $lr_row['lr_weight'];?>" class="form-control lr_weight add-more-table bill_cal" ></td>

                            <td><input type="text" name="product[<?php echo $i; ?>][lr_pcs]" value="<?php echo $lr_row['lr_pcs'];?>" class="form-control lr_pcs add-more-table bill_cal" readonly></td>
                            
                            <td><input type="text" name="product[<?php echo $i; ?>][lr_rate]" value="<?php echo $lr_row['lr_rate'];?>" class="form-control lr-rate add-more-table bill_cal" ></td>
                            

                            <td><input type="text" name="product[<?php echo $i; ?>][lr_amount]" value="<?php echo $lr_row['lr_amount'];?>" class="form-control lr-amount calc-amt add-more-table bill_cal"></td>

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

                            <td><input type="text" name="product[<?php echo $i; ?>][remark]" value="<?php echo $lr_row['remark'];?>" class="form-control calc-amt add-more-table bill_cal"></td>
                          </tr>
                          <?php $i++; }?>
                          <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><input type="text" name="" class="add-more-table form-control mr_status">
          </td>
                            <td id="lrno"><input type="text" name="product[<?php echo $i; ?>][lr_no]" value="" class="form-control product-name add-more-table bill_cal lr_no" placeholder="Search By LR NO" data-count="<?php echo $i;?>" onchange="CheckLr(this);CheckDuplicateRow(this);"></td>

                            <td><input type="date" name="product[<?php echo $i; ?>][lr_date]" value="" class="form-control lr-date add-more-table bill_cal" readonly></td>

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

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

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

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

                            <td><input type="text" name="product[<?php echo $i; ?>][lr_rate]"  value="" class="form-control lr-rate add-more-table bill_cal"></td>

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

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


                            <td><input type="text" name="product[<?php echo $i; ?>][remark]" class="form-control calc-amt add-more-table bill_cal"></td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
                <legend class="hitz-legend">PAYMENT DETAIL</legend>
                  <div class="row">
                    <div class="col-md-4">
                      <div class="col-md-12" id="product-wappers">
                        <table class="table table-bordered">
                            <tbody>
                              <?php
                                $tax =  "SELECT * FROM `tax_mst` WHERE `sign` = '+' AND FIND_IN_SET('BILL', module)";
                                $tax_res = mysqli_query($conn,$tax);

                                $tax_rows = array();
                                while($tax_row = mysqli_fetch_assoc($tax_res)) {
                                  $tax_rows[$tax_row['id']] = $tax_row['descr'];
                                }

                                $bill_data          = "SELECT * FROM billing_details WHERE bill_no='".$update_row['invoice_no']."' AND type = 'add' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
                                $bill_data_res      = mysqli_query($conn,$bill_data);
                                
                                $bill_det = array();
                                while ($bill_update_row    = mysqli_fetch_array($bill_data_res,MYSQLI_BOTH)) {
                                  $bill_det[$bill_update_row['key']] = array('id' => $bill_update_row['tax_mst_id'], 'amount' => $bill_update_row['amount']);
                                }
                              ?>

                              <?php for ($i=1; $i <=4 ; $i++) { ?>
                              <?php
                                $tmp_lc_detail = array();
                                if(isset($bill_det[$i])) {
                                  $tmp_lc_detail = $bill_det[$i];
                                }
                              ?>
                              <?php 
                                if(@$tmp_lc_detail['amount'] > 0){
                                  $style = '';
                                }else{
                                  $style = 'readonly';
                                }
                              ?>
                              <tr>
                                <td width="65%">
                                  <select class="form-control height29 chosen-select hitz-add" name="add[<?php echo $i ?>][tax_mst_id]" style="width: 100%;">
                                      <option value></option>
                                      <?php foreach ($tax_rows as $tax_row_id => $tax_row_desc) {
                                          ?>
                                      <option value="<?php echo $tax_row_id;?>" <?php echo ($tax_row_id == $tmp_lc_detail['id']) ? 'selected' : ''; ?>><?php echo $tax_row_desc;?></option>
                                      <?php } ?>
                                  </select>
                                </td>
                                <td><input type="text" name="add[<?php echo $i ?>][amount]" class="form-control hitz_add height29 payment-table number addition" value="<?php echo @$tmp_lc_detail['amount']; ?>" data-count="<?php echo $i ?>" data-count="<?php echo $i ?>" <?php echo $style;?> autocomplete="off"></td>
                                <input type="hidden" class="form-control" data-count="0" name="add[<?php echo $i; ?>][auto_add_id]" value="<?php echo $tmp_lc_detail['id'];?>">
                              </tr>
                              <?php } ?>
                              
                            </tbody>
                         </table>
                      </div>
                      <div class="col-md-12">
                      <table class="table table-bordered">
                        <tbody>
                          <tr>
                            <td width="35%;" align="center"><label class="capital">SGST</label></td>

                            <td width="25%;"><input type="text" id="sgst_per" name="sgst_per" class="form-control height29 number payment-table sgst_per gst-cal" autocomplete="off" placeholder="SGST(%)" value="<?php echo $update_row['sgst_per']?>"></td>
                            
                            <td><input type="text" name="sgst_amount" id="sgst_amount" class="form-control height29 number payment-table sgst_amount" autocomplete="off" placeholder="SGST(₹)" readonly="" value="<?php echo $update_row['sgst_amount']?>"></td>
                          </tr>
                          <tr>
                            <td width="35%;" align="center"><label class="capital">CGST</label></td>
                            <td width="25%;"><input type="text" id="cgst_per" name="cgst_per" class="form-control height29 number payment-table cgst_per gst-cal" autocomplete="off"  placeholder="CGST(%)" value="<?php echo $update_row['cgst_per']?>"></td>
                             <td><input type="text" name="cgst_amount" id="cgst_amount" class="form-control height29 number payment-table cgst_amount" autocomplete="off" placeholder="CGST(₹)" readonly="" value="<?php echo $update_row['cgst_amount']?>"></td>
                          </tr>
                          <tr>
                            <td width="35%;" align="center"><label class="capital">IGST</label></td>
                            <td width="25%;"><input type="text" id="igst_per" name="igst_per" class="form-control height29 number payment-table igst_per gst-cal" autocomplete="off"  placeholder="IGST(%)" value="<?php echo $update_row['igst_per']?>"></td>

                             <td><input type="text" name="igst_amount" id="igst_amount" class="form-control height29 number payment-table igst_amount" autocomplete="off" placeholder="IGST(₹)" readonly="" value="<?php echo $update_row['igst_amount']?>"></td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                    </div>
                    <div class="col-md-4">
                      <div class="col-md-12" id="sub-wapper">
                        <table class="table table-bordered">
                          <tbody>
                            <?php 
                            $d_tax =  "SELECT * FROM `tax_mst` WHERE `sign` = '-' AND FIND_IN_SET('BILL', module)";
                            $d_tax_res = mysqli_query($conn,$d_tax);
                            $s_tax_rows = array();
                            while($d_tax_row = mysqli_fetch_assoc($d_tax_res)) {
                              $s_tax_rows[$d_tax_row['id']] = $d_tax_row['descr'];
                            }

                            $bill_data_s          = "SELECT * FROM billing_details WHERE bill_no='".$update_row['invoice_no']."' AND type = 'sub' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
                            $bill_data_s_res      = mysqli_query($conn,$bill_data_s);
                                
                            $bill_dets = array();
                            while ($bill_updates_row    = mysqli_fetch_array($bill_data_s_res,MYSQLI_BOTH)) {
                              $bill_dets[$bill_updates_row['key']] = array('id' => $bill_updates_row['tax_mst_id'], 'amount' => $bill_updates_row['amount']);
                            }
                            
                            for ($i=1; $i <=4 ; $i++) { 
                            $tmp_lc_details = array();
                              if(isset($bill_dets[$i])) {
                                $tmp_lc_details = $bill_dets[$i];
                              }
                            ?>
                            <?php 
                              if(@$tmp_lc_details['amount'] > 0){
                                  $style = '';
                              }else{
                                $style = 'readonly';
                              }
                            ?>
                            <tr>
                              <td width="65%">
                                <select class="form-control chosen-select hitz-del height29" name="sub[<?php echo $i ?>][tax_mst_id]" style="width: 100%;">
                                  <option value></option>
                                  <?php foreach ($s_tax_rows as $dtax_row_id => $dtax_row_desc) { ?>
                                  <option value="<?php echo $dtax_row_id;?>" <?php echo ($dtax_row_id == $tmp_lc_details['id']) ? 'selected' : ''; ?>><?php echo $dtax_row_desc;?></option>
                                  <?php } ?>
                                </select>
                              </td>
                              
                              <td><input type="text" name="sub[<?php echo $i ?>][amount]" class="form-control hitz_subs height29 payment-table number cal deduction" value="<?php echo @$tmp_lc_details['amount'];?>" data-count="<?php echo $i ?>" <?php echo $style;?> autocomplete="off"></td>
                              <input type="hidden" class="form-control" data-count="0" name="sub[<?php echo $i; ?>][auto_sub_id]" value="<?php echo $tmp_lc_details['id'];?>">
                            </tr>
                            <?php } ?>
                          </tbody>
                        </table>
                      </div>
                      
                    </div>
                    <div class="col-md-4">
                      <div class="col-md-4">
                        <div class="form-group">
                          <label class="capital">TOTAL ADDITION</label>
                          <input type="text" size="35" id="other_add" name="other_add" class="form-control other_add" autocomplete="off" placeholder="TOTAL" readonly="" />
                        </div>
                      </div>
                      <div class="col-md-4">
                        <div class="form-group">
                          <label class="capital">TOTAL DEDUCTION</label>
                          <input type="text" size="35" id="other_less" name="other_less" class="form-control other_less" autocomplete="off" placeholder="TOTAL" readonly="" />
                        </div>
                      </div>
                      <div class="col-md-4">
                        <div class="form-group">
                          <label class="capital">TOTAL AMOUNT</label>
                          <input type="text" size="35" id="total_amnt" name="total_amnt" class="form-control" autocomplete="off" placeholder="TOTAL AMOUNT" readonly="" value="<?php echo $update_row['total_amnt'];?>"/>
                        </div>
                      </div>
                      <div class="col-md-4">
                        <div class="form-group">
                          <label class="capital">GROSS AMOUNT</label>
                          <input type="text" size="35" id="gross_amnt" name="gross_amnt" class="form-control" autocomplete="off" placeholder="GROSS AMOUNT" readonly="" value="<?php echo $update_row['gross_amt'];?>"/>
                        </div>
                      </div>
                      <div class="col-md-4">
                        <div class="form-group">
                          <label class="capital">NET AMOUNT</label>
                          <input type="text" size="35" id="net_amnt" name="net_amnt" class="form-control" autocomplete="off" placeholder="NET AMOUNT" readonly="" value="<?php echo $update_row['net_amt'];?>"/>
                          <input type="hidden" name="id" value="">
                        </div>
                      </div>
                      <div class="col-md-12">
                        <div class="form-group">
                          <label class="capital">remark</label>
                          <textarea class="form-control hit-textarea" autocomplete="off" name="remarks" id="remarks"><?php echo $update_row['remarks'];?></textarea>
                        </div>
                      </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="<?php echo $_GET['eid'];?>" 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=bill/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><input type="text" name="" class="add-more-table form-control mr_status">
          </td>
          <td id="lrno"><input type="text" name="product[%i%][lr_no]" class="form-control product-name add-more-table bill_cal lr_no" placeholder="Search By LR NO" onchange="CheckLr(this);CheckDuplicateRow(this);"></td>

          <td><input type="date" name="product[%i%][lr_date]" class="form-control lr-date add-more-table bill_cal" readonly></td>

          <td><input type="text" name="product[%i%][lr_from]" class="form-control lr-from add-more-table bill_cal" readonly></td>
          <td><input type="text" name="product[%i%][lr_to]" class="form-control lr-to add-more-table bill_cal" readonly></td>
          <td><input type="text" name="product[%i%][hsn_code]" class="form-control hsn_code  add-more-table bill_cal" readonly></td>
          <td><input type="text" name="product[%i%][lr_weight]" class="form-control lr_weight add-more-table bill_cal" ></td>
          <td><input type="text" name="product[%i%][lr_pcs]" class="form-control lr_pcs add-more-table bill_cal" readonly></td>
          <td><input type="text" name="product[%i%][lr_rate]" class="form-control lr-rate add-more-table bill_cal" ></td>
          
          <td><input type="text" name="product[%i%][lr_amount]" class="readonly table skipping using js" autocomplete="off"></td>

          <td><input type="text" name="product[%i%][other_charges]" class="add-more-table bill_cal form-control form-control calc-amt other_charges top " autocomplete="off"></td>
          <td><input type="text" name="product[%i%][remark]" class="form-control t_amnt add-more-table bill_cal" 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('.lr_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: "bill/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('.lr_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.mr_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.mr_no);
                            $(".cancel_btn").hide();
                            $(".view_bn").hide();
                            

                        }
                    }
                });
            },
            error: function() {
                
                console.log("Error inserting MR data.");
                
            }
        });
    });
});

  jQuery(document).ready(function() {
    calculateFinalAmount();
    $('#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");
    });

    $( "#from_place" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "lhc/get_from_place.php",
          type: 'post',
          dataType: "json",
          data: {
              search: request.term
          },
          success: function( data ) {
              response( data );
          }
        });
      },
      select: function (event, ui) {
        $('#from_place').val(ui.item.label);
        return false;
      }
    });

    $( "#to_place" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "lhc/get_to_place.php",
          type: 'post',
          dataType: "json",
          data: {
              search: request.term
          },
          success: function( data ) {
              response( data );
          }
        });
      },
      select: function (event, ui) {
        $('#to_place').val(ui.item.label);
        return false;
      }
    });

    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', '.hitz_add', function() {
      calculateFinalAmount();
    });

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

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

  });
  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: "bill/get_lr_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.lr_no, ui.item.id);
        if( $checkpoint ) {
          $parent.find('.product-name').val(ui.item.lr_no);
          $parent.find('.lr-date').val(ui.item.l_date);
          $parent.find('.lr-truck').val(ui.item.truck_no);
          $parent.find('.lr-from').val(ui.item.from_place);
          $parent.find('.lr-to').val(ui.item.to_place);
          $parent.find('.lr_weight').val(ui.item.weight);
          $parent.find('.lr_pcs').val(ui.item.pcs);
          $parent.find('.lr-rate').val(ui.item.rate);
          $parent.find('.lr-rate_on').val(ui.item.rate_on);
          $parent.find('.lr-amount').val(ui.item.freight);
        }else{
          var $this = jQuery(this);
          setTimeout(function(){
            $this.focus();
            $this.select();
          }, 100);
        }
        calculateFinalAmount();
        return false;
      }
    }).each(function() {
       $(this).autocomplete( 'instance' )._renderItem = function( ul, item ) {
          return $( "<li>" )
             .append( "<a><span>" + item.lr_no + '</span></a>' )
             .appendTo( ul );
        };
    });
  }
  
  function CheckLr(ele){
    var lr_no = $(ele).val();
    var vendor= $("#vendor_id").val();
    var $tr = jQuery(ele).closest('tr');
    $.ajax({
      'type': 'POST',
      'url': 'bill/CheckLr.php',
      'data': {
        'lr_no' : lr_no,
        'vendor': vendor
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 1) {
          $tr.find('.lr_no').val(result.lr_no);
          $tr.find('.lr-date').val(result.lr_date);
          $tr.find('.lr-from').val(result.lr_from);
          $tr.find('.lr-to').val(result.lr_to);
          $tr.find('.lr_weight').val(result.lr_weight);
          $tr.find('.lr_pcs').val(result.lr_pcs);
          $tr.find('.lr-rate').val(result.lr_rate);
          $tr.find('.lr-amount').val(result.lr_amount);
          $tr.find('.other_charges').val(result.other_charges);
          calculateFinalAmount();
          $.toast({
            heading: 'Error',
            text: 'OPPS...',
            showHideTransition: 'fade',
            position: 'top-right',
            icon: 'error'
          })  
          $tr.find('.lr_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': 'bill/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 +'][lr_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 VerifyLrData() {
    var $container = jQuery('#product-wapper');
    jQuery.each($container.find('tbody tr'), function(i, v){
      var $tmp_data_count  = jQuery(v).find('.bill_cal').attr('data-count');
      var $tmp_lr_no       = jQuery('input[name="product['+ $tmp_data_count +'][lr_no]"]').val();
      var $vendor          = $("#vendor_id").val();
      if($tmp_lr_no != ''){
        //console.log('ajax call');
        $.ajax({
        'type': 'POST',
        'url': 'bill/check_lr_verify.php',
        'data': {
          'vendor': $vendor,
          'lr_no': $tmp_lr_no
        },
        dataType: 'JSON',
        success: function (result) {
          if(result.status == 1) {
            swal("Opps !!", "THIS LR IS ANOTHER VENDOR...!!!", "info")  
            setTimeout("location.reload(true);",2000);
          }else{
            jQuery('.submit').attr('enable', true);
          }
        }
      });
      }
      /**/
      
    });
  };

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

  function CheckNumberSeries() {
    var invoice_no = $("#invoice_no").val();
    var branch_id  = $("#branch_id").val();
    var module     = $("#module").val();
    $.ajax({
      'type': 'POST',
      'url': 'bill/check_number_series.php',
      'data': {
        'invoice_no': invoice_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);  
        }
      }
    });
  }
  function CheckDate() {
   var bill_date      = $("#bill_date").val();
   $.ajax({
      'type': 'POST',
      'url': 'bill/check-date.php',
      'data': {
         'bill_date': bill_date
      },
      dataType: 'JSON',
      success: function (result) {
         if(result.status == 0) {
            swal("Opps !!", "Date should be between Financial Year...!!!", "info");
            setTimeout("location.reload(true);",2000);
            $('#bill_date').val('').trigger('focus');   
         }else{
            jQuery('.ajax-submit').attr('enable', true);
         }
      }
   });
}

</script>