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

	require_once("../connection.php");
	
		$key=mysqli_real_escape_string($connect, $_GET['key']);
		$tanggal_awal=mysqli_real_escape_string($connect, $_GET['first_date']);
			$tanggal_akhir=mysqli_real_escape_string($connect, $_GET['last_date']);

	$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){

	$query = "SELECT * FROM product WHERE user='$m[phone_number]' ORDER BY stock DESC";
	$hasil = mysqli_query($connect,$query);

	if(mysqli_num_rows($hasil) > 0 ){
	$response = array(
    'status' 	=> 'true',
    'errCode' 	=> '01',
	'msg' 		=> 'Success'
	);
	$response["data"] = array();
	while($x = mysqli_fetch_array($hasil)){
	  
	$jumlahterjual = mysqli_query($connect,"SELECT SUM(amount) as totalpenjualan FROM sales WHERE id_product='$x[id_product]' AND date>='$tanggal_awal' and date<='$tanggal_akhir'");
    $j=mysqli_fetch_array($jumlahterjual);

	if($j['totalpenjualan']==''){
	$terjual=0;
	}else{
	$terjual= $j['totalpenjualan'];
	}

	$begin = new DateTime( "$tanggal_awal" );
	$end   = new DateTime( "$tanggal_akhir" );
   
   	$datastok = array();
	for($i = $begin; $i <= $end; $i->modify('+1 day')){
    $tanggalnya= $i->format("Y-m-d");
		
	$datasisa = mysqli_query($connect,"SELECT SUM(rest_stock) as sisa FROM sales WHERE id_product='$x[id_product]' AND date='$tanggalnya'");
    $s=mysqli_fetch_array($datasisa);
	
	
	if($s['sisa']==''){
	$sisa=0;
	}else{
	$sisa= $s['sisa'];
	}
	
    $g['rest_stock']	 	= $sisa;
    $g['minimal_stock'] 	= $x["minimalstock"];
    $g['date'] 		= $tanggalnya;
    array_push($datastok, $g);
	}
	
	
    $h['id_product'] 	= $x["id_product"];
    $h['name_product'] 	= $x["name_product"];
    $h['first_date'] 	= $tanggal_awal;
    $h['last_date'] = $tanggal_akhir;
    $h['sold'] 		= $terjual;
    $h['last_stock'] = $x["stock"];
    $h['minimal_stok'] 	= $x["minimalstock"];
    $h['datastok'] 		= $datastok;
    array_push($response["data"], $h);
	}
	
	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);	
	}
?>