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

if($_GET['type'] != 'truck' && $_GET['type'] != ''){
   $page       = 'truck';
   $truck_no   = '';
}else{
   $page       = 'lr';
   $truck_no   = $_GET['no'];
}

$vendor     = "SELECT * FROM `vendor_master` WHERE `status` = '0' and type = 'V' ORDER BY name ASC";
$vendor_res = mysqli_query($conn,$vendor);

$vendors      = "SELECT * FROM `vendor_master` WHERE `status` = '0'  and type = 'V' ORDER BY name ASC";
$vendor_resu  = mysqli_query($conn,$vendors);

$bill     = "SELECT * FROM `vendor_master` WHERE `status` = '0'  and type = 'V' ORDER BY name ASC";
$bill_res = mysqli_query($conn,$bill);

$agent = mysqli_query($conn, "SELECT * FROM `vendor_master` WHERE `type` = 'A' AND `status` = '0' ORDER BY name ASC");
$agent_data = array();
while ($agent_row = mysqli_fetch_assoc($agent)) {
 $agent_data[] = $agent_row;
}   
$branch = "SELECT * FROM `branch_mst` WHERE `id` = '".$_SESSION['branch_id']."'";
   $bra_res = mysqli_query($conn,$branch);
   $bra_row = mysqli_fetch_array($bra_res);
?>
<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>
 <style>
      .datepicker {
         z-index: 1051 !important;
      }

      /* Optional: for Bootstrap Datepicker dropdown */
      .datepicker-dropdown {
         z-index: 9999 !important;
      }

      /* Optional: for jQuery UI Datepicker */
      .ui-datepicker {
         z-index: 9999 !important;
      }
   </style>
