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

	require_once("../connection.php");
	
	$timestamp = new DateTime(null, new DateTImeZone('Asia/Kolkata'));
	$tanggal = $timestamp->format('Y-m-d');
	$time = $timestamp->format('H:i');
	
	$key				=mysqli_real_escape_string($connect, $_POST['key']);
	$stok				=mysqli_real_escape_string($connect, $_POST['stock']);
	$id_product			=mysqli_real_escape_string($connect, $_POST['id_product']);

	$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){
		
		
	
	$datastock = mysqli_query($connect,"SELECT * FROM stock WHERE id_product  = '$id_product' AND id_store='$u[id_store]'");
	$s=mysqli_fetch_array($datastock);
	
	if($s['stock']<$stok){
		$status = "0";
		$opname = $stok-$s['stock'];
	}else{
		$status = "1";
		$opname = $s['stock']-$stok;
	}
		
	
	mysqli_query($connect,"UPDATE stock SET stock   = '$stok' WHERE id_product  = '$id_product' AND id_store='$u[id_store]'");
	mysqli_query($connect,"INSERT INTO history_stock(id_product,
								  id_store,
								  stock,
								  detail,
								  status,
								  date,
                                  user) 
					VALUES('$id_product',
						   '$u[id_store]',
						   '$opname',
						   'Opname Stock',
						   '$status',
						   '$tanggal',
                           '$m[phone_number]')");
	
 $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);	
	}
	?>