<?php
include 'common.php';
include 'server_exchange_common.php';

function GetExchangePurchaseCompletedList($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 = "GET_EXCHANGE_PURCHASE_COMPLETED_LIST_FAIL";
	$error = "";

	$dataArray = array();

	if (CheckExchangeIsMaintenance($dbhandle))
	{
		$return = "EXCHANGE_UNDER_MAINTENANCE";
		$error = "";
	}
	else
	{
		$now = new DateTime('now', new DateTimeZone('UTC'));
		$strNow = $now->format('Y-m-d');
		$days30Ago = date('Y-m-d', strtotime($strNow. " -30 days"));
	
		$stmt = $dbhandle->prepare("SELECT * FROM (SELECT * FROM exchange_log WHERE buyer_uid=? AND deal_date >= ? ORDER BY deal_date DESC LIMIT 100) AS tmp ORDER BY deal_date ASC");
		$stmt->bind_param("is", $character_uid, $days30Ago);
		$stmt->execute();
		$result = $stmt->get_result();
		if ($result)
		{
			$return = "GET_EXCHANGE_PURCHASE_COMPLETED_LIST_OK";
			while ($row = $result->fetch_assoc())
			{
				array_push($dataArray, $row["id"].",". $row["item_uid"].",".$row["count"].",".$row["price"].",".$row["enchant"].",".$row["deal_date"]);
			}
		}
		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,'list'=>$dataArray));
		
	mysqli_close($dbhandle);
}

$account_id = $_GET['account_id'];
$character_uid = $_GET['character_uid'];
$login_key = $_GET['login_key'];

if(CheckValidatedServerIP())
{
	GetExchangePurchaseCompletedList($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	));
}

?>