<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 LR</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'], 'lr_list') ) { ?>
               <a href="index.php?page=lr/list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW LR 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 action="lr/insert.php" method="post" 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">LR TYPE</label><span style="color: red">*</span><br>
                          <label class="radio-inline fontradiobuttion">
                           <input class="type lr_type" type="radio" name="lr_type" value="D" <?php if($type=='D'){echo "checked";}?>> <span class="label-text">DUMMY</span>
                        </label>
                        <label class="radio-inline fontradiobuttion">
                           <input class="type lr_type" type="radio" name="lr_type" value="O" <?php if($type=='O'){echo "checked";}?> checked=""> <span class="label-text">ORIGINAL</span>
                        </label>
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">truck no</label><span style="color: red">*</span>
                        <input type="text" size="35" id="truck_no" name="truck_no" class="form-control" autofocus="" autocomplete="off" onchange="get_Truck_weight(this);"/>
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">LR.NO</label><span style="color: red">*</span>
                        <!-- <input type="text" size="35" id="lr_no" name="lr_no" class="form-control lr_number" autocomplete="off" placeholder="LR.NO" onChange="CheckLr(this.value);" /> -->
                        <?php 
                        if($codeType == 1){  ?>
                           <input type="text" size="35" id="lr_no" name="lr_no" class="form-control lr_number required" autocomplete="off" placeholder="LR.NO" value="<?php echo lrCode($conn);?>" onChange="CheckNumberSeries(this.value);CheckCode(this.value);"/>
                        <?php }else{ ?>
                           <input type="text" size="35" id="lr_no" name="lr_no" class="form-control lr_number required" autocomplete="off" placeholder="LR.NO" value="<?php echo lrCode($conn);?>" onChange="CheckCode(this.value);" autofocus="" readonly=""/>
                        <?php } ?>
                     </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="l_date" name="l_date" class="form-control required" placeholder="DATE" autocomplete="off" value="<?php echo date('d-m-Y')?>" onchange="CheckDate(this.value);"/>
                        </div>
                     </div>
                  </div>
                 
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">FROM PLACE</label><span style="color: red">*</span>
                        <input type="text" size="35" id="from_place" name="from_place" class="form-control required" autocomplete="off" placeholder="FROM PLACE" value="<?php echo $from_place;?>" />
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">TO PLACE</label><span style="color: red">*</span>
                        <input type="text" size="35" id="to_place" name="to_place" class="form-control required" autocomplete="off" placeholder="TO PLACE" />
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-1">
                     <div class="form-group">
                        <label class="capital">INVOICE</label>
                        <input type="text" size="35" id="party_invoice" name="party_invoice" class="form-control" autocomplete="off"/>
                     </div>
                  </div>
                  <div class="col-md-1">
                     <div class="form-group">
                        <label class="capital">INV.AMOUNT</label>
                        <input type="text" size="35" id="party_amount" name="party_amount" class="form-control number" autocomplete="off"/>
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">INVOICE 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="invoice_date" name="invoice_date" class="form-control" autocomplete="off"/>
                        </div>
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">EWAY BILL NO</label> 
                        <input type="text" name="eway_bill_no" id="eway_bill_no" class="form-control">
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">EWAY BILL 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="eway_date" name="eway_date" class="form-control"  autocomplete="off"/>
                        </div>
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">EWAY EX. 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="eway_ex_date" name="eway_ex_date" class="form-control"  autocomplete="off"/>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">Challan No</label> 
                        <input type="text" name="challan_no" id="challan_no" class="form-control"  autocomplete="off">
                     </div>

                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">challan 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="po_date" name="po_date" class="form-control" autocomplete="off"/>
                        </div>
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">METHOD OF PACKING</label> 
                        <input type="text" name="packing" id="packing" class="form-control"  autocomplete="off">
                     </div>

                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">Vehicle TYPE</label> 
                        <input type="text" name="lorry_type" id="lorry_type" class="form-control"  autocomplete="off">
                     </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">Weight</label> 
                        <input type="text" name="weight" id="weight" class="form-control"  autocomplete="off">
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">insurance Status</label> 
                        <input type="text" name="insurance_status" id="insurance_status" class="form-control"  autocomplete="off">
                     </div>

                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">Insurance 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="insurance_date" name="insurance_date" class="form-control" autocomplete="off"/>
                        </div>
                     </div>
                  </div>
                          <div class="col-md-2">
                              <div class="form-group">
                                 <label class="capital">Issured by </label> 
                                 <input type="text" name="insured_by" id="insured_by" class="form-control" >
                           </div>
                        </div>
                          <div class="col-md-2">
                              <div class="form-group">
                                 <label class="capital">POLICY NO</label> 
                                 <input type="text" name="policy_no" id="policy_no" class="form-control">
                           </div>
                        </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">NOTES</label> 
                        <input type="text" name="notes" id="notes" class="form-control"  autocomplete="off">
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-2">
                        <div class="form-group">
                           <label class="capital">LR MODE</label> 
                           <select class="form-control select2 " name="lr_mode" id="lr_mode">
                              <option></option>
                              <option value="NONE">NONE</option>
                              <option value="TO BE BILLED">TO BE BILLED</option>
                              <option value="PAID">PAID</option>
                              <option value="TO PAY">TO PAY</option>
                              <option value="TO PAY">FOC</option>
                           </select>
                        </div>
                  </div>
                  <div class="col-md-2">
                     <div class="form-group">
                        <label class="capital">delivery</label> 
                        <select class="form-control select2 delivery" name="delivery" id="delivery">
                           <option></option>
                           <option value="DOOR">DOOR DELIVERY</option>
                           <option value="GODOWN">GODOWN DELIVERY</option>
                        </select>
                     </div>
                  </div>
                    <div class="col-md-2">
                      <div class="form-group">
                         <label class="capital"> Transport MODE</label> 
                           <input type="text" name="mode" id="mode" class="form-control">
                      </div>
                    </div>
               </div>
               <div class="row">
                 <div class="col-md-2">
                    <div class="form-group">
                     <label class="capital ">Billing Party</label>
                     <select class="form-control select2" name="billing_party" id="billing_party" onchange="CopyData(this.value)">
                      <option></option>
                      <option value="CONSIGNOR">CONSIGNOR</option>
                      <option value="CONSIGNEE">CONSIGNEE</option>
                      <option value="TRANSPORTER">TRANSPORTER</option>
                      <option value="OTHER">OTHER</option>
                      <option value="TO PAY">TO PAY</option>
                   </select>
                </div>
             </div>
             <div class="col-md-2">
              <div class="form-group">
               <label class="capital control-label">GST PAID BY</label>
               <select class="form-control" name="gst_paid_by" id="gst_paid_by">
                <option></option>
                <option value="CONSIGNOR">CONSIGNOR</option>
                <option value="CONSIGNEE">CONSIGNEE</option>
                <option value="TRANSPORTER">TRANSPORTER</option>
                <option value="OTHER">OTHER</option>
                <option value="NOT APPLICABLE">NOT APPLICABLE</option>
             </select>
          </div>
       </div>
       
    </div>
    <div class="row">
      <div class="col-md-4">
         <legend class="capital hitz-legend">CONSIGNOR</legend>
         <div class="col-md-12">
            <div class="form-group">
               <label class="capital">name</label><span style="color: red">*</span>
               <input class="form-control required" name="consignor_name" id="consignor_name" autocomplete="off"
               onchange="get_consignor_name_data(this); get_consignor_name_data2(this);"/>
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <textarea class="form-control hitz-text-height" name="consignor_address" id="consignor_address" readonly="" style="height: 64px !important;"></textarea> 
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignor_city" id="consignor_city" class="form-control get_city" placeholder="CITY" readonly=""/>  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignor_contact" id="consignor_contact" class="form-control" placeholder="CONTACT" readonly=""/>  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignor_pan" id="consignor_pan" class="form-control" placeholder="PAN" readonly=""/>  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignor_gst" id="consignor_gst" class="form-control" placeholder="GST" readonly=""/>  
            </div>
         </div>
      </div>
      <div class="col-md-4">
         <legend class="capital hitz-legend">CONSIGNEE</legend>
         <div class="col-md-12">
            <div class="form-group">
               <label class="capital">name</label><span style="color: red">*</span>
               <input class="form-control required" name="consignee_name" id="consignee_name" autocomplete="off"
               onchange="get_consignee_name_data(this); get_consignee_name_data2(this);"/>
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <textarea class="form-control hitz-text-height" name="consignee_address" id="consignee_address"  style="height: 64px !important;"></textarea> 
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignee_city" id="consignee_city" class="form-control" placeholder="CITY" />  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignee_contact" id="consignee_contact" class="form-control" placeholder="CONTACT" />  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignee_pan" id="consignee_pan" class="form-control" placeholder="PAN" />
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="consignee_gst" id="consignee_gst" class="form-control" placeholder="GST" />  
            </div>
         </div>
      </div>
      <div class="col-md-4">
         <legend class="capital hitz-legend">BILLING TO</legend>
         <div class="col-md-12">
            <div class="form-group">
               <label class="capital">name</label>
               <select class="form-control select2" name="billing_to" id="billing_to" onchange="get_bill_data(this);">
                  <option value=""></option>
                  <?php while ($bill_row = mysqli_fetch_array($bill_res)) { ?>
                     <option value="<?php echo $bill_row['id'];?>"><?php echo $bill_row['name'];?></option>
                  <?php } ?>
               </select>
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <textarea class="form-control hitz-text-height" name="bill_address" id="bill_address" readonly="" style="height: 64px !important;"></textarea> 
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="bill_city" id="bill_city" class="form-control get_city" placeholder="CITY" readonly=""/>  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="bill_contact" id="bill_contact" class="form-control" placeholder="CONTACT" readonly=""/>  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="bill_pan" id="bill_pan" class="form-control" placeholder="PAN" readonly=""/>  
            </div>
         </div>
         <div class="col-md-12">
            <div class="form-group">
               <input type="text" name="bill_gst" id="bill_gst" class="form-control" placeholder="GST" readonly=""/>  
            </div>
         </div>
      </div>
   </div>
   <div class="row">
      <div class="col-md-4">
         <div class="form-group">
            <label class="capital">Agent</label>
               <input class="form-control" name="agent" id="agent" autocomplete="off"/>
         </div>
      </div>
       
   <div class="col-md-4">
         <div class="form-group">
      </div>
   </div>
  
   <div class="col-md-2">
       <div class="form-group">
         <label class="capital">TO BE BILLED AT</label> 
         <input type="text" size="35" id="to_be_billed_at" name="to_be_billed_at" class="form-control" autocomplete="off"/>
      </div>
   </div>
   </div>
