<?php    include_once('../config/db.php');  include_once('../config/check.php'); include_once('../functions/sale/sale.php');

           $invoicenum= getnewinvoicenum($conn);

 if (filter_has_var(INPUT_POST, "submit")) 
  try{  
      
        $transtype =         18 ; 
        $transaction =       1 ; 
        $transmode =         1 ; 


        $date =              htmlspecialchars (strtoupper($_POST['todaydate'])); 
        $date =                date("Y-m-d", strtotime($date));
        $enddate =           htmlspecialchars (strtoupper($_POST['todaydate']));
        $enddate =           date("Y-m-d", strtotime($enddate));

        $branch =            htmlspecialchars (strtoupper($_POST['branch']));
        $partner =            htmlspecialchars (strtoupper($_POST['partner']));
        $invnum  =            htmlspecialchars ($_POST['receiptnum']);               // receiptnumber
        $memo =              'RETAIL SALE'; // htmlspecialchars ($_POST['description']);     
        $memo2 =              '';     
        $notes =              '' ; //htmlspecialchars (strtoupper($_POST['notes']));   
     

        //$currency =       currency($conn,$partner); 
        // $erate =        erate($conn,$partner);

          $currency =   1 ; //    currency($conn,$partner); 
          $erate =      1;  //  erate($conn,$partner);

       // footer details 
       $subtotal       =         htmlspecialchars (strtoupper($_POST['subtotal']));  
    
       $vatall   =         htmlspecialchars (strtoupper($_POST['vatamount']));  
       $totalvat   =    $vatall *  $erate;       
       $amount   =       htmlspecialchars (strtoupper($_POST['total']));
       $total =  $amount *  $erate ;

       // Payments details
         $mode1       =         htmlspecialchars (strtoupper($_POST['mode1']));  
         $payment1       =         htmlspecialchars (strtoupper($_POST['payment1']));  
         $payment1total       =     $payment1 * $erate  ;//      htmlspecialchars (strtoupper($_POST['payment1']));  
       // footer details 

        $item =              $_POST['item'];
        $salecoa =          $_POST['salecoa'];
        $stockcoa =          $_POST['stockcoa'];
        $cogscoa =           $_POST['cogscoa'];
    
        $name =           ''; //   $_POST['name'];
        $uom =              $_POST['uom'];
        $uombase =        $_POST['uombase'];
        $uomrate =        $_POST['uomrate'];
        
        $unit =              $_POST['unit'];
        $itembp =             $_POST['itembp'];
        $price =             $_POST['price'];
        $discount =          $_POST['discount'];
        $vat =               $_POST['vat'];
        $vatmount =           $_POST['vatamount'];
        $gross =             $_POST['total'];
        $payable =           $_POST['payable'];
    
    $number = count($_POST["item"]); 
        
if($number > 0)  
 {  

       
    $sql1 = 'INSERT INTO acctransactions(date,enddate,memo,invnumber,memo2,notes,transtype,transaction,transmode,transuid) VALUES (:date,:enddate,:memo,:invnum,:memo2,:notes,:transtype,:transaction,:transmode,:transuid)';     
    $stmt = $conn->prepare($sql1)->execute(['date'=>$date,'enddate'=>$enddate,'memo'=>$memo,'invnum'=>$invnum ,'memo2'=>$memo2,'notes'=>$notes,'transtype' =>$transtype,'transaction'=>$transaction,'transmode' =>$transmode,'transuid'=>$uid  ]); 
     $lastid = $conn->lastInsertId(); 

   
    // Inserting into Detailes / Items debeting 
    for($i=0; $i<$number; $i++)  
       {  
          $sql = 'INSERT INTO acctransactionsdetails(transid,branch,warehouse,partner,currency,erate,coa,stockcoa,cogscoa,item,itemdetails,itemuom,itemuombase,itemuomrate,
                                                    itemunit,itemunitbase,itemunittotal,itembp,itemprice,
                                                    itemsubtotal,itemtaxrate,itemtax,itemtotal,total,transmove,transclass )
                  VALUES( :transid,:branch,:warehouse,:partner,:currency,:erate,:coa,:stockcoa,:cogscoa,:item,:itemd,:itemuom,
                          :itemuombase,:itemuomrate,:itemunit,:itemunitbase,:itemunittotal,:itembp,:itemprice,
                          :itemsubtotal,:itemtaxrate,:itemtax,:itemtotal,:total,:transmove,:tclass )'; 

           $stmt = $conn->prepare($sql)->execute([
                               'transid' => $lastid,'branch' =>$branch,'warehouse'=>$branch,'partner' =>$partner,'currency'=>$currency,
                               'erate'=>$erate,'coa'=>$salecoa[$i],'stockcoa' =>$stockcoa[$i],'cogscoa' =>$cogscoa[$i],'item' =>$item[$i],'itemd' => '',
                               'itemuom' => $uom[$i],'itemuombase' => $uombase[$i],'itemuomrate' => $uomrate[$i],
                               'itemunit'=>$unit[$i],'itemunitbase' => $uombase[$i],'itemunittotal'=>$unit[$i], 'itembp' => $itembp[$i] ,
                               'itemprice' => $price[$i],'itemsubtotal' => $gross[$i],'itemtaxrate' => $vat[$i],'itemtax' => $vatmount[$i],
                               'itemtotal' => $payable[$i],'total' => ($payable[$i]*$erate),'transmove' =>1,'tclass'=>1  ]);
       }  
        // crediting     
        $sql = 'INSERT INTO acctransactionsdetails(transid,branch,partner,currency,erate,coa,itemtotal,total,transmove,transclass ) 
                VALUES(:transid,:branch,:partner,:currency,:erate,:coa,:itemtotal,:total,:tmove,:tclass )';

        // subtotal,vat,total
          $conn->prepare($sql)->execute(['transid'=>$lastid,'branch'=>0,'partner'=>0,'currency'=>0,'erate'=>0,'coa'=>0,'itemtotal'=>$subtotal,'total'=>0 , 'tmove' =>3,'tclass'=>0  ]);
          $conn->prepare($sql)->execute(['transid'=>$lastid,'branch'=>$branch,'partner'=>$partner,'currency'=>$currency,'erate'=>$erate,'coa'=>7,'itemtotal'=>$vatall,'total'=>$totalvat , 'tmove' =>4 ,'tclass'=>2 ]);
          $conn->prepare($sql)->execute(['transid'=>$lastid,'branch'=>$branch,'partner'=>$partner, 'currency'=>$currency,'erate'=>$erate,'coa'=>$mode1,'itemtotal'=>$payment1,'total'=>$payment1total , 'tmove' =>5,'tclass'=>2  ]);


 } else{}
            
 // Call ATF    
 audittrail($conn,$lastid,$transtype,$transaction,$transmode,$uid);
 
        header("location:sellreceipt.php?receipt="."$lastid"); 
} catch(Exception $e) { echo 'Message: ' .$e->getMessage();}
       
       
?>

<!DOCTYPE html>
<html>
<head>
<?php include_once('../inc/slink.php');   ?>  
</head>
<body   class="hold-transition skin-black sidebar-collapse sidebar-mini"  >
<div class="wrapper">

  <!-- Main Header -->
    <header class="main-header">

    <!-- Logo -->
       <?php include_once('../inc/sbrand.php');   ?>

    <!-- Header Navbar -->
    <?php include_once('../inc/snavbar.php');   ?>

  </header>
 
  <!-- Left side column. contains the logo and sidebar -->
    <aside class="main-sidebar">

    <!-- sidebar: style can be found in sidebar.less -->
     <?php include_once('../inc/smenu.php');   ?>
    <!-- /.sidebar -->
  </aside>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
   
       <div class="row ">
          <div class="col-xs-12">
            <div class="box ">
                <div class="box-body with-border">
                     <div class="col-xs-2">  <h5 class="box-title listheader"> <i class="fa fa-plus-circle"></i>  POS RETAIL SALE</h5>
                     </div>
                     <div class="col-xs-3"> 
                     <input type="text" name="todaydate" style="border:none" class="form-control todaydate col-lg " autocomplete="off" value="<?php echo "$today"; ?>" required="" >
                     </div>
                    
                </div>
            </div>
          </div>
        </div>

        <!-- /.modal -->
      


        
        <!-- /.modal -->

      <section class="content" style="padding-top:0px;" >
       <div class="row">
         <form   action="" method="post">
        <div class="col-md-8">       
          <div class="box box-default">
            <div class="box-header with-border">
                <!-- Start search -->
                <div class="">
                    <div class="col-lg-2">
                        <div class="">
                                 <label style="color:red;"> RECEIPT NO: </label>
                                 <input type="hidden" name="todaydate" style="border:none" class="form-control todaydate col-lg " autocomplete="off" value="<?php echo "$today"; ?>" required="" >
                                 <input type="text" name="receiptnum" id="" class="form-control receiptnum col-lg " style="color:green;border:none;" autocomplete="off" value="<?php echo "$invoicenum"; ?>" required="" >
                        </div>
                    </div>
                    <div class="col-lg-2">
                        <div class="">
                                 <label style="color:green;"> SELECT BRANCH </label>
                        <!-- <span class="input-group-addon"><i class="fa fa-plus-circle"></i></span> -->
                                <select class="form-control js-example-basic-single" required=""   name="branch" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM admbranch where type=1   ");
                                                            $stmt->execute(); foreach ($stmt as $row) {?>
                                                                    <option></option>
                                                                    <option value="<?php echo $row['id']; ?>"><?php
                                                                        echo $row['name']; ?></option> <?php } ?>
                                </select> 
                            <!-- <input type="text" class="form-control"> -->
                            <!-- <span class="input-group-addon"><i class="fa fa-plus-circle"></i></span> -->
                        </div>
                    </div>
                    <div class="col-lg-3">
                        <div class="">
                                <label style="color:green;" > SELECT CUSTOMER </label>
                        <!-- <span class="input-group-addon"><i class="fa fa-plus-circle"></i></span> -->
                                <select class="form-control js-example-basic-single"  required="" name="partner" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM bppartner where type=1   ");
                                                            $stmt->execute(); foreach ($stmt as $row) {?>
                                                                    <option></option>
                                                                    <option value="<?php echo $row['id']; ?>"><?php
                                                                        echo $row['name']; ?></option> <?php } ?>
                                </select> 
                            <!-- <input type="text" class="form-control"> -->
                            <!-- <span class="input-group-addon"><i class="fa fa-plus-circle"></i></span> -->
                        </div>
                    </div>
                    <div class="col-lg-5">
     
                        <div class="">
                                <label style="color:green;"> SELECT PRODUCT </label>
                        <!-- <span class="input-group-addon"><i class="fa fa-search"></i></span> -->
                                <select class="form-control js-example-basic-single product block "   name="product" style="width:100%;" >
                                                            <?php $stmt = $conn->prepare("      SELECT a.*,b.pricegroup FROM item a 
                                                                                                JOIN itemprice b ON a.id=b.item
                                                                                                WHERE a.type=2 AND b.pricegroup=1   ");
                                                            $stmt->execute(); foreach ($stmt as $row) {?>
                                                                    <option></option>
                                                                    <option value="<?php echo $row['id']; ?>"><?php
                                                                        echo $row['name']; ?></option> <?php } ?>
                                </select>  

                            <!-- <input type="text" class="form-control"> -->
                            <!-- <span class="input-group-addon"><i class="fa fa-plus-circle"></i></span> -->
                        </div>
                    </div>
                </div>
                <!-- End Start search -->
            
            </div>
            <!-- /.box-header -->
            <!-- form start -->
            
              <div class="box-body">
                    <div class="col-md-12">                            
                        <table class="table table-bordered table-condesed table-sm table-condensed bg-default  item_table " id="item_table" >
                                    <tr  class="bg-primary">
                                    <th style="width:20%;">   Item</th>
                                    <!-- <th style="width:20%;">   Details   </th> -->
                                    <th style="width:10%;">   Uom  </th>
                                    <!-- <th style="width:10%;">   Availableunit  </th> -->
                                    <th style="width:20%;">   Unit  </th>
                                    <th style="width:13%;">   Price  </th>
                                    <!-- <th style="width:13%;">   Tax </th> -->
                                    <th style="width:17%;">  Total </th>                                                                      
                                    <th style="width:2%;" >      
                                        <button  type="button" class="btn btn-default btn-xs btn-block add" name="add">  <i class=" "></i> Action </button>
                                    </th>
                                </tr>
                        </table>
                    </div>

                <!-- <div class="form-group">
                  <label for="exampleInputEmail1">Email address</label>
                  <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                </div>
                <div class="form-group">
                  <label for="exampleInputPassword1">Password</label>
                  <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                </div> -->
             
              
              </div>
              <!-- /.box-body -->

              <!-- <div class="box-footer">
                <button type="submit" class="btn btn-primary">Submit</button>
              </div> -->
            
          </div>
          <!-- /.box -->

        </div>
        <!--/.col (left) -->
        <!-- right column -->
          <div class="col-md-4 totalarea">
           <div class="box box-default">
            <!-- <form class="form-horizontal"> -->
              <!-- <div class="box-header with-border">  </div> -->
              <div class="box-body with-border">
                  <div class="col-md-4">
                      <label class="">  Discount: </label>
                      <input type="text" name="discount" id="" class="form-control discount col-lg " autocomplete="off"  required="" >
                  </div>
                  <div class="col-md-4">
                      <label class=""> Subtotal: </label>
                      <input type="text" name="subtotal" id="" class="form-control subtotal  " autocomplete="off"  required="" >
                  </div> 
                  <div class="col-md-4">
                      <label class="">  TAX: </label>
                      <input type="text" name="vatamount" id="" class="form-control vatamount  " autocomplete="off"  required="">
                      
                  </div>
                  <div class="col-md-6">
                      <label class="totalheader">  TOTAL: </label>
                      <input type="text" name="total" id="" class="form-control total  totalbtn" style="font-size:25px;background-color:white;border-color:green;height:30px;" readonly="" autocomplete="off"  required="">
                   </div>
                   <div class="col-md-3">
                      <label class="" style="color:green;">   Paid: </label>
                      <input type="text" name="paid" id="" class="form-control paid  " style="font-size:20px;background-color:white;" readonly="" autocomplete="off"  required="">
                   </div>
                   <!-- <div class="col-md-4">
                      <label class="" style="color:orange;">  Balance: </label>
                      <input type="text" name="balance" id="" class="form-control balance  " style="font-size:20px;" readonly="" autocomplete="off"  required="">
                   </div> -->
                   <div class="col-md-3">
                      <label class="" style="color:orange;">  Balance: </label>
                      <input type="text" name="balance" id="" class="form-control balance  " style="font-size:20px;background-color:white;" readonly="" autocomplete="off"  required="">
                   </div>
                  
                           
              </div>
              
            <!-- </form> -->
           </div>
            <!-- btns -->
            <div class="box box-default">
            <!-- <form class="form-horizontal"> -->
              <div class="box-body">
              <div class="table-responsive">
                  <table class="table  table-condesed table-sm table-condensed bg-default  paymenttable " id="paymenttable" >
                      <tr class="bg-default">
                        <th style="width:25%;">   Payment  </th>
                        <th style="width:30%;">   Amount Paid    </th>
                        <th style="width:20%;">   Remarks  </th>                                                                                            
                        <!-- <th style="width:10%;" >      
                            <button  type="button" class="btn btn-default btn-xs btn-block add" name="add">  <i class=" fa fa-plus-circle fa-sm"></i> Add </button>
                        </th> -->
                      </tr>
                      <tr>
                        <td>   <select class="form-control "   name="mode1" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM coa WHERE payaccount=1 and isdefault=1  ");
                                                            $stmt->execute(); foreach ($stmt as $row) {?>
                                                                    <!-- <option></option> -->
                                                                    <option value="<?php echo $row['id']; ?>"><?php
                                                                        echo $row['name']; ?></option> <?php } ?>
                                </select>  </td>
                          <!-- <input type="text" name="vatamount" id="" class="form-control mode1  " autocomplete="off"  required=""> -->
                        <td> <input type="text" name="payment1" id="" class="form-control payment1" required="" value=0 autocomplete="off"  required=""></td>
                        <td> <input type="text" name="remark1" id="" class="form-control remark1  " autocomplete="off"  required=""></td>
                      
                      </tr>
                      <tr>
                        <td> <select class="form-control "   name="mode2" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM coa WHERE payaccount=1 and isdefault!=1  ");
                                                            $stmt->execute(); foreach ($stmt as $row) {?>
                                                                    <!-- <option></option> -->
                                                                    <option value="<?php echo $row['id']; ?>"><?php
                                                                        echo $row['name']; ?></option> <?php } ?>
                                </select> 
                        </td>
                        <td> <input type="text" name="payment2" id="" class="form-control payment2 " value='' autocomplete="off"  ></td>
                        <td> <input type="text" name="remark2" id="" class="form-control remark2  " autocomplete="off" >
                        </td>
                      </tr>
                      
                  </table>
                <div class="col-xs-12">
                  <!-- <a href="invoice-print.html" target="_blank" class="btn btn-default "><i class="fa fa-print"></i> Print</a> -->
                  <!-- <button type="button" class="btn btn-success  pull-right   subbtn"><i class="fa fa-print"></i> Submit and Print Receipt
                  </button> -->
                  <button  class="btn btn-primary  pull-right  subbtn postgl " type="submit" name="submit" >
                    <i class="fa fa-save"></i> Submit
                  </button>
              


                </div>
              </div>               
              </div>
              
            </form>
           </div>
            <!-- btns end -->
          </div>


        

       </section>

  <!-- Main content -->
  
</div>
  <!-- /.content-wrapper -->
  
  <!-- Main Footer -->
  <footer class="main-footer">
    <?php  include_once('../inc/sfooter.php'); ?>
  </footer>
  
</div>
                         
<!-- ./wrapper -->

<!-- REQUIRED JS SCRIPTS -->
<?php include_once('../inc/slinkjs.php') ?>

</body>
</html>

<!-- dynamic rows start here -->
<script>

  // currency and balance for partners 
// $("select[name='partner']") .change(function(){        
//      var partner = $("select[name='partner']").val();  
//                   $.ajax({
//                               async: false, 
//                               'type': "POST",                                          
//                               'url': "../functions/ajax/partnerdetails.php",
//                               'data': { partner:partner  },
//                               'success': function (data) {  
//                                                             var ob=jQuery.parseJSON(data); 
//                                                               code = ob.bcode ;   
//                                                               $("#bcode").text(code);                                                                         
//                                                           }
//                                 });               
                         
//                      });
 


    
$(document).ready(function(){

// initaialise branch  
 // $("select[name='product']") .change(function()
    // {        
      //  var  product = $("select[name='product']").val();  
      
        
     // Load system
        var counter=0; 

        $(document).on('change', '.product', function(){

           counter++; 
          var  product = $("select[name='product']").val();  
                   $.ajax({
                        async: false, 
                        'type': "POST",                                          
                        'url': "../functions/ajax/pos/sellretail.php",
                        'data': { product:product,counter:counter },
                        'success': function (data) {  
                                                       $('#item_table').append(data);
                                                       calculatediscount ();  
                                                       calculateTotal (); 
                                                        calculatePayable ();
                                                        calculateVat ();   
                                                                                                                                                                                                    
                                                  }
                                                  
                        });  
                       
                       
            
        // DELETE A ROW 
                $(document).on('click', '.remove', function(){  
                var button_id = $(this).attr("id");  
                //alert(button_id);
                  $('#row'+button_id+'').remove();   
                  calculateTotal ();  
                  calculateVat ();    
                  calculatediscount();                    
                   calculatePayable (); 
                    
            }); 
            
        //  INITIALIZE SELECT 2 ON DYNAMIC TABLE 
            
                    $('.js-example-basic-single').select2({
                        placeholder:'',
                        width: 'resolve'        
                    });

        
             
            // UNIT CHANGE
              $("#item_table").on('change', '.unit', function(){

                  var unit =      $(this).closest('tr').find('.unit').val();
                  var item =      $(this).closest('tr').find('.item').val();
                  var cprice =      $(this).closest('tr').find('.price').val();
               //  alert(cprice);
                  var vat_rate = function () { var vat_rate = 0 ;
                                              $.ajax({
                                                      async: false, 
                                                      'type': "POST",                                          
                                                      'url': "../functions/ajax/pos/sellretailchange",
                                                      'data': {unit:unit,item:item,cprice:cprice  },
                                                      'success': function (data) {  
                                                                                    var ob=jQuery.parseJSON(data); 
                                                                                    ntotal = parseInt(ob.total) ;    
                                                                                    nsubtotal = parseInt(ob.subtotal) ;    
                                                                                    nrate = parseInt(ob.itemrate) ;    
                                                                                   // alert(nrate)   ;                                                                              
                                                                                }
                                                      });  return   vat_rate;
                                            }();

                  $(this).parents("tr").find(".vatamount").val(nrate);  
                   $(this).parents("tr").find(".total").val(nsubtotal) ; 
                   $(this).parents("tr").find(".payable").val(ntotal) ; 
                  // $(this).parents("tr").find(".item_payable").val(payable) ;             
                  calculateTotal (); calculatePayable (); calculateVat ();  
                                                            });
            // END UNIT CHANGE  

            $("#item_table").on('change', '.price', function(){

                  var oldprice =     $(this).closest('tr').find('.oldprice').val();
                  var price =        $(this).closest('tr').find('.price').val();

                  if( price > oldprice  )
                     {
                          var unit =         $(this).closest('tr').find('.unit').val();
                          var vatrate =      $(this).closest('tr').find('.vatrate').val();
                                     
                          var rate       =     vatrate / 100 ;
                          var nvatamount =    ( price * unit ) * rate ;
                          var ntotal     =       unit * price  ;
                          var npayable     =    nvatamount + ( unit * price ) ;
                                             
                          $(this).parents("tr").find(".vatamount").val(nvatamount);  
                          $(this).parents("tr").find(".total").val(ntotal) ; 
                          $(this).parents("tr").find(".payable").val(npayable) ; 
                                    
                          calculateTotal (); calculatePayable (); calculateVat ();  
                                                            
                     } 
                     else{
                           $(this).parents("tr").find(".price").val(oldprice); 
                           var price =     $(this).closest('tr').find('.oldprice').val();
                           var unit =         $(this).closest('tr').find('.unit').val();
                           var vatrate =      $(this).closest('tr').find('.vatrate').val();
                                     
                           var rate       =     vatrate / 100 ;
                           var nvatamount =    ( price * unit ) * rate ;
                           var ntotal     =       unit * price  ;
                           var npayable     =    nvatamount + ( unit * price ) ;
                                             
                           $(this).parents("tr").find(".vatamount").val(nvatamount);  
                           $(this).parents("tr").find(".total").val(ntotal) ; 
                           $(this).parents("tr").find(".payable").val(npayable) ; 
                                    
                          calculateTotal (); calculatePayable (); calculateVat ();  
                     }

                    });
                  // END UNIT CHANGE  

                  // amout paid 
                       $("input[name='payment1']") .change(function()
                             {   calculatebalance ();   

                              });

                       $("input[name='payment2']") .change(function()
                             {   calculatebalance ();    

                             });
                  // end amount paid
                    
          
                                      
    });
         
                                                          
                                    function calculateTotal () { $(".item_table").each(function () {  
                                                     var sum = 0; 
                                                      $("input[name='total[]']").each(function () {
                                                      if (!isNaN(this.value) && this.value.length != 0) 
                                                             { sum += parseFloat(this.value);  }
                                                                       $("input[name='subtotal']").val(sum);
                                                                                                    });  
                                                                                      });
                                                             }
          
                                   function calculatePayable () { $(".item_table").each(function () {  
                                                     var sum = 0; 
                                                      $("input[name='payable[]']").each(function () {
                                                      if (!isNaN(this.value) && this.value.length != 0) 
                                                             { sum += parseFloat(this.value);  }
                                                                       $("input[name='total']").val(sum);

                                                                       var  payment1 = $("input[name='payment1']").val(); 
                                                                        var  payment2 = $("input[name='payment2']").val(); 
                                                                         var totalpaid =  ( payment1 +  payment2 );

                                                                  
                                                                      
                                                                       if ( totalpaid > sum )
                                                                          {
                                                                            var balance= sum -totalpaid ;
                                                                          }else
                                                                          {
                                                                             var balance= 0 ;
                                                                          }
                                                                      // alert(amountpaid);
                                                                      $("input[name='paid']").val(totalpaid);
                                                                      $("input[name='balance']").val(balance);
                                                                      $("input[name='paid']").val(totalpaid);
                                                                                                    });  
                                                                                      });
                                                                 }
                        
                                     function calculateVat () { $(".item_table").each(function () {  
                                                         var sum = 0; 
                                                          $("input[name='vatamount[]']").each(function () {
                                                          if (!isNaN(this.value) && this.value.length != 0) 
                                                                 { sum += parseFloat(this.value);  }
                                                                      $("input[name='vatamount']").val(sum);
                                                                      
                                                                                                        });  
                                                                  });
                                                              }

                                                                    
                                     function calculatediscount () { $(".item_table").each(function () {  
                                                         var sum = 0; 
                                                          $("input[name='discount[]']").each(function () {
                                                          if (!isNaN(this.value) && this.value.length != 0) 
                                                                 { sum += parseFloat(this.value);  }
                                                                      $("input[name='discount']").val(sum);
                                                                      
                                                                                                        });  
                                                                  });
                                                              }

                                      function calculatebalance () { 
                                            var  total = $("input[name='total']").val(); 
                                            var  payment1 = $("input[name='payment1']").val(); 
                                            var  payment2 = $("input[name='payment2']").val(); 
                                             var totalpaid =  (payment1 + payment2 );
                                             var balance = ( total - totalpaid );

                                             $("input[name='paid']").val(totalpaid);
                                             $("input[name='balance']").val(balance);


                                                                   if(balance > 0 ){
                                                                              $('.postgl').hide();
                                                                           }else {   $('.postgl').show(); }
                                                                           
                                                                  }


                                                       
                                                  

                   });
</script>
<!-- DYANAMIC ROWS LISTING HERE --->

<!-- DYNAMIC ROWS ENDS HERE --->