<?php
include 'common.php';
include 'server_exchange_common.php';

function CheckExchangeCalcItems($account_id, $character_uid, $login_key)
{
	$dbhandle = DB_Connect();
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");

	if(!CheckLoginKey($dbhandle, $account_id, $login_key))
	{
		PrintLoginKeyError();
		mysqli_close($dbhandle);
		return;
	}

	$return = "CHECK_EXCHANGE_CALC_ITEM_FAILED";
	$error = "";

	if (CheckExchangeIsMaintenance($dbhandle))
	{
		$return = "EXCHANGE_UNDER_MAINTENANCE";
	}
	else
	{
		$stmt = $dbhandle->prepare("SELECT count(*) as cnt FROM exchange_log WHERE is_calc=0 AND seller_uid=?");
		$stmt->bind_param("i", $character_uid);
		$stmt->execute();
		$result = $stmt->get_result();
		if ($result)
		{
			
			if ($row = $result->fetch_assoc())
			{
				if ($row["cnt"] > 0)
				{
					$return = "CHECK_EXCHANGE_CALC_ITEM_OK";
				}
				else
				{
					$return = "CHECK_EXCHANGE_CALC_ITEM_EMPTY";
				}
			}
		}
		else
		{
			$error = mysqli_error($dbhandle);
		}
	}

	$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));
		
	mysqli_close($dbhandle);
}

$account_id = $_GET['account_id'];
$character_uid = $_GET['character_uid'];
$login_key = $_GET['login_key'];

if(CheckValidatedServerIP())
{
	CheckExchangeCalcItems($account_id, $character_uid, $login_key);
}
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	));
}

?>