<div class="row">
   <div class="col-md-8">
     <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="7%">Description</th>
          <th class="text-center" width="7%">pcs</th>
          <th class="text-center" width="7%">Actual  weight</th>
          <th class="text-center" width="7%">Charged weight</th>
          <th class="text-center" width="7%">HSN CODE</th>
          <th class="text-center" width="7%">FREIGHT RATE</th>
       </tr>
    </thead>
    <tbody>
      <?php $i = 0;?>
      <tr>
       <td>
        <a href="javascript:;" class="btn green btn-block add-more" style="display: block;"><i class="fa fa-plus"></i></a>
        <a href="javascript:;" class="btn red btn-block remove-me" style="display: none;"><i class="fa fa-minus"></i></a>
     </td>
     <td id="lrno">
      <input type="text" name="product[<?php echo $i; ?>][description]" value="" name="description" id="description" class="add-more-table form-control top product-name description bill_cal" data-count="<?php echo $i;?>" >
   </td>
   <td><input type="text" name="product[<?php echo $i; ?>][pcs]" value="" name="pcs" id="pcs" class="add-more-table form-control top pcs bill_cal" ></td>
   <td><input type="text" name="product[<?php echo $i; ?>][weight]"  value="" name="lr_weight" id="lr_weight" class="add-more-table form-control top weight bill_cal"></td>
   <td><input type="text" name="product[<?php echo $i; ?>][charged_weight]"  value="" name="lr_charged_weight" id="lr_charged_weight" class="add-more-table form-control top charged_weight bill_cal"></td>

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

   <td><input type="text" name="product[<?php echo $i; ?>][freight_rate]"  value="" name="lr_freight_rate" id="lr_freight_rate" class="add-more-table form-control top freight_rate bill_cal"></td>
