	<?php
	/**
	* Created by PhpStorm.
	* User: ahmad
	* Date: 20/08/2019
	* Time: 11:48 AM
	*/

	require_once("../connection.php");
	
	$key=mysqli_real_escape_string($connect, $_POST['key']);
	$no_invoice=mysqli_real_escape_string($connect, $_POST['no_invoice']);
	$totalbayars=mysqli_real_escape_string($connect, $_POST['totalpay']);

	$getusers	= mysqli_query($connect,"SELECT * FROM users WHERE id_session='$key'");
	$u	   		= mysqli_fetch_array($getusers);
	$jumlah   	= mysqli_num_rows($getusers);
	$tanggal	= gmdate("Y-m-d", time()+60*60*7);
	
	
	$masterakun = mysqli_query($connect,"SELECT * FROM users WHERE phone_number='$u[master]'");
	$m=mysqli_fetch_array($masterakun);

	if ($jumlah > 0){


	$query = "SELECT * FROM sales_data WHERE user='$m[phone_number]' AND no_invoice='$no_invoice'";
	$hasil = mysqli_query($connect,$query);
	$p=mysqli_fetch_array($hasil);

	$totalbayar=$p['totalpay']+$totalbayars;

	$kembalian=$totalbayar-$p['totalorder'];


	if(mysqli_num_rows($hasil) > 0 ){
	
	
	  mysqli_query($connect,"UPDATE sales_data SET    totalpay    = '$totalbayar',
											changepay		 = '$kembalian'
										WHERE no_invoice 	 = '$no_invoice'");
										
							
	$datapenjualan = mysqli_query($connect,"SELECT * FROM sales_data WHERE no_invoice='$no_invoice'");
	$db=mysqli_fetch_array($datapenjualan);
	
	
	mysqli_query($connect,"INSERT INTO logscustomerdebtpayments(id_customer, user, no_invoice, nominal, date) 
                    VALUES('$db[id_customer]', '$m[phone_number]', '$no_invoice', '$totalbayars', '$tanggal')");
	
	if($db['totalorder'] == $db['totalpay']){
	mysqli_query($connect,"UPDATE sales_data SET status    = 'paid off' WHERE no_invoice = '$no_invoice'");
	mysqli_query($connect,"UPDATE customerdebthistory SET status    = 'paid off' WHERE no_invoice = '$no_invoice'");
	}
	
						
	$statushutang = mysqli_query($connect,"SELECT * FROM customerdebthistory WHERE id_customer='$db[id_customer]' AND status='debt'");
	$jumlah = mysqli_num_rows($statushutang);
						if ($jumlah == 0){
						mysqli_query($connect,"UPDATE customer SET debt = '0'
                             WHERE id_customer = '$db[id_customer]'");	
						}else{
							mysqli_query($connect,"UPDATE customer SET debt = '1'
                             WHERE id_customer = '$db[id_customer]'");	
						}					
	
	
	$response = array(
    'status' => 'true',
    'errCode' => '01',
	'msg' => 'Payment Success'
	);
   
	echo json_encode($response);

	}else {
	$response = array(
    'status' => 'true',
    'errCode' => '02',
	'msg' => 'no data'
	);
	echo json_encode($response);
	}


	}else{
	
	
	$json = array(
    'status' => 'true',
    'errCode' => '00',
	'msg' => 'User Not Found'
	);

    echo json_encode($json);	
	}
	?>