<?php
//open connection
include 'db_Connection.php';

//update timestamp
//$cek_uid =$_SESSION['username'];  
$timezone = "Asia/Jakarta";
date_default_timezone_set($timezone);  
$datetime = new DateTime(date("Y-m-d H:i:s"));
$str_datetime = $datetime->format("Y-m-d H:i:s");
//$sql  = ("UPDATE usr_profile SET last_activity = '$str_datetime' WHERE user_id = '$cek_uid'");
//$query = mysqli_query($conn, $sql);

//get parameters
$data_post = $_POST['data_post'];

//get array value
$json = $data_post;
$array = json_decode($json, true);
$Invoice_Number = $array['Invoice_Number'];
$Nominal_Amount = $array['Nominal_Amount'];
$Invoice_Amount = $array['Invoice_Amount'];

// menghitung total amount perPO yang ditemukan        
	$sql = "SELECT IFNULL(sum(Amount),0) as total FROM payment_receive WHERE Invoice_Number = '$Invoice_Number'";	
	$rs_result = $conn->query($sql);

	 while($row = $rs_result->fetch_assoc()) {	
		$total = $row['total'];                            			
     }
	 
	 //get remaind cashout
	 $Remain = $Invoice_Amount - $total;
    
if($Nominal_Amount > $Remain){	        	        
        $overlimit = "overlimit";    
        $res = array("result" => $overlimit);			
        echo json_encode($res);				
}
elseif($Nominal_Amount == $Remain){
		$sql  = ("INSERT INTO payment_receive (Invoice_Number, Date, Amount, User_Id_Created)
		VALUES ('$Invoice_Number','$str_datetime','$Nominal_Amount','UserName')");
        $query = mysqli_query($conn, $sql);
		
		$sql  = ("UPDATE sales_invoice SET Status = 'Closed' WHERE Invoice_Number = '$Invoice_Number'");
		$query = mysqli_query($conn, $sql);

        $sukses = "sukses";    
        $res = array("result" => $sukses);
        echo json_encode($res);
}
else{
		$sql  = ("INSERT INTO payment_receive (Invoice_Number, Date, Amount, User_Id_Created)
		VALUES ('$Invoice_Number','$str_datetime','$Nominal_Amount','UserName')");
        $query = mysqli_query($conn, $sql);

        $sukses = "sukses";    
        $res = array("result" => $sukses);		
        echo json_encode($res);    
		}
?>