</tr>
<?php $i++; ?>
</tbody>
</table>
</div>

<div class="col-md-5">
   <div class="form-group">
   </div>
</div>
<div class="col-md-2">
   <div class="form-group">
      <label class="col-md-12 capital">A WEIGHT</label> 
      <input type="text" name="total_actual_weight" id="total_actual_weight" class="form-control">
   </div>
</div>
<div class="col-md-2">
   <div class="form-group">
      <label class="col-md-12 capital">C WEIGHT</label> 
      <input type="text" name="total_charged_weight" id="total_charged_weight" class="form-control">
   </div>
</div>
<div class="col-md-4">
   <div class="form-group">
   </div>
</div>
               </div>
                     <div class="col-md-4">
                        <div class="col-md-12">
                           <div class="form-group">
                              <label class="capital">REMARK</label>
                              <textarea class="form-control hitz-text-height" id="remark" name="remark" style="height: 64px !important;"></textarea>
                           </div>
                        </div>
                     </div>

<div class="col-md-4">
<div class="col-md-6">
   <div class="form-group">
      <label class="capital">EMPLOYEE</label> 
      <select class="form-control select2 " name="emp_id" id="emp_id">
         <option value></option>
         <?php 
         $emp     = "SELECT * FROM `emp_mst` WHERE status = '0'";
         $emp_res = mysqli_query($conn,$emp);
         while ($emp_row = mysqli_fetch_assoc($emp_res)) { ?>
            <option value="<?php echo $emp_row['id'];?>"><?php echo $emp_row['code'];?> - <?php echo $emp_row['name'];?> </option>
         <?php } ?>
      </select>
   </div>
</div>
<div class="col-md-6">
   <div class="form-group">
      <label class="capital">TRUCK DRIVER NO</label> 
      <input type="text" name="truck_driver_no" id="truck_driver_no" class="form-control">
   </div>
</div>

<div class="col-md-6">
   <div class="form-group">
    <label class="capital"> FREIGHT </label>
   </div>
 </div>

<div class="col-md-6" >
   <div class="form-group">
      <input type="text" class="form-control" id="freight" name="freight" autocomplete="off" placeholder="CHARGE" />
   </div>
 </div>
 <div class="col-md-6">
   <div class="form-group">
    <label class="capital"> ST CHARGES</label>
   </div>
 </div>

<div class="col-md-6" >
   <div class="form-group">
      <input type="text" class="form-control" id="st_charges" name="st_charges" autocomplete="off" placeholder="CHARGE" />
   </div>
 </div>
 </div>

