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

	require_once("../connection.php");
	$user=mysqli_real_escape_string($connect, $_POST['user']);
	$id_product=mysqli_real_escape_string($connect, $_POST['id_product']);
	$no_invoice=mysqli_real_escape_string($connect, $_POST['no_invoice']);
	$id_customer=mysqli_real_escape_string($connect, $_POST['id_customer']);
	$id_store=mysqli_real_escape_string($connect, $_POST['id_store']);
	$date=mysqli_real_escape_string($connect, $_POST['date']);
	$amount=mysqli_real_escape_string($connect, $_POST['amount']);
	$totalprice=mysqli_real_escape_string($connect, $_POST['totalprice']);
	$price=mysqli_real_escape_string($connect, $_POST['price']);
	$status=mysqli_real_escape_string($connect, $_POST['status']);
	$note=mysqli_real_escape_string($connect, $_POST['note']);

	
	$getusers	= mysqli_query($connect,"SELECT * FROM users WHERE phone_number='$user'");
	$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);




	$barang = mysqli_query($connect,"SELECT * FROM product WHERE id_product='$id_product'");
	$b=mysqli_fetch_array($barang);


	$totalharga	=$b['selling_price']*$amount;
	$stok		=$b['stock']-$amount;
	$datastok = mysqli_query($connect,"SELECT * FROM stock WHERE id_product='$id_product' AND id_store='$id_store'");
	$s=mysqli_fetch_array($datastok);
    $stoknya		=$s['stock']-$amount;

	mysqli_query($connect,"INSERT INTO sales(id_product, amount, id_customer, id_store, user, no_invoice, status, price, totalprice, date, note, rest_stock) 
                    VALUES('$id_product', '$amount', '$id_pelanggan', '$id_store', '$m[phone_number]', '$no_invoice', '$status', '$price', '$totalprice', '$date', '$note', '$stoknya')");
  
			mysqli_query($connect,"UPDATE product SET stock   = '$stok' WHERE id_product  = '$id_product'");
			
			mysqli_query($connect,"UPDATE stock SET stock   = '$stoknya' WHERE id_product  = '$id_product' AND id_store='$id_store'");
	
		
	$responses = array(
    'status' 	=> 'true',
    'errCode' 	=> '01',
	'msg' 		=> 'Success'
	);
   

	echo json_encode($responses);


	?>