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

  $trans = mysqli_query($conn, "SELECT * FROM `trans` WHERE `balance` > 0 GROUP BY act_code");

  $vendor_data   = array();
  while ($row  = mysqli_fetch_array($trans)) {
    $vendor = mysqli_query($conn, "SELECT * FROM `act_master` WHERE `act_code` = '".$row['act_code']."'");

    while ($rows = mysqli_fetch_assoc($vendor)) {
      $vendor_data[] = $rows;
    }
  }
  $master_vendor = combine(getAllRecords('vendor_master'), 'name', 'id');
  
?>
<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 MR</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'], 'mr_list') ) { ?>
          <a href="index.php?page=mr/list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW MR 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 method="post" enctype="multipart/form-data" class="" id="signupForm">
              <div class="row">
                 <div class="col-md-2">
                    <div class="form-group">
                      <label class="capital">MR NO</label><span style="color: red">*</span>
                      <?php 
                      if($codeType == 1){  ?>
                      <input type="text" size="35" id="mr_no" name="mr_no" class="form-control lr_number" autocomplete="off" placeholder="MR NO" onChange="CheckNumberSeries(this.value);CheckCode(this.value);" value="<?php echo ResetmrCode($conn,$financial_years);?>" autofocus=""/>

                      <?php }else{ ?>
                      <input type="text" size="35" id="mr_no" name="mr_no" class="form-control lr_number" autocomplete="off" placeholder="MR NO" value="<?php echo mrCode($conn);?>" autofocus="" 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);VerifyLrData(this);">
                      <option></option>
                      <?php foreach ($vendor_data as $datas) { ?>
                      <option value="<?php echo @$master_vendor[$datas['ac_name']]?>"><?php echo $datas['ac_name']?></option>
                      <?php } ?>
                      </select>
                      
                    </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="mr_date" name="mr_date" class="form-control date-picker required" placeholder="DATE" autocomplete="off" value="<?php echo date('d-m-Y')?>" />
                      </div>
                    </div>
                 </div>
              </div>
              <div class="row">
                <div class="col-xs-12 col-sm-12">
                  <div id="product-wapper" class="table-responsive">
                    <table class="table table-bordered">
                      <thead>
                        <tr>
                          <th class="text-center" width="2%">#</th>
                          <th class="text-center" width="3%">Status</th>
                          <th class="text-center" width="10%">BILL NO</th>
                          <th class="text-center" width="7%">DATE</th>
                          <th class="text-center" width="7%">FROM</th>
                          <th class="text-center" width="7%">TO</th>
                          <th class="text-center" width="7%">AMOUNT</th>
                          <th class="text-center" width="7%">DUE</th>
                          <th class="text-center" width="7%">RECEIVED</th>
                          <th class="text-center" width="5%">T.D.S.</th>
                          <th class="text-center" width="7%">CASH DISCOUNT</th>
                          <th class="text-center" width="7%">LATE DELIVERY</th>
                          <th class="text-center" width="5%">CLAIM</th>
                          <th class="text-center" width="10%">REMARKS</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><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; ?>][bill_no]" value="" class="add-more-table form-control top product-name bill_no bill_cal" placeholder="Search By Bill NO" data-count="<?php echo $i;?>" onchange="CheckBill(this);CheckDuplicateRow(this)">
                            </td>
                            <td><input type="text" name="product[<?php echo $i; ?>][bill_date]" value="" class="add-more-table form-control top bill_date bill_cal" readonly></td>
                            
                            <td><input type="text" name="product[<?php echo $i; ?>][bill_from]"  value="" class="add-more-table form-control top bill_from bill_cal" readonly></td>

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

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

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

                            </td>

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

                            <td><input type="text" name="product[<?php echo $i; ?>][tds]"  value="" class="add-more-table form-control top tds cal number bill_cal payment_amount" autocomplete="off">
                            </td>
                            <td><input type="text" name="product[<?php echo $i; ?>][cash_diss]"  value="" class="add-more-table form-control top cash_diss cal number bill_cal payment_amount" autocomplete="off">
                            </td>
                            <td><input type="text" name="product[<?php echo $i; ?>][late_delivery]"  value="" class="add-more-table form-control top late_delivery cal number bill_cal payment_amount" autocomplete="off">
                            </td>
                            <td><input type="text" name="product[<?php echo $i; ?>][claim]"  value="" class="add-more-table form-control top claim cal number bill_cal payment_amount" autocomplete="off">
                            </td>
                            <td><input type="text" name="product[<?php echo $i; ?>][remarks]"  value="" class="add-more-table form-control top remarks cal  payment_amount" autocomplete="off">
                            </td>
                            
                            <!-- <td><input type="text" name="product[<?php echo $i; ?>][bill_pending]" class="add-more-table form-control top bill_pending bill_cal" readonly></td> -->
                          </tr>
                          <?php $i++; ?>
                       </tbody>
                    </table>
                  </div>
                 </div>
              </div>
              <legend class="hitz-legend">PAYMENT DETAIL</legend>
                <div class="row">
                  <div class="col-md-3">
                    <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('MR', module)";
                              $tax_res = mysqli_query($conn,$tax);

                              $tax_rows = array();
                              while($tax_row = mysqli_fetch_assoc($tax_res)) {
                                $tax_rows[] = $tax_row;
                              }
                            ?>

                            <?php for ($i=1; $i <=4 ; $i++) { ?>
                             <tr>
                                <td>
                                   <select class="form-control hitz-add height29 chosen-select" name="add[<?php echo $i ?>][tax_mst_id]" style="width: 100%;" data-placeholder="SELECT" aria-required="true">
                                    <option value></option>
                                    <?php foreach ($tax_rows as $tax_row) { ?>
                                      <option value="<?php echo $tax_row['id'];?>"><?php echo $tax_row['descr'];?></option>
                                    <?php } ?>
                                   </select>
                                </td>
                                <td width="30%"><input type="text" name="add[<?php echo $i ?>][amount]" class="form-control hitz_add addition height29 payment-table number" data-count="<?php echo $i ?>" readonly=""></td>
                             </tr>
                            <?php } ?>
                            
                          </tbody>
                       </table>
                    </div>
                    <div class="col-md-12">
                       <div class="form-group">
                          <label class="capital">TOTAL</label>
                          <input type="text" size="35" id="other_add" name="other_add" class="form-control" autocomplete="off" readonly="" />
                       </div>
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="col-md-12" id="sub-wapper">
                       <table class="table table-bordered">
                          <tbody>
                            <?php for ($i=1; $i <=4 ; $i++) { ?>
                            <tr>
                              <td>
                                <?php 
                                  $d_tax =  "SELECT * FROM `tax_mst` WHERE `sign` = '-' AND FIND_IN_SET('MR', module)";
                                  $d_tax_res = mysqli_query($conn,$d_tax);
                                  $d_tax_rows = array();
                                  while($d_tax_row = mysqli_fetch_assoc($d_tax_res)) {
                                    $d_tax_rows[] = $d_tax_row;
                                  }
                                ?>
                                  <select class="form-control chosen-select hitz-del height29" name="sub[<?php echo $i ?>][tax_mst_id]" style="width: 100%;" data-placeholder="SELECT" aria-required="true">
                                    <option value></option>
                                    <?php foreach ($d_tax_rows as $d_tax_row) { ?>
                                    <option value="<?php echo $d_tax_row['id'];?>"><?php echo $d_tax_row['descr'];?></option>
                                    <?php } ?>
                                  </select>
                              </td>
                              <td width="20%"><input type="text" name="sub[<?php echo $i ?>][tax_per]" class="form-control hitz_tax deduction cal height29 payment-table number" data-count="<?php echo $i ?>" readonly=""></td>
                              
                              <td width="30%"><input type="text" name="sub[<?php echo $i ?>][amount]" class="form-control hitz_subs height29 payment-table number" readonly=""></td>
                            </tr>
                            <?php } ?>
                          </tbody>
                       </table>
                    </div>
                    <div class="col-md-12">
                      <div class="form-group">
                        <label class="capital">TOTAL</label>
                        <input type="text" size="35" id="other_less" name="other_less" class="form-control hitz_sub" autocomplete="off" readonly="" />
                      </div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="col-md-12">
                      <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=""/>

                        <input type="hidden" size="35" id="total_tds" name="total_tds" class="form-control" autocomplete="off" readonly=""/>

                        <input type="hidden" size="35" id="total_cash_diss" name="total_cash_diss" class="form-control" autocomplete="off" readonly=""/>

                        <input type="hidden" size="35" id="total_late_delivery" name="total_late_delivery" class="form-control" autocomplete="off" readonly=""/>

                        <input type="hidden" size="35" id="total_claim" name="total_claim" class="form-control" autocomplete="off" readonly=""/>
                        

                        <input type="hidden" size="35" id="total_received" name="total_received" class="form-control" autocomplete="off" placeholder="NET AMOUNT" readonly=""/>
                      </div>
                    </div>
                    <legend>PAYMENT MODE</legend>
                    <div class="col-md-12">
                      <div class="row">
                        <div class="col-md-2">
                          <div class="col-md-12">
                            <div class="form-group">
                              <label class="radio-inline fontradiobuttion">
                              <input type="checkbox" name="payment_type[]" value="C" class="required hit-cash"> <span class="label-text">CASH</span>
                              </label>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-5">
                          <div class="col-md-12">
                            <div class="form-group">
                              <label>AMOUNT</label>  
                              <input type="text" name="cash"  id="cash" class="form-control calc-amt payment_amount number" autocomplete="off" onchange="CheckCashAct(this);checknagativevalue(this)"/>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-5">
                          <div class="row">
                            <div class="form-group">
                              <label>NAME</label>  
                              <select name="cash_name" id="cash_name" class="form-control at-cash" style="width: 100%">
                                <option></option>
                                <?php 
                                   $truck     = "SELECT * FROM `act_master` WHERE `account_group` ='CASH'";
                                   $truck_res = mysqli_query($conn,$truck);
                                   while ($truck_row=mysqli_fetch_array($truck_res)) { ?>f
                                  <option value="<?php echo $truck_row['id']?>"><?php echo $truck_row['ac_name']?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="row">
                        <div class="col-md-2">
                          <div class="col-md-12">
                            <div class="form-group">
                              <label class="radio-inline fontradiobuttion">
                              <input type="checkbox" name="payment_type[]" value="B" class="required hit-bank"> <span class="label-text">BANK</span>
                              </label>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-5">
                          <div class="col-md-12">
                            <div class="form-group">
                              <label>AMOUNT</label>  
                              <input type="text" name="pay_mode_amnt" autocomplete= "off"  id="pay_mode_amnt" class="form-control payment_amount number number" autocomplete="off"/>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-5">
                          <div class="row">
                            <div class="form-group">
                              <label>MODE</label>  
                              <select name="payment_mode" id="payment_mode" class="form-control hit-payment_mode">
                                <option value="">-PAYMENT MODE-</option>
                                <option value="CHEQUE">CHEQUE</option>
                                <option value="NEFT">NEFT</option>
                                <option value="RTGS">RTGS</option>
                                <option value="IMPS">IMPS</option>
                                <option value="GPAY">GPAY</option>
                              </select>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="row">
                        <div class="col-lg-6" id="imps_number_div" style="display:none">
                          <div class="form-group">
                             <label class="capital">IMPS Transaction Number</label><span style="color: red"><sup>*</sup></span>
                             <input type="text" name="imps_number"  id="imps_number" class="form-control" autocomplete="off" />
                          </div>
                        </div>
                        <div class="col-lg-6" id="rtgs_number_div" style="display:none">
                          <div class="form-group">
                             <label class="capital">RTGS Transaction Number</label><span style="color: red"><sup>*</sup></span>
                             <input type="text" name="rtgs_number"  id="rtgs_number" class="form-control" autocomplete="off"/>
                          </div>
                        </div>
                        <div class="col-lg-6" id="neft_number_div" style="display:none">
                          <div class="form-group">
                             <label class="capital">NEFT Transaction Number</label><span style="color: red"><sup>*</sup></span>
                             <input type="text" name="neft_number"  id="neft_number" class="form-control" autocomplete="off"/>
                          </div>
                        </div>
                        <div class="col-lg-6" id="cheque_number_div" style="display:none">
                          <div class="form-group">
                             <label class="capital">Enter Cheque Number</label><span style="color: red"><sup>*</sup></span>
                             <input type="text" name="cheque_number"  id="cheque_number" class="form-control" autocomplete="off"/>
                          </div>
                        </div>
                        <div class="col-lg-6" id="cheque_date_div" style="display:none">
                          <div class="form-group">
                             <label class="capital">Enter Cheque Date</label>
                             <input type="text" name="cheque_date" autocomplete= "off"  id="cheque_date" class="form-control date-picker" autocomplete="off"/>
                          </div>
                        </div>
                        <div class="col-lg-6" id="bank_name_div" style="display:none">
                          <div class="form-group">
                             <label class="capital">Bank Name</label>
                             <select name="bank_name" id="bank_name" class="form-control at-bank" style="width: 100%">
                                <option></option>
                                <?php 
                                   $truck     = "SELECT * FROM `act_master` WHERE `account_group` ='BANK'";
                                   $truck_res = mysqli_query($conn,$truck);
                                   while ($truck_row=mysqli_fetch_array($truck_res)) { ?>f
                                <option value="<?php echo $truck_row['id']?>"><?php echo $truck_row['ac_name']?></option>
                                <?php } ?>
                             </select>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                  </div>
                  <div class="col-md-2">
                    <legend>CUSTOMER CHEQUE DETAILS</legend>
                    <div class="col-md-12">
                       <div class="form-group">
                          <label class="capital">BANK NAME</label>
                          <input type="text" name="customer_bank_name" id="customer_bank_name" class="form-control" autocomplete="off" />
                       </div>
                    </div>
                    <div class="col-md-12">
                       <div class="form-group">
                          <label class="capital">BANK BRANCH</label>
                          <input type="text" name="customer_bank_branch" id="customer_bank_branch" class="form-control" autocomplete="off" />
                       </div>
                    </div>
                    <div class="col-md-12">
                       <div class="form-group">
                          <label class="capital">CHEQUE DATE</label>
                          <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="customer_cheque_date" name="customer_cheque_date" class="form-control date-picker" placeholder="DATE" autocomplete="off"/>
                          </div>
                       </div>
                    </div>
                    <div class="col-md-12">
                       <div class="form-group">
                          <label class="capital">CHEQUE NO</label>
                          <input type="text" name="customer_cheque_no" id="customer_cheque_no" class="form-control" autocomplete="off" />
                       </div>
                    </div>                    
                  </div>
                </div>
                <input type="hidden" value="<?php echo $_SESSION['branch_id'];?>" name="branch_id" id="branch_id">
                <input type="hidden" value="MR" 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=mr/list.php" class="btn btn-success capital  view_bn" style="display:none;">VIEW ALL MR</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%][bill_no]" class="add-more-table form-control product-name top bill_no 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 form-control bill_date top bill_cal" readonly></td>

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

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

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

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

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

          <td><input type="text" name="product[%i%][bill_rec]" class="add-more-table form-control bill_rec cal top number bill_cal payment_amount">
          </td>
          <td><input type="text" name="product[%i%][tds]" class="add-more-table form-control tds bill_rec cal top number bill_cal payment_amount">
          </td>
          <td><input type="text" name="product[%i%][cash_diss]" class="add-more-table form-control cash_diss bill_rec cal top number bill_cal payment_amount">
          </td>
          <td><input type="text" name="product[%i%][late_delivery]" class="add-more-table form-control late_delivery cal top number bill_cal payment_amount">
          </td>
          <td><input type="text" name="product[%i%][claim]" class="add-more-table form-control claim cal top number bill_cal payment_amount">
          </td>
          <td><input type="text" name="product[%i%][remarks]" class="add-more-table form-control remarks cal top bill_cal payment_amount">
          </td>
          
          <!-- <td><input type="text" name="product[%i%][bill_pending]"  class="add-more-table form-control bill_pending top bill_cal" readonly></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: "mr/insert.php",
            type: "post",
            data: formData,
            success: function(data) {
                var response = JSON.parse(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.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.");
                
            }
        });
    });
});

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");
          }
      });
  });
}






  jQuery(document).ready(function() {
    $('#vendor_id').select2();
    $('#hitz').select2();
    $('#cash_name').select2();
    $(".chosen-select").chosen({disable_search_threshold: 1});
    $( "#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();

       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();
    });

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

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

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

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

    $(document).on('change', '.bill_cal', function() {
      checknagative();
    });

    $(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');

      jQuery('input[name="add[' + $trs + '][amount]"]').removeAttr("readonly", "readonly");
    });
   
    $('#payment_mode').on('change', function() {
      if (this.value == 'CASH') {
        $("#cash_div").show();
        $("#cheque_date_div").hide();
        $("#cheque_deposite_div").hide();
        $("#bank_name_div").hide();
        $("#bank_branch_div").hide();
        $("#cheque_status_div").hide();
        $("#neft_number_div").hide();
        $("#rtgs_number_div").hide();
        $("#imps_number_div").hide();
        $("#amount_div").show();
      }else if (this.value == 'CHEQUE') {
        $("#cheque_number_div").show();
        $("#cheque_date_div").show();
        $("#cheque_deposite_div").show();
        $("#bank_name_div").show();
        $("#bank_branch_div").show();
        $("#cheque_status_div").show();
        $("#neft_number_div").hide();
        $("#rtgs_number_div").hide();
        $("#imps_number_div").hide();
        $("#cash_div").hide();
        $("#amount_div").show();      
      }else if (this.value == 'NEFT'){
        $("#neft_number_div").show();
        $("#rtgs_number_div").hide();
        $("#imps_number_div").hide();
        $("#cheque_date_div").hide();
        $("#cheque_deposite_div").hide();
        $("#bank_name_div").show();
        $("#bank_branch_div").hide();
        $("#cheque_status_div").hide();
        $("#cheque_number_div").hide();
        $("#rtgs_number").val('');
        $("#cheque_number").val('');
        $("#cheque_date").val('');
        $("#bank_name").val('').trigger('change');
        $("#bank_branch").val('');
        $("#cheque_status").val('');
        $("#cash_div").hide();
        $("#amount_div").show();
      } else if (this.value == 'RTGS'){
        $("#rtgs_number_div").show();
        $("#neft_number_div").hide();
        $("#imps_number_div").hide();
        $("#cheque_date_div").hide();
        $("#cheque_deposite_div").hide();
        $("#bank_name_div").show();
        $("#bank_branch_div").hide();
        $("#cheque_status_div").hide();
        $("#cheque_number_div").hide();
        $("#neft_number").val('');
        $("#cheque_number").val('');
        $("#cheque_date").val('');
        $("#bank_name").val('').trigger('change');
        $("#bank_branch").val('');
        $("#cheque_status").val('');
        $("#cash_div").hide();
        $("#amount_div").show();
      } else if (this.value == 'IMPS'){
        $("#imps_number_div").show();
        $("#rtgs_number_div").hide();
        $("#neft_number_div").hide();
        $("#cheque_date_div").hide();
        $("#cheque_deposite_div").hide();
        $("#bank_name_div").show();
        $("#bank_branch_div").hide();
        $("#cheque_status_div").hide();
        $("#cheque_number_div").hide();
        $("#rtgs_number").val('');
        $("#neft_number").val('');
        $("#cheque_number").val('');
        $("#cheque_date").val('');
        $("#bank_name").val('').trigger('change');
        $("#bank_branch").val('');
        $("#cheque_status").val('');
        $("#cash_div").hide();
        $("#amount_div").show();
      } else if (this.value == 'DD') {
        $("#cheque_number_div").show();
        $("#cheque_date_div").show();
        $("#cheque_deposite_div").show();
        $("#bank_name_div").show();
        $("#bank_branch_div").show();
        $("#cheque_status_div").show();
        $("#neft_number_div").hide();
        $("#rtgs_number_div").hide();
        $("#imps_number_div").hide();
        $("#cash_div").hide();
        $("#amount_div").show();
      } else {
        $("#payment_collection_date").val('');
        $("#imps_number_div").hide();
        $("#imps_number").val('');
        $("#rtgs_number_div").hide();
        $("#rtgs_number").val('');
        $("#neft_number_div").hide();
        $("#neft_number").val('');
        $("#cheque_number_div").hide();
        $("#cheque_number").val('');
        $("#cheque_date_div").hide();
        $("#cheque_deposite_div").hide();
        $("#cheque_date").val('');
        $("#bank_name_div").hide();
        $("#bank_name").val('').trigger('change');
        $("#bank_branch_div").hide();
        $("#bank_branch").val('');
        $("#cheque_status_div").show();
        $("#cheque_status").val('');
        $("#cash_div").hide();
        $("#amount_div").show();
      }
    });
    
    /*AUTO CHECK*/
    $('.payment_amount').on('keyup', function() {
      var $cash = parseFloat(jQuery('#cash').val());
      if ($cash == '' || $cash == undefined || isNaN($cash)) {
          $cash = 0;
      }
      
      jQuery('.hit-cash').prop("checked", false).iCheck('update');
      jQuery('.at-cash').removeClass('required');
      if($cash > 0) {
        jQuery('.hit-cash').prop("checked", true).iCheck('update');
        jQuery('.at-cash').addClass('required');
      }
      
      var $bank = parseFloat(jQuery('#pay_mode_amnt').val());
      if ($bank == '' || $bank == undefined || isNaN($bank)) {
          $bank = 0;
      }
      jQuery('.hit-bank').prop("checked", false).iCheck('update');
      jQuery('.at-bank').removeClass('required');
      jQuery('.hit-payment_mode').removeClass('required');
      if($bank > 0) {
        jQuery('.hit-bank').prop("checked", true).iCheck('update');
        jQuery('.at-bank').addClass('required');
        jQuery('.hit-payment_mode').addClass('required');
      }
    });

    $('#payment_mode').select2();
    $('#bank_name').select2();
    $(document).on('keyup', ".cal", function() {
      var $id = jQuery(this).closest('tr').find('.product-name').attr('data-count');
      var $ids = jQuery(this).closest('tr').find('.deduction').attr('data-count');
      //calculateAmount($id);
      calculateFinalAmount($ids);
      //CheckDuplicateRow($id);
    });

    $(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 get_Party_details(str) {
    if (str=="") {
      document.getElementById("lrno").innerHTML="";
      return;
    } 
    if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();
    } else { 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (this.readyState==4 && this.status==200) {
        document.getElementById("lrno").innerHTML=this.responseText;
      }
    }
    xmlhttp.open("GET","mr/get_lr_details.php?q="+str,true);
    xmlhttp.send();
  }
  
  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: "mr/get_bill.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.voucher_no, ui.item.id);
        if( $checkpoint ) {
          $parent.find('.product-name').val(ui.item.voucher_no);
          $parent.find('.bill_date').val(ui.item.v_date);
          $parent.find('.bill_from').val(ui.item.l_from);
          $parent.find('.bill_to').val(ui.item.l_to);
          $parent.find('.bill_amnt').val(ui.item.amount);
          $parent.find('.bill_due').val(ui.item.balance);
          $parent.find('.bill_due_hidden').val(ui.item.balance);
          
          //$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.voucher_no + '</span></a>' )
             .appendTo( ul );
        };
    });
  }
  
    function calculateFinalAmount($ids) {
    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 $bra = 0;
    var $total_tds = 0;
    var $total_cash_diss = 0;
    var $total_late_delivery = 0;
    var $total_claim = 0;
    
    $product_wapper.each(function(i, v) {
      var $indi_tds = 0;
      $bill_amnt  = parseFloat(jQuery(v).find('.bill_amnt').val());
      if ($bill_amnt == '' || $bill_amnt == undefined || isNaN($bill_amnt)) {
        $bill_amnt = 0;
      }

      $bill_received  = parseFloat(jQuery(v).find('.bill_rec').val());
      if ($bill_received == '' || $bill_received == undefined || isNaN($bill_received)) {
        $bill_received = 0;
      }

      $tds  = parseFloat(jQuery(v).find('.tds').val());
      if ($tds == '' || $tds == undefined || isNaN($tds)) {
        $tds = 0;
      }
      
      $cash_diss   = parseFloat(jQuery(v).find('.cash_diss').val());
      if ($cash_diss  == '' || $cash_diss  == undefined || isNaN($cash_diss)) {
        $cash_diss  = 0;
      }

      $late_delivery  = parseFloat(jQuery(v).find('.late_delivery').val());
      if ($late_delivery == '' || $late_delivery == undefined || isNaN($late_delivery)) {
        $late_delivery = 0;
      }

      $claim  = parseFloat(jQuery(v).find('.claim').val());
      if ($claim == '' || $claim == undefined || isNaN($claim)) {
        $claim = 0;
      }

      $bill_pen  = parseFloat(jQuery(v).find('.bill_due').val());
      if ($bill_pen == '' || $bill_pen == undefined || isNaN($bill_pen)) {
        $bill_pen = 0;
      }

      $bill_due_hidden  = parseFloat(jQuery(v).find('.bill_due_hidden').val());
      if ($bill_due_hidden == '' || $bill_due_hidden == undefined || isNaN($bill_due_hidden)) {
        $bill_due_hidden = 0;
      }

      
      $balance        = $bill_due_hidden - $bill_received - $tds - $cash_diss - $late_delivery - $claim;
      jQuery(v).find('.bill_due').val($balance.toFixed(2));
      $bra       += $bill_received;
      $total_tds += $tds;
      $total_cash_diss += $cash_diss;
      $total_late_delivery += $late_delivery;
      $total_claim += $claim;

    });

    // 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 = 0;
      $sub_per    = parseFloat(jQuery(v).find('.hitz_tax').val());
      if ($sub_per == '' || $sub_per == undefined || isNaN($sub_per)) {
        $sub_per = 0;
      }
      if($sub_per > 0) {
        $sub_amnt  = ($bra * $sub_per) / 100;  
        jQuery(v).find('.hitz_subs').val($sub_amnt.toFixed(2));
      }

      
      $sub_amnts += $sub_amnt;
    });
    
    $other_less    = $sub_amnts;

    $net_amount = $bra + $other_add - $other_less;
    
    var $cash = parseFloat(jQuery('#cash').val());
    if ($cash == '' || $cash == undefined || isNaN($cash)) {
      $cash = 0;
    }

    var $pay_mode_amnt = parseFloat(jQuery('#pay_mode_amnt').val());
    if ($pay_mode_amnt == '' || $pay_mode_amnt == undefined || isNaN($pay_mode_amnt)) {
      $pay_mode_amnt = 0;
    }
    $rem = $net_amount - $cash;
    jQuery('#total_received').val($bra.toFixed(2));
    jQuery('#total_tds').val($total_tds.toFixed(2));
    jQuery('#total_cash_diss').val($total_cash_diss.toFixed(2));
    jQuery('#total_late_delivery').val($total_late_delivery.toFixed(2));
    jQuery('#total_claim').val($total_claim.toFixed(2));
    jQuery('#other_add').val($other_add.toFixed(2));
    jQuery('#other_less').val($other_less.toFixed(2));
    jQuery('#net_amnt').val($net_amount.toFixed(2));
    jQuery('#pay_mode_amnt').val($rem.toFixed(2));
    document.getElementById('pay_mode_amnt').setAttribute('max', $rem);
    document.getElementById('cash').setAttribute('max', $net_amount);
  }

  function CheckBill(ele){
     
    var bill_no = $(ele).val();
    var $tr = jQuery(ele).closest('tr');
    $.ajax({
      'type': 'POST',
      'url': 'mr/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 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 CheckCashAct(ele){
    $.ajax({
      'type': 'POST',
      'url': 'mr/check_cash_act.php',
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 0) {
          swal("Opps !!", "ACCOUNT NOT DETECT...!!!", "info")
          setTimeout("location.reload(true);",2000); 
        }else{
          jQuery('.submit').attr('enable', true);
        }
      }
    });
  }

  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_bill_no        = jQuery('input[name="product['+ $tmp_data_count +'][bill_no]"]').val();
      var $vendor          = $("#vendor_id").val();
      if($tmp_bill_no != ''){
        //console.log('ajax call');
        $.ajax({
        'type': 'POST',
        'url': 'mr/check_bill_verify.php',
        'data': {
          'vendor': $vendor,
          'lr_no': $tmp_bill_no
        },
        dataType: 'JSON',
        success: function (result) {
          if(result.status == 1) {
            swal("Opps !!", "THIS BILL IS ANOTHER VENDOR...!!!", "info")  
            setTimeout("location.reload(true);",2000);
          }else{
            jQuery('.submit').attr('enable', true);
          }
        }
      });
      }
      /**/
      
    });
  };

  function checknagative(){
    var $product_wapper  = jQuery('#product-wapper').find('table tbody tr');
    var $bra = 0;
    $product_wapper.each(function(i, v) {
      $bill_amnt  = parseFloat(jQuery(v).find('.bill_amnt').val());
      if ($bill_amnt == '' || $bill_amnt == undefined || isNaN($bill_amnt)) {
        $bill_amnt = 0;
      }

      $bill_received  = parseFloat(jQuery(v).find('.bill_rec').val());
      if ($bill_received == '' || $bill_received == undefined || isNaN($bill_received)) {
        $bill_received = 0;
      }

      $tds  = parseFloat(jQuery(v).find('.tds').val());
      if ($tds == '' || $bill_received == undefined || isNaN($bill_received)) {
      }

      


      $due        = $bill_amnt - $bill_received ; 

      $bill_pen  = parseFloat(jQuery(v).find('.bill_due').val());
      if ($bill_pen == '' || $bill_pen == undefined || isNaN($bill_pen)) {
        $bill_pen = 0;
      }
      
      $bill_due_hidden  = parseFloat(jQuery(v).find('.bill_due_hidden').val());
      if ($bill_due_hidden == '' || $bill_due_hidden == undefined || isNaN($bill_due_hidden)) {
        $bill_due_hidden = 0;
      }
      
      if($bill_pen < $bill_received){
        jQuery(v).find('.bill_rec').addClass('max-validation').attr('max',$bill_due_hidden); 
      }else{
        jQuery(v).find('.bill_rec').removeClass('max-validation');
      }
    });
  }
  function checknagativevalue(ele){
    var $net_amnt = parseFloat(jQuery('#net_amnt').val());
    if ($net_amnt == '' || $net_amnt == undefined || isNaN($net_amnt)) {
        $net_amnt = 0;
    }

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

    var $bank = parseFloat(jQuery('#pay_mode_amnt').val());
    if ($bank == '' || $bank == undefined || isNaN($bank)) {
        $bank = 0;
    }
    
    if($bank < $cash){
      jQuery('#cash').addClass('max-validation').attr('max',$net_amnt); 
    }else{
      jQuery('#cash').removeClass('max-validation');
    }
  }

  function CheckCode() {
    var lr_no      = $("#mr_no").val();
    $.ajax({
      'type': 'POST',
      'url': 'mr/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 mr_no = $("#mr_no").val();
    var branch_id  = $("#branch_id").val();
    var module     = $("#module").val();
    $.ajax({
      'type': 'POST',
      'url': 'mr/check_number_series.php',
      'data': {
        'mr_no': mr_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 Mr Number", "info");
          setTimeout("location.reload(true);",2000);  
        }
      }
    });
  }
</script>
