	<?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){
		
		
	$datap = mysqli_query($connect,"SELECT * FROM sales_data WHERE no_invoice='$no_invoice'");
	$db=mysqli_fetch_array($datap);
	
	if($db['status']=='debt'){
			
	$json = array(
    'status' => 'true',
    'errCode' => '02',
	'msg' => 'Orders cannot be deleted for debt transactions'
	);

    echo json_encode($json);	
		}else{
		
		$datapenjualan = mysqli_query($connect,"SELECT * FROM sales WHERE no_invoice='$no_invoice'");
	while($p = mysqli_fetch_array($datapenjualan)){
	$query1	=mysqli_query($connect,"SELECT * FROM product WHERE id_product ='$p[id_product]'");
	$b = mysqli_fetch_array($query1);
	if($b['have_stock']==1){
	$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]'");		

	}
	}
		
	
	
	mysqli_query($connect,"DELETE FROM sales WHERE no_invoice='$no_invoice'");
	mysqli_query($connect,"DELETE FROM sales_data WHERE no_invoice='$no_invoice'");
	
	mysqli_query($connect,"UPDATE db_table SET status   = '0' WHERE id_table  = '$db[id_table]'");	

	$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);	
	}
	?>