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

	require_once("../connection.php");
	$tanggal= gmdate("Y-m-d", time()+60*60*7);
	
					$key=mysqli_real_escape_string($connect, $_GET['key']);
					$search=mysqli_real_escape_string($connect, $_GET['search']);
					$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 name_product LIKE '%$search%' AND user='$m[phone_number]' ORDER BY id_product 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, SUM(totalprice) as totalorder FROM sales WHERE id_product='$x[id_product]' AND date='$tanggal'");
    $j=mysqli_fetch_array($jumlahterjual);
	

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

	if($j['totalorder']==''){
	$total_order=0;
	}else{
	$total_order= $j['totalorder'];
	}

    $harga_beli	= $x["purchase_price"]*$terjual;
    $harga_jual	= $x["selling_price"]*$terjual;
    $raba_rugi	= $harga_jual-$harga_beli;
	
	
	$datastok = mysqli_query($connect,"SELECT * FROM stock WHERE id_product='$x[id_product]' AND user='$m[phone_number]'");
    $ds=mysqli_fetch_array($datastok);
	
	if($ds['stock']==''){
	$stok_terakhir=0;
	}else{
	$stok_terakhir= $ds['stock'];
	}
	  
    $h['id_product'] 	= $x["id_product"];
    $h['name_product'] 	= $x["name_product"];
    $h['have_stock'] 		= $x["have_stock"];
    $h['first_date'] 	= $tanggal_awal;
    $h['last_date'] = $tanggal_akhir;
    $h['totalorder'] 	= $total_order;
    $h['sales'] 	= $terjual;
    $h['last_stock'] = $stok_terakhir;
    $h['purchase_price'] 	= $harga_beli;
    $h['selling_price'] 	= $harga_jual;
    $h['laba_rugi'] 	= $raba_rugi;
    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);	
	}
	?>