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

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

	$getusers = mysqli_query($connect,"SELECT * FROM users WHERE id_session='$key'");
	$u	      = mysqli_fetch_array($getusers);
	$jumlah   = mysqli_num_rows($getusers);
	
	
	$masterakun = mysqli_query($connect,"SELECT * FROM users WHERE phone_number='$u[master]'");
	$m=mysqli_fetch_array($masterakun);

	if ($jumlah > 0){
	
	$datapembelian = mysqli_query($connect,"SELECT * FROM sales WHERE no_invoice='$no_invoice'");
	while($p = mysqli_fetch_array($datapembelian)){
		
	$query1	=mysqli_query($connect,"SELECT * FROM product WHERE id_product ='$p[id_product]'");
	$b = mysqli_fetch_array($query1);
	$stokbaru=($b['stock']-$p['amount']);
	
	$query3	=mysqli_query($connect,"UPDATE product SET stock='$stokbaru' WHERE id_product ='$p[id_product]'");		
	$query30	=mysqli_query($connect,"UPDATE stock SET stock='$stokbaru' WHERE id_product ='$p[id_product]'");		
		
	}
	
	$datap 	= mysqli_query($connect,"SELECT * FROM purchasing_data WHERE no_invoice='$no_invoice'");
	$dp 	= mysqli_fetch_array($datap);
							 
	mysqli_query($connect,"UPDATE purchasing_data SET status       = 'cancel'
                             WHERE no_invoice 	   = '$no_invoice'");
							 
	mysqli_query($connect,"UPDATE historydebtsupplier SET status       = 'cancel'
                             WHERE no_invoice 	   = '$no_invoice'");
							 
	$datapiutang 	= mysqli_query($connect,"SELECT * FROM purchasing_data WHERE user='$m[phone_number]' AND id_supplier='$dp[id_supplier]' AND status='debt'");
	$jumlahdata   	= mysqli_num_rows($datapiutang);

		
		if ($jumlahdata > 0){
			mysqli_query($connect,"UPDATE supplier SET debt       = '1'
                             WHERE id_supplier = '$dp[id_supplier]'");
		}else{
					
					mysqli_query($connect,"UPDATE supplier SET debt       = '0'
                             WHERE id_supplier = '$dp[id_supplier]'");
							}						 
							 
	mysqli_query($connect,"UPDATE pembelian SET status       	   = 'cancel'
                             WHERE no_invoice 	   = '$no_invoice'");						 
							 
	$json = array(
    'status' 		=> 'true',
    'errCode'	 	=> '01',
	'msg' 			=> 'Success'
	);

    echo json_encode($json);

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

    echo json_encode($json);	
	}
	?>