<?php

$id=$_POST['ids'];
$payment=$_POST['payment'];
$payment1=$payment;
$payment_mode=$_POST['payment_mode'];
$payment_balance_date=$_POST['payment_balance_date'];
require_once "config.php";
$con->autocommit(FALSE);
$sql="select * from vendor_invoice_details where  id='".$id."'";
$query=mysqli_query($con,$sql);
if($result=mysqli_fetch_array($query)){
    
    $sql2="select * from vendor_invoice_details_history where customer_id='".$id."'";
    $query2= mysqli_query($con,$sql2);
   if($query2==false){
       die(mysqli_error($con));
   }
    while($result1=mysqli_fetch_array($query2)){
      $payment=$payment+  $result1['balance'];
    }
    
    $sql1="update vendor_invoice_details set balance=amount-$payment where id='".$id."'";
   $query1= mysqli_query($con,$sql1);
   if($query1==false){
       die(mysqli_error($con));
   }
    
    $sql1="insert into vendor_invoice_details_history(customer_name,invoice_no,balance,created_on,customer_id,payment_mode) "
            . "values('".$result['customer_name']."','".$result['invoice_no']."','".$payment1."','".$payment_balance_date."','".$id."','".$payment_mode."')";
$query1=mysqli_query($con,$sql1);
 if($query1==false){
       die(mysqli_error($con));
   }
  
$count=mysqli_affected_rows($con);
}

$sql="select * from vendor_invoice_details where  id='".$id."'";
$query=mysqli_query($con,$sql);
if($result=mysqli_fetch_array($query)){
    if($result['balance']<=0){
        $sql1="update vendor_invoice_details set status='completed' where id='".$id."'";
   $query1= mysqli_query($con,$sql1);
   if($query1==false){
       die(mysqli_error($con));
   }
    }else{
         $sql1="update vendor_invoice_details set status='pending' where id='".$id."'";
   $query1= mysqli_query($con,$sql1);
   if($query1==false){
       die(mysqli_error($con));
   }
    }
    
}

$con->commit(); 




if($query==false){
    die(mysqli_error($con));
}
echo $count;
$con->close();

?>