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

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
//  error_reporting(E_ALL);

//if (filter_has_var(INPUT_POST, "edit")) 
//try{
    $id = $_POST['edit']; 
//     if($id == '')
//           {   header("location:acc_invoicel");   }

// else  {              
   
  $stmt = $conn->prepare(" SELECT a.*, SUM(b.taxamount) taxamount ,SUM(b.gross) gross ,sum(taxamount) taxamount  FROM acctransaction a
                           JOIN acctransaction_item b ON b.transactionid = a.id WHERE a.id=? ");
                     $stmt->execute([$id]);  $details = $stmt->fetch(); 
        
               // invoice items -based on quote ref 
                    $items = $conn->query(" SELECT  * from acctransaction_item a  where a.transactionid =  '".$details["id"]."'     ")->fetchAll();
   
       

      // }
//} catch(Exception $e) { echo 'Message: ' .$e->getMessage();} 


 if (filter_has_var(INPUT_POST, "submit")) 
  try{  
        $cid =              htmlspecialchars (strtoupper($_POST['cid']));
        $startdate =         htmlspecialchars (strtoupper($_POST['startdate']));
         $startdate = date("Y-m-d", strtotime($startdate));
         $enddate =         htmlspecialchars (strtoupper($_POST['enddate']));
         $enddate = date("Y-m-d", strtotime($enddate));
        
        $partner =           htmlspecialchars (strtoupper($_POST['partner']));
        $invoicenum =           htmlspecialchars (strtoupper($_POST['invoicenum']));
       // $memo   =            htmlspecialchars ($_POST['memo']);              
        $description =       htmlspecialchars ($_POST['description']);     
        $notes =       htmlspecialchars (strtoupper($_POST['notes']));     
        $split =  1 ;      
       // $amount =  0.00 ;      
         
        //$dr =  0 ;   
        $cogs= 176;  
        $currency =       currency($conn,$partner); 
        $erate =       erate($conn,$partner); 

                  
      //  $subtotal   =    htmlspecialchars (strtoupper($_POST['g_subtotal']));        
      //  $g_vat   =         htmlspecialchars (strtoupper($_POST['g_vat']));        
        $amount   =       htmlspecialchars (strtoupper($_POST['g_total']));
        $glamount =  $amount *  $erate ;

        $rid =                $_POST['rid'];
       
        $item =                $_POST['item'];
        $salecoa =                $_POST['salecoa'];
        $stockcoa =                $_POST['stockcoa'];
        $pcost =                $_POST['pcost'];
        $name =              $_POST['name'];
        $unit =              $_POST['unit'];
        $uom =              $_POST['uom'];
        $uomrate =              $_POST['uomrate'];
        $price =             $_POST['price'];
        $vat =               $_POST['vat'];
        $vatamount =           $_POST['vatamount'];
        $gross =             $_POST['total'];
        $payable =           $_POST['payable'];
        
        $number = count($_POST["item"]);  

        $sql = "UPDATE acctransaction SET invoicenum=:invoicenum,date=:startdate,enddate=:enddate,bpartner=:partner,memo=:memo,currency=:currency,
        erate =:erate,amount =:amount,glamount =:glamount,description=:description,notes=:notes  WHERE id=:id "; 
        $conn->prepare($sql)->execute(['invoicenum'=>$invoicenum,'startdate'=>$startdate,'enddate'=>$enddate,'partner' =>$partner,
                                       'memo' => $invoicenum ,'currency' => $currency,'erate' => $erate ,'amount' => $amount ,'glamount' =>$glamount ,
                                        'description' => $description,'notes'=> $notes,'id'=>$cid  ]); 

for($i=0; $i<$number; $i++)  
  {  

    


      $stmt = 'UPDATE acctransaction_item  SET coa=:coa,item=:item,name=:name,unit=:unit,uom=:uom,uomrate=:uomrate,uomunit=:uomunit,price=:price,gross=:gross,
                                tax=:tax,taxamount=:taxamount,gltaxamount=:gltaxamount,drsale=:drsale,crsale=:crsale,cogs=:cogs,total=:total,glamount=:glamount  WHERE  id=:tid '; 
      $conn->prepare($stmt)->execute([ 'coa' =>$salecoa[$i],'item' =>$item[$i],'name' => $name[$i],'unit' => ($unit[$i] * $uomrate[$i] ) ,'uom' => $uom[$i],'uomrate' => $uomrate[$i],'uomunit' => $unit[$i],
                                       'price' => $price[$i],'gross' => $gross[$i],'tax' =>$vat[$i], 'taxamount' => $vatamount[$i] ,
                                       'gltaxamount' => ($vatamount[$i]* $erate) ,'drsale'=>$cogs,'crsale'=>$stockcoa[$i],
                                        'cogs'=>( $pcost[$i] * $unit[$i]),
                                       'total' => $payable[$i], 'glamount' => ($gross[$i]*$erate) , 'tid' => $rid[$i] ]);
  } 

       

        
            
        header("location:acc_invoicel.php"); 
} catch(Exception $e) { echo 'Message: ' .$e->getMessage();}
       
       



?>

<!DOCTYPE html>
<html>
<head>
<?php include_once('inc/link.php');   ?>  
</head>
<body <?php include_once('inc/nav.php');  ?> >
<div class="wrapper">

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

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

    <!-- Header Navbar -->
    <?php include_once('inc/navbar.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/menu.php');   ?>
    <!-- /.sidebar -->
  </aside>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">

  <section class="content-header" >
    <div class="row">
      <div class="">
         <div class="col-md-4">
          <a href="acc_invoicel" class="btn btn-success btn-sm"> Go Back <i class="fa fa-arrow-left"></i> </a>
             
     
         </div>
         <div class="col-md-4">
             <p style="color:green; font-size:20px ;font-weight:bold; " > <i class="fa fa-file-o" ></i> EDIT INVOICE </p>
            
              <span id="currency">  </span> 
         </div>
         <div class="col-md-4">
             
         </div>
      </div>
   
    </div>
   
  </section>

 


  <!-- Main content -->
  <section class="content container-fluid" style="padding-top:0px;" >
    <div class="">
      <div class="box box-default box-xs">
              <div class="box-body">
                  <div class="row">
             
                    <form class="form-horizontal "  action="" method="post"  >
                        <div class="row">
                                                                           
                                  <div class="col-md-12 "  > 
                                           
                                                        
                                        <!-- CURRENT DATE  --->
                                            
                                                <div class="col-md-2">
                                                   <label>  Invoice Number  </label>
                                                   <input type="text" class="form-control" name="invoicenum" required=''  value="<?php  echo $details["invoicenum"]?>" autocomplete="off">
                                                </div>
                                                <div class="col-md-2">
                                                    <label > Start Date  </label>
                                                    <input type="hidden" class="" autocomplete="off" value="<?php  echo $details["id"]?>"  name="cid">    
                                                    <input type="text" class="form-control datepickere " autocomplete="off" value="<?php  echo $details["date"]?>"  name="startdate">    
                                                </div>     
                                                <div class="col-md-2">
                                                    <label > Due Date  </label>
                                                     
                                                    <input type="text" class="form-control datepickere " autocomplete="off" value="<?php  echo $details["enddate"]?>"  name="enddate">    
                                                </div>     
                                                                                                                      
                                              
                                                <div class="col-md-2  ">
                                                      <label> Customer* </label>
                                                        <select class="form-control  js-example-basic-single  "  required="" name="partner" 
                                                        style="width:100%" >
                                                            <?php  $stmt = $conn->prepare("SELECT id,name  FROM bppartner "); $stmt->execute();
                                                            foreach($stmt as $row)
                                                                {
                                                                    if( $row['id'] == $details["bpartner"] )
                                                                            { ?>
                                                                                <option selected value="<?php echo $details["bpartner"]  ?>" > 
                                                                                        <?php echo $row['name'] ?>  <option>
                                                                                <?php  }    
                                                                    else  { ?>
                                                                                    
                                                                                    <option  value="<?php echo $row['id']; ?>" > 
                                                                                            <?php echo $row['name'] ?>  <option>
                                                                                    <?php } 
                                                                    } 
                                                            ?>
                                                        </select> 

                                                </div>                               
                                                <!-- <div class="col-md-2">
                                                   <label>  Memo/ Reference No  </label>
                                                   <input type="text" class="form-control" name="memo" required=''  value="<?php  echo $details["memo"]?>" autocomplete="off">
                                                </div>  -->
                                                <div class="col-md-4">
                                                    <label>  Description   </label>
                                                    <input type="text" name="description"  class="form-control"  value="<?php  echo $details["description"]?>" autocomplete="off">
                                                </div>
                                               
                                                
                                                                  

                                              <!---  QUOTE PRODUCTS AND DETAILS   --->
                                                  <!---  QUOTE HEADER  --->                               
                                                    <div class="col-xs-12">
                                                        <div class="" style="margin-top:5px;">
                                                        <table class="table  table-condesed table-sm table-condensed    item_table " id="item_table" >
                                                        <tr style="" class="bg-primary" >
                                                            <th style="width:20%;">   Item </th>
                                                            <th style="width:20%;">   Details   </th>
                                                            
                                                            <th style="width:13%;">   Uom  </th>
                                                            <th style="width:13%;">   Unit  </th>
                                                            <th style="width:10%;">   Price  </th>
                                                            <th style="width:10%;">   Tax    </th>
                                                            
                                                            <th style="width:15%;" >  Payable </th>
                                                            <!-- <th style="width:2%;" >      
                                                                <button  type="button" class="btn btn-success  btn-xs btn-block add" name="add">  <i class=" fa fa-plus-circle fa-sm"></i> Add </button>
                                                            </th> -->
                                                        </tr>
                                                        <?php   $i = 0; foreach($items as $item )
                                                                 { extract($item); 
                                                                  
                                                                 
                                                                  $i++;                                
                                                            ?>	
                                                                                       
                                                                <tr id="row'+i+'">
                                                                  
                                                                <td style="border:none;" >  <input type="hidden" name="rid[]"   value="<?php echo $id; ?>" id="rid_'+i+'" class="form-control table-condesed rid" />                           
                                                                                            
                                                                                            <select name="item[]" id="item_'+i+'"  class="form-control js-example-basic-single  item_coa">
                                                                                              <option value="">Select Unit</option><?php echo salee($conn,$item) ; ?></select>
                                                                                              <input type="hidden" name="salecoa[]" id="salecoa_'+i+'"  value="<?php echo $coa; ?>"  class="form-control salecoa " />
                                                                                              <input type="hidden" name="stockcoa[]" id="stockcoa_'+i+'"  value="<?php echo $crsale; ?>"   class="form-control stockcoa " />
                                                                                              <input type="hidden" name="pcost[]" id="pcost_'+i+'"   value="<?php echo $cogs/$uomunit; ?>"  class="form-control pcost " />
                                                                                            </td>
                                                                <td style="border:none;" > <input type="" name="name[]"    value="<?php echo $name; ?>" id="name_'+i+'" class="form-control table-condesed item_name" /></td>
                                                                <td style="border:none;" > <input type="hidden" name="uomrate[]"    value="<?php echo $uomrate; ?>" id="uomrate_'+i+'" class="form-control table-condesed item_uomrate" />
                                                                                           <select name="uom[]" id="uom_'+i+'"  class="form-control  item_uom"><option value="">Select Unit</option><?php echo uome($conn ,$uom) ; ?></select></td>  
                                                                <td style="border:none;" > <input type="" name="unit[]"   value="<?php echo $uomunit; ?>" id="unit_'+i+'" class="form-control table-condesed item_unit" /></td>  
                                                                <td style="border:none;" > <input type="" name="price[]"   value="<?php echo $price; ?>" id="price_'+i+'" class="form-control table-condesed item_price" /></td>  
                                                                <td style="border:none;" > <select name="vat[]" id="vat_'+i+'"  class="form-control js-example-basic-single   item_vat"><option value="">Select Unit</option><?php echo taxe($conn,$tax) ; ?></select></td>  
                                                                 <td style="border:none;" ><input type="hidden" name="vatamount[]" id="vatamount_'+i+'"  value="<?php echo $taxamount; ?>" class="form-control item_vatamount " />
                                                                                           <input type="hidden" name="total[]" id="total_'+i+'"  value="<?php echo $gross; ?>" class="form-control item_total " />
                                                                                           <input type="" name="payable[]"    value="<?php echo $gross+$taxamount; ?>" id="payable_'+i+'" class="form-control table-condesed item_payable" /></td>  
                                                                                                                
                                                                
                                             
                                                                </tr>
                                                            
                                                            <?php } ?>

                                                                               
                                                              
                                                  </table>
                                                           
                                                        </div>
                                                    </div>
                                                    <!---  QUOTE HEADER  ---> 
                                                
                                  
                                              <!---  QUOTE PRODUCTS AND DETAILS   --->
                                              <div class="col-sm-12"  >  
                                                <!---  Start End details   --->
                                                <div class="col-sm-4" style="padding-top:10px;">
    
                                                                   <label  class=" control-label"> Amount in words: </label>
                                                                    <textarea class="form-control" name="notes" required=""><?php  echo $details["notes"] ?></textarea>
                                                                  
                                                   
                                                   </div>              
                                                   <div class="col-sm-6 pull-right" style="border:none; border-width:thin; border-color:lightgrey;"  >                                     
                                                       
                                                               
                                                              <label for="inputEmail" class="col-md-6 control-label"> Subtotals: </label>
                                                                 <div class="col-sm-6">    
                                                                 <input type="text"    name="g_subtotal" class="form-control"  value="<?php  echo $details["gross"] ?>"  style="" >
                                                   
                                                                  </div>
 
                                                              <label for="inputEmail" class="col-md-6 control-label"> Tax <span id="taxname">  </span>  </label>
                                                                  <div class="col-sm-6">
                                                                  <input type="text"   name="g_vat"class="form-control" value="<?php  echo $details["taxamount"] ?>"  style="margin-top:2px;margin-bottom:2px;" >
                                                      
                                                                  </div>
                                                                                                                        
                                                             <label for="inputEmail" class="col-md-6 control-label"> Total:  </label>
                                                               <div class="col-sm-6">
                                                               <input type="text"    name="g_total"  id="quotepay"class="form-control totalsum"  value="<?php  echo $details["amount"] ?>" style="" >
                                                     
                                                             </div>
             
                                                             
                                                   </div> 
                                               
                                       
                                        
                                        
                                          <!-- submit button -->
                                        <div class="form-group " >
                                          <div class="col-sm-offset-4 col-xs-10" style="padding-top:10px;">                             
                                          <button type="submit"name="submit" class="btn btn-success col-xs-4">
                                                <i class="fa fa-plus "></i>  Update Invoice   </button>
                                                </div>
                                    </div>
                            
                        </div>
                    </form>
                        
                    </div>
                </div>
            </div>
      </div>
   </section>
</div>
  <!-- /.content-wrapper -->
  
  <!-- Main Footer -->
  <footer class="main-footer">
    <?php  include_once('inc/footer.php'); ?>
  </footer>
  
</div>
                         
<!-- ./wrapper -->

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

</body>
</html>

<!-- dynamic rows start here -->
<script>
    
$(document).ready(function(){
// loading the footer details


    var i=0; 

 
 $(document).on('click', '.add', function(){
    i++;  
  var html = '';
  html += '<tr id="row'+i+'">';
   html += '<td><select name="coa[]" class="form-control item_coa js-example-basic-single "><option value="">Select </option><?php echo expense($conn); ?></select></td>';
   html += '<td><input type="text" name="name[]" id="name_'+i+'" class="form-control table-condesed item_name" autocomplete="off"  required="" /></td>';
   html += '<td><input type="text" name="unit[]" value="1"  id="unit_'+i+'" class="form-control table-condesed item_unit" autocomplete="off" /></td>';
   html += '<td><input type="" name="price[]" id="price_'+i+'" class="form-control item_price"  /></td>';
   html += '<td><select name="vat[]"  id="vat_'+i+'" class="form-control item_vat js-example-basic-single "><option value="1">ZERO RATED</option><?php echo vat($conn); ?></select><input type="hidden" name="vatamount[]" id="vatamount_'+i+'"  class="form-control item_vatamount " /></td>';  
     
   html += '<td> <input type="hidden" name="total[]" id="total_'+i+'" value="0" class="form-control item_total " /><input type="text" name="payable[]" id="payable_'+i+'"  class="form-control item_payable " /></td>';  
   html += '<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-xs btn-block remove"> <i class="fa fa-trash"></i> </button></td></tr>';
      
  $('#item_table').append(html);
                                      
     
  // DELETE A ROW 
          $(document).on('click', '.remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
              
      }); 
     
  //  INITIALIZE SELECT 2 ON DYNAMIC TABLE 
     
              $('.js-example-basic-single').select2({
                placeholder:'SELECT',
                width: 'resolve'        
            });
     



// PRICE CHANGE 
            $("#item_table").on('change', '.item_price', function(){

                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                      
                      var vat =       $(this).closest('tr').find(' .item_vat :selected').val();
                      
                      var vat_rate = function () { var vat_rate = 0 ;
                                                   $.ajax({
                                                          async: false, 
                                                          'type': "POST",                                          
                                                          'url': "aj.taxrate.php",
                                                          'data': { vat: vat  },
                                                          'success': function (data) {  
                                                                                        var ob=jQuery.parseJSON(data); 
                                                                                         vat_rate = parseInt(ob.value) ;    
                                                                                         alert(vat_rate)   ;                                                                              
                                                                                     }
                                                           });  return   vat_rate;
                                                 }();
                     
                      var total = unit * price ;                          
                      var myvat = total * vat_rate /100 ;
                      var payable = myvat + total; 
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
                      $(this).parents("tr").find(".item_payable").val(payable) ;             
                      calculateTotal (); calculatePayable (); calculateVat ();  
                                                                 });
// UNIT CHNAGE 
$("#item_table").on('change', ".item_unit", function()
         {                     
                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                      
                      var vat =       $(this).closest('tr').find(' .item_vat :selected').val();

                    //  alert(unit);
                      var vat_rate = function () { var vat_rate = 0 ;
                                                   $.ajax({
                                                          async: false, 
                                                          'type': "POST",                                          
                                                          'url': "aj.taxrate.php",
                                                          'data': { vat: vat  },
                                                          'success': function (data) {  
                                                                                        var ob=jQuery.parseJSON(data);  vat_rate = parseInt(ob.value) ;                                                                                     
                                                                                     }
                                                           });  return   vat_rate;
                                                 }();
                      var total = unit * price ;                          
                      var myvat = total * vat_rate /100 ;
                      var payable = myvat + total; 
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
                      $(this).parents("tr").find(".item_payable").val(payable) ;             
                      calculateTotal (); calculatePayable (); calculateVat ();                    
          }); 
// VAT CHANGE 
$("#item_table").on('change', ".item_vat", function()
         {                     
                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                      
                      var vat =       $(this).closest('tr').find(' .item_vat :selected').val();
                      var vat_rate = function () { var vat_rate = 0 ;
                                                   $.ajax({
                                                          async: false, 
                                                          'type': "POST",                                          
                                                          'url': "aj.taxrate.php",
                                                          'data': { vat: vat  },
                                                          'success': function (data) {  
                                                                                        var ob=jQuery.parseJSON(data);  vat_rate = parseInt(ob.value) ;                                                                                     
                                                                                     }
                                                           });  return   vat_rate;
                                                 }();
                      var total = unit * price ;                          
                      var myvat = total * vat_rate /100 ;
                      var payable = myvat + total; 
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
                      $(this).parents("tr").find(".item_payable").val(payable) ;             
                      calculateTotal (); calculatePayable (); calculateVat ();                    
          }); 

     
     
 });
       
 
// System edits  

//  Product change

$("#item_table").on('change', '.item_coa', function()
            {
               var item =      $(this).closest('tr').find('.item_coa').val();
               alert(item)
                                    $.ajax({
                                            async: false, 
                                            'type': "POST",                                          
                                            'url': "zajax/aj.itemsales.php",
                                            'data': { item:item  },
                                            'success': function (data) {  
                                                                          var ob=jQuery.parseJSON(data); 
                                                                          stockcoa = parseInt(ob.stockcoa) ;                                                                              
                                                                          salecoa = parseInt(ob.salecoa) ;                                                                              
                                                                          pcost = parseInt(ob.production) ;                                                                              
                                                                          // alert(stockcoa) ;                                                                            
                                                                      }
                                            });  
                                  
               $(this).parents("tr").find(".stockcoa").val(stockcoa);   
               $(this).parents("tr").find(".salecoa").val(salecoa);   
               $(this).parents("tr").find(".pcost").val(pcost);   
               //$(this).parents("tr").find(".stockcoa").val(stockcoa);   
                                                  
            });

// end product change 
// uom rate chnage 
$("#item_table").on('change', '.item_uom', function(){
var uom =      $(this).closest('tr').find('.item_uom').val();
var uom_rate = function () { var uom_rate = 0 ;
                             $.ajax({
                                    async: false, 
                                    'type': "POST",                                          
                                    'url': "zajax/aj.uomsale.php",
                                    'data': { uom:uom },
                                    'success': function (data) {  
                                                                  var ob=jQuery.parseJSON(data); 
                                                                   uom_rate = ob.erate ;    
                                                                  // alert(uom_rate)   ;                                                                              
                                                               }
                                     });  return   uom_rate;
                           }();
 $(this).parents("tr").find(".item_uomrate").val( uom_rate);  
                                           });
                                           
// end uom rate chnage 

    // PRICE CHANGE 
    $("#item_table").on('change', '.item_price', function(){

    var unit =      $(this).closest('tr').find('.item_unit').val();
    var price =     $(this).closest('tr').find('.item_price').val();                      
    var vat =       $(this).closest('tr').find(' .item_vat :selected').val();

    var vat_rate = function () { var vat_rate = 0 ;
                                $.ajax({
                                        async: false, 
                                        'type': "POST",                                          
                                        'url': "aj.taxrate.php",
                                        'data': { vat: vat  },
                                        'success': function (data) {  
                                                                      var ob=jQuery.parseJSON(data); 
                                                                      vat_rate = parseInt(ob.value) ;    
                                                                      alert(vat_rate)   ;                                                                              
                                                                  }
                                        });  return   vat_rate;
                              }();

    var total = unit * price ;                          
    var myvat = total * vat_rate /100 ;
    var payable = myvat + total; 
    $(this).parents("tr").find(".item_total").val(total);  
    $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
    $(this).parents("tr").find(".item_payable").val(payable) ;             
    calculateTotal (); calculatePayable (); calculateVat ();  
                                              });
// UNIT CHNAGE 
    $("#item_table").on('change', ".item_unit", function()
    {                     
    var unit =      $(this).closest('tr').find('.item_unit').val();
    var price =     $(this).closest('tr').find('.item_price').val();                      
    var vat =       $(this).closest('tr').find(' .item_vat :selected').val();

    //alert(unit);
    var vat_rate = function () { var vat_rate = 0 ;
                                $.ajax({
                                        async: false, 
                                        'type': "POST",                                          
                                        'url': "aj.taxrate.php",
                                        'data': { vat: vat  },
                                        'success': function (data) {  
                                                                      var ob=jQuery.parseJSON(data);  vat_rate = parseInt(ob.value) ;                                                                                     
                                                                  }
                                        });  return   vat_rate;
                              }();
    var total = unit * price ;                          
    var myvat = total * vat_rate /100 ;
    var payable = myvat + total; 
    $(this).parents("tr").find(".item_total").val(total);  
    $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
    $(this).parents("tr").find(".item_payable").val(payable) ;             
    calculateTotal (); calculatePayable (); calculateVat ();                    
    }); 
    // VAT CHANGE 
    $("#item_table").on('change', ".item_vat", function()
    {                     
    var unit =      $(this).closest('tr').find('.item_unit').val();
    var price =     $(this).closest('tr').find('.item_price').val();                      
    var vat =       $(this).closest('tr').find(' .item_vat :selected').val();
    var vat_rate = function () { var vat_rate = 0 ;
                                $.ajax({
                                        async: false, 
                                        'type': "POST",                                          
                                        'url': "aj.taxrate.php",
                                        'data': { vat: vat  },
                                        'success': function (data) {  
                                                                      var ob=jQuery.parseJSON(data);  vat_rate = parseInt(ob.value) ;                                                                                     
                                                                  }
                                        });  return   vat_rate;
                              }();
    var total = unit * price ;                          
    var myvat = total * vat_rate /100 ;
    var payable = myvat + total; 
    $(this).parents("tr").find(".item_total").val(total);  
    $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
    $(this).parents("tr").find(".item_payable").val(payable) ;             
    calculateTotal (); calculatePayable (); calculateVat ();                    
    });
 

         
// Functions 
                                    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='g_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='g_total']").val(sum);
                                                                       $("input[name='invamount']").val(sum);
                                                                                                    });  
                                                                                      });
                                                                 }
                        
                                     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='g_vat']").val(sum);
                                                                      
                                                                                                        });  
                                                                  });
                                                              }
                                                       
                                                  

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

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