<?php
include 'common.php';
include 'server_exchange_common.php';

function ExchangeMarketPrice($item_uid)
{
	$dbhandle = DB_Connect();
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");

	$count = 0;
	$sum = 0;
	$avg = 0;
	$min = PHP_FLOAT_MAX; //$min = INF; 
	$max = 0;
	
	$now = new DateTime('now', new DateTimeZone('UTC'));
	$strNow = $now->format('Y-m-d');
	$weeksAgo = date('Y-m-d', strtotime($strNow. " -1 week"));

	if (CheckExchangeIsMaintenance($dbhandle))
	{
		$return = "EXCHANGE_UNDER_MAINTENANCE";
		$error = "";
	}
	else
	{
		$stmt = $dbhandle->prepare("SELECT count, price FROM exchange_log WHERE item_uid=? AND DATE(deal_date) BETWEEN ? AND ?");	
		$stmt->bind_param("iss", $item_uid, $weeksAgo, $strNow);
		$stmt->execute();
		$result = $stmt->get_result();
		if($result)
		{		
			while ($row = $result->fetch_assoc())
			{
				$count++;
				$ppp = $row['price'] / $row['count'];
				if ($ppp > $max) $max = $ppp;
				if ($ppp < $min) $min = $ppp;
				$sum += $ppp;
	
			}
			mysqli_stmt_free_result($stmt);
	
			if ($count > 0)
			{
				$temp = $sum / $count;
				$avg = round($temp, 2);
			}
			else
			{
				$avg = 0;
				$min = 0;
				$max = 0;
			}
			
			$return = "EXCHANGE_MARKET_PRICE_OK";
			$error = "";
		}
		else
		{
			$return = "EXCHANGE_MARKET_PRICE_FAIL";
			$error = mysqli_error($dbhandle);
		}
	}

	

	$strNow = date('y.m.d', strtotime($strNow));
	$weeksAgo = date('y.m.d', strtotime($weeksAgo));

	$isXmlHttpRequest = (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) ?
	(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false: false;
	($isXmlHttpRequest) ? header('Content-type: application/json') : header('Content-type: text/plain');
 
	echo json_encode(array('result'=>$return,'error'=>$error,'item_uid'=>$item_uid, 'count'=>$count, 'avg'=>$avg, 'max'=>$max, 'min'=>$min, 'now'=>$strNow, 'weeks_ago'=>$weeksAgo));
		
	mysqli_close($dbhandle);
}

$item_uid = $_GET['item_uid'];

if(CheckValidatedServerIP())
{
	ExchangeMarketPrice($item_uid);
}
else
{
	$response = "INVALIDATED_SERVER";
	$error = "CheckValidatedServerIP ERROR";
	$isXmlHttpRequest = (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) ?
	(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false: false;
	($isXmlHttpRequest) ? header('Content-type: application/json') : header('Content-type: text/plain'); 
 
	echo json_encode(array(	'result'=>$response,'error'=>$error	));
}

?>