<input type="hidden" value="<?php echo $_SESSION['branch_id'];?>" name="branch_id" id="branch_id">
<input type="hidden" value="LR" 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 ajax-submit capital" type="submit"> Save & List</button>
   <a href="index.php?page=lr/list.php" class="btn btn-danger capital"> Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
</section>

<script type="text/javascript">
   $(document).ready(function(){
      jQuery('#signupForm').delegate('.lr_type', 'ifChecked', function(event){
         $value = jQuery(this).val();
         if($value == 'D') {
          jQuery('#from_place').removeClass('required');
          jQuery('#to_place').removeClass('required');
          jQuery('#consignor_name').removeClass('required');
          jQuery('#consignee_name').removeClass('required');
          jQuery('#billing_party').removeClass('required');
       }
    });
    $('#rate_on').select2();
    $('#lr_mode').select2();
    // $('#delivery').select2();
    $('#emp_id').select2();
    $('#gst_paid_by').select2();
    $('#billing_party').select2();
    $('#location_id').select2();
    $('#billing_branch').select2();
    $('#billing_to').select2();
    $( "#from_place" ).autocomplete({
       source: function( request, response ) {
          $.ajax({
             url: "lr/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;
       }
   });

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



    jQuery(document).ready(function($) {
    var $length = 0;

    // Add a new row
    $(document).on('click', '.add-more', function(e) {
        $length = $('#product-wapper').find('table tbody tr').length;
        var $clone = $('#product-wapper table tbody tr:first').clone();

        $clone.find('input').each(function() {
            this.name = this.name.replace('[0]', '[' + $length + ']');
            this.value = ''; // Clear input values if needed
        });

        $clone.find('.product-name').attr('data-count', $length);
        $('#product-wapper table tbody').append($clone);
        $('#product-wapper table tbody').find('.remove-me').show();
        $('#product-wapper table tbody').find('.add-more').hide();
        $('#product-wapper table tbody').find('.remove-me:last').hide();
        $('#product-wapper table tbody').find('.add-more:last').show();

        calculateTotalWeight(); // Recalculate total weight
        calculateCTotalWeight(); // Recalculate total weight
    });

   jQuery(document).on('click', '.add-more-expense', function(e) {
         $length = jQuery('#expense-wapper').find('table tbody tr').length;
         var $clone = jQuery('#expense-template table tr').clone();
         $clone.find('input').each(function() {
            this.name = this.name.replace('[%i%]', '[' + $length + ']');
         });
         $clone.find('.account_name').attr('data-count', $length);
         $clone.find('.account_id').attr('data-count', $length);
         jQuery('#expense-wapper table tbody').append($clone);
         jQuery('#expense-wapper table tbody').find('.remove-me-expense').show();
         jQuery('#expense-wapper table tbody').find('.add-more-expense').hide();
         jQuery('#expense-wapper table tbody').find('.remove-me-expense:last').hide();
         jQuery('#expense-wapper table tbody').find('.add-more-expense:last').show();
      });


    // Remove a row
    $(document).on('click', '.remove-me', function(e) {
        e.preventDefault();
        $(this).closest('tr').remove();
        calculateTotalWeight(); // Recalculate total weight
        calculateCTotalWeight(); // Recalculate total weight
    });

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


    // Calculate total actual weight on input change
    $(document).on('input', '.weight', function() {
        calculateTotalWeight();
    });
     $(document).on('input', '.charged_weight', function() {
        calculateCTotalWeight();
    });
     

    // Function to calculate total weight
    function calculateTotalWeight() {
        var totalWeight = 0;
        $('.weight').each(function() {
            var weight = parseFloat($(this).val()) || 0; // Parse value or default to 0
            totalWeight += weight;
        });
        $('#total_actual_weight').val(totalWeight.toFixed(2)); // Display total with 2 decimal places
    }

     function calculateCTotalWeight() {
        var totalCWeight = 0;
        $('.charged_weight').each(function() {
            var chargedweight = parseFloat($(this).val()) || 0; // Parse value or default to 0
            totalCWeight += chargedweight;
        });
        $('#total_charged_weight').val(totalCWeight.toFixed(2)); // Display total with 2 decimal places
    }
});



   //TRUCK NO
   $( "#truck_no" ).autocomplete({
      source: function( request, response ) {
         $.ajax({
            url: "lr/get_truck_data.php",
            type: 'post',
            dataType: "json",
            data: {
            search: request.term
            },
            success: function( data ) {
               response( data );
            }
        });
      },
      select: function (event, ui) {
         if(ui.item.value != 0) {
            $('#truck_no').val(ui.item.label);
            get_Truck_weight();
            return false;
         }
      }
   });



   $( "#to_place" ).autocomplete({
      source: function( request, response ) {
         $.ajax({
            url: "lr/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;
      }
   });

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

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

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

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

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

   /* $('#rate_on').on('change', function() {
       calculateFinalAmount(this);
    });

    $('#billing_party').on('change', function() {
       if ($(this).val()  == 'CONSIGNOR') {
          var $consi = parseFloat(jQuery('#consignor_name').val());
          if($consi == $consi){
             var $consis = parseFloat(jQuery('#billing_to').val($consi).change());
          }
          }else if($(this).val()  == 'CONSIGNEE'){
          var $consignee = parseFloat(jQuery('#consignee_name').val());
          if($consignee == $consignee){
             var $consignee = parseFloat(jQuery('#billing_to').val($consignee).change());
          }
       }else{
          var $consignee = parseFloat(jQuery('#billing_to').change());
       }
    });*/
    
    $("#consignor_name").autocomplete({
       source: function( request, response ) {
          $.ajax({
             url: "lr/get_consignor_search_data.php",
             type: 'post',
             dataType: "json",
             data: {
                search: request.term
             },
             success: function( data ){
                response( data );
                $('#consignor_address').prop('readonly',false);
                $('#consignor_city').prop('readonly',false);
                $('#consignor_contact').prop('readonly',false);
                $('#consignor_pan').prop('readonly',false);
                $('#consignor_gst').prop('readonly',false);
             }
          });
       },
       select: function (event, ui) {
          if(ui.item.value != 0) {
               $('#consignor_name').val(ui.item.label);
               $('#consignor_address').prop('readonly',true);
               $('#consignor_city').prop('readonly',true);
               $('#consignor_contact').prop('readonly',true);
               $('#consignor_pan').prop('readonly',true);
               $('#consignor_gst').prop('readonly',true);
          return false;
          }
       }
    });

    $("#consignee_name").autocomplete({
       source: function( request, response ) {
          $.ajax({
             url: "lr/get_consignor_search_data.php",
             type: 'post',
             dataType: "json",
             data: {
               search: request.term
             },
             success: function( data ) {
                response( data );
                $('#consignee_name').prop('readonly',false);
                $('#consignee_address').prop('',false);
                $('#consignee_city').prop('',false);
                $('#consignee_contact').prop('',false);
                $('#consignee_pan').prop('',false);
                $('#consignee_gst').prop('',false);
             }
          });
       },
       select: function (event, ui) {
          if(ui.item.value != 0) {
               $('#consignee_name').val(ui.item.label);
               $('#consignee_address').prop('',true);
               $('#consignee_city').prop('',true);
               $('#consignee_contact').prop('',true);
               $('#consignee_pan').prop('',true);
               $('#consignee_gst').prop('',true);
             return false;
          }
       }
    });
    });

function get_consignor_name_data2(input) {
  var consignorName = input.value;
  $.ajax({
     type: "POST",
     url: "lr/get_consignor_details.php", // Replace with your PHP script URL
     data: { consignor_name: consignorName },
     success: function(response) {
        // Parse the response and update other form fields
        var data = JSON.parse(response);
        $('#consignor_address').val(data.address);
        $('#consignor_city').val(data.city);
        $('#consignor_contact').val(data.contact);
        $('#consignor_pan').val(data.pan);
        $('#consignor_gst').val(data.gst);
     },
        error: function(xhr, status, error) {
        // Handle errors
     }
  });
}

function get_consignee_name_data2(input) {
  var consigneeName = input.value;
  $.ajax({
     type: "POST",
     url: "lr/get_consignee_details.php", // Replace with your PHP script URL
     data: { consignee_name: consigneeName },
     success: function(response) {
        // Parse the response and update other form fields
        var data = JSON.parse(response);
        $('#consignee_address').val(data.address);
        $('#consignee_city').val(data.city);
        $('#consignee_contact').val(data.contact);
        $('#consignee_pan').val(data.pan);
        $('#consignee_gst').val(data.gst);
     },
        error: function(xhr, status, error) {
        // Handle errors
     }
  });
}


// Attach event listener to gst_per for dynamic GST and net_amount calculation




function calculateFinalAmount(ele) {
   var lr_no = $(ele).val();
   var $weight = parseFloat(jQuery('#weight').val());
   if ($weight == '' || $weight == undefined || isNaN($weight)) {
      $weight = 0;
   }
   $rate       = parseFloat(jQuery('#rate').val());
   if ($rate == '' || $rate == undefined || isNaN($rate)) {
      $rate = 0;
   }
   $pcs  = parseFloat(jQuery('#pcs').val());
   if ($pcs == '' || $pcs == undefined || isNaN($pcs)) {
     $pcs = 0;
   }

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

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

   var $extra_height_amnt = parseInt(jQuery('#extra_height_amnt').val());
   if ($extra_height_amnt == '' || $extra_height_amnt == undefined || isNaN($extra_height_amnt)) {
      $extra_height_amnt = 0;
   }
   if(lr_no == 'WEIGHT'){
      if($weight !=''){
         $amnt  = $weight * $rate;
      }
      if($weight !='' && $pcs !=''){
         $amnt  = $weight * $rate;
      }
   }else if(lr_no == 'PCS'){
      if($pcs !=''){
         $amnt  = $pcs * $rate;
      }
      if($weight !='' && $pcs !=''){
         $amnt  = $pcs * $rate;
      }
   }else{}

   if(lr_no != 'WEIGHT' && lr_no != 'PCS'){
      $net   = $freight - $advance;
      jQuery('#total_amnt').val($net.toFixed(2));  
   }else{
   $net   = $amnt - $advance;
   jQuery('#freight').val($amnt.toFixed(2));
   jQuery('#total_amnt').val($net.toFixed(2));  
   }

   if($extra_height_amnt !=''){
      $final_am = $freight + $extra_height_amnt - $advance;  
      jQuery('#total_amnt').val($final_am.toFixed(2));
   }
   document.getElementById('advance').setAttribute('max', $freight);
}

function get_Truck_weight(ele) {
   var truck_no = $("#truck_no").val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/get_truck.php',
      'data': 'truck_no=' + truck_no,
      dataType: 'JSON',
      success: function (result) {
         if (result != '') {
            jQuery('#lorry_type').val(result.lorry_type);
         }
      }
   });
}

function get_consignor_data(ele) {
   var consignor_name = $(ele).val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/get_consignor_data.php',
      'data': 'consignor_name=' + consignor_name,
      dataType: 'JSON',
      success: function (result) {
         if (result != '') {
            $('#consignor_address').val(result.address);
            $('#consignor_city').val(result.city);
            $('#consignor_contact').val(result.mobile);
            $('#consignor_pan').val(result.pan);
            $('#consignor_gst').val(result.gstin);
         }
      }
   });
}

function get_bill_data(ele) {
    var billing_to = $(ele).val();
    $.ajax({
        type: 'POST',
        url: 'lr/get_bill_data.php',
        data: 'billing_to=' + billing_to,
        dataType: 'JSON',
        success: function (result) {
            if (result) {
                $('#bill_address').val(result.address);
                $('#bill_city').val(result.city);
                $('#bill_contact').val(result.mobile);
                $('#bill_pan').val(result.pan);
                $('#bill_gst').val(result.gstin);
                $('#rate').val(result.rate); // Populate the rate field

                updateGSTPercentages();
            } else {
                // Clear fields if no result
                $('#bill_address, #bill_city, #bill_contact, #bill_pan, #bill_gst, #rate').val('');
            }
        }
    });
}

function updateGSTPercentages() {
    const billGst = $('#bill_gst').val();
    const gstSlab = parseFloat($('#gst_slab').val());

    if (billGst.startsWith('24') || billGst === '' || billGst === null) {
        // If bill_gst starts with '24' or is null/blank, divide gst_slab by 2 for CGST and SGST
        const gstPercentage = gstSlab / 2;
        $('#cgst_per').val(gstPercentage);
        $('#sgst_per').val(gstPercentage);
        $('#igst_per').val(0); // Reset IGST
    } else {
        // If bill_gst does not start with '24', set gst_slab to IGST
        $('#igst_per').val(gstSlab);
        $('#cgst_per').val(0); // Reset CGST
        $('#sgst_per').val(0); // Reset SGST
    }

    // Recalculate GST and Net Amount
    calculateGST();
}

function get_consignee_data(ele) {
   var consignee_name = $(ele).val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/get_consignee_data.php',
      'data': 'consignee_name=' + consignee_name,
      dataType: 'JSON',
      success: function (result) {
         if (result != '') {
            $('#consignee_address').val(result.address);
            $('#consignee_city').val(result.city);
            $('#consignee_contact').val(result.mobile);
            $('#consignee_pan').val(result.pan);
            $('#consignee_gst').val(result.gstin);
         }
      }
   });
}

function get_consignor_name_data(ele) {
   var consignor_name = $(ele).val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/get_consignor_name_data.php',
      'data': 'consignor_name=' + consignor_name,
      dataType: 'JSON',
      success: function (result) {
         if (result != '') {
            $('#consignor_address').val(result.address);
            $('#consignor_city').val(result.city);
            $('#consignor_contact').val(result.mobile);
            $('#consignor_pan').val(result.pan);
            $('#consignor_gst').val(result.gstin);
         }
      }
   });
} 

function get_consignee_name_data(ele) {
   var consignor_name = $(ele).val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/get_consignee_name_data.php',
      'data': 'consignee_name=' + consignee_name,
      dataType: 'JSON',
      success: function (result) {
         if (result != '') {
            $('#consignee_address').val(result.address);
            $('#consignee_city').val(result.city);
            $('#consignee_contact').val(result.mobile);
            $('#consignee_pan').val(result.pan);
            $('#consignee_gst').val(result.gstin);
         }
      }
   });
}

function CheckLr() {
   var lr_no      = $("#lr_no").val();
   var branch_id  = $("#branch_id").val();
   var module     = $("#module").val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/check-lr-no.php',
      'data': {
         'lr_no': lr_no,
         'branch_id': branch_id,
         'module': module
      },
      dataType: 'JSON',
      success: function (result) {
         if(result.status == 1) {
            jQuery('.submit').attr('disabled', false);
         }else{
            jQuery('.submit').attr('disabled', true);
            swal("Opps !!", "Not A Valid LR Number", "info")  
         }
      }
   });
}

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

function CheckTruck() {
   var truck_no = $("#truck_no").val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/check-truck-no.php',
      'data': {
         'truck_no': truck_no
      },
      dataType: 'JSON',
      success: function (result) {
         if(result.status != 1) {
            var $truck      = $("#truck_no").val('').trigger('focus');
            var url = "index.php?page=truck_mst/add.php" + '&type=' + 'truck' + '&no=' + jQuery('#truck_no').val();
            window.open(url);
         }else{
            get_Truck_weight();
         }
     }
   });
}

function CheckUplode() {
   var truck_no      = $("#truck_no").val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/check_truck_doc.php',
      'data': {
         'truck_no': truck_no
      },
      dataType: 'JSON',
      success: function (result) {
         if(result.status == 1) {
            $.toast({
               heading: 'OPPS....',
               text: 'RC AND IMAGE NOT UPLODED',
               icon: 'warning',
               position: 'top-right'
            });  
         }else{
            jQuery('.submit').attr('enable', true);
         }
      }
   });
}

function CheckDate() {
   var l_date      = $("#l_date").val();
   $.ajax({
      'type': 'POST',
      'url': 'lr/check-date.php',
      'data': {
         'l_date': l_date
      },
      dataType: 'JSON',
      success: function (result) {
         if(result.status == 0) {
            swal("Opps !!", "Date should be between Financial Year...!!!", "info");
            setTimeout("location.reload(true);",2000);
            $('#l_date').val('').trigger('focus');   
         }else{
            jQuery('.ajax-submit').attr('enable', true);
         }
      }
   });
}

function CopyData(ele) {
   var $billing_party = ele;
   jQuery('#gst_paid_by').val($billing_party).trigger('change');
}
</script>