<?php
include 'common.php';
include 'server_exchange_common.php';

function ChangeIsCalcExchangeLog($dbhandle, $character_uid, $exchange_id, $calc_price)
{
	$stmt = $dbhandle->prepare("UPDATE exchange_log SET is_calc=1, calc_price=? WHERE is_calc=0 AND id=? AND seller_uid=?");
	$stmt->bind_param("iii", $calc_price, $exchange_id, $character_uid);
	$result = $stmt->execute();
	$stmt->close();
	
	if($result)
	{
		return true;
	}
	return false;
}

function CalcExchangeItem($account_id, $character_uid, $login_key, $group_id, $group_calc_price)
{
	$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;
	}


	$response = "EXCAHNGE_CALC_OK";
	$error = "";

	if (CheckExchangeIsMaintenance($dbhandle))
	{
		$response = "EXCHANGE_UNDER_MAINTENANCE";
	}
	else
	{
		$split = ",";
		$arrIds = explode($split, $group_id);
		$arrCalcPrices = explode($split, $group_calc_price);
	
		for($i=0;$i< sizeof($arrIds);$i++)
		{
			if (ChangeIsCalcExchangeLog($dbhandle, $character_uid, $arrIds[$i], $arrCalcPrices[$i]))
			{
				if (AddCash($dbhandle, $account_id, $arrCalcPrices[$i]))
				{
					$addType = "EXCHANGE";
					LogAddCrystal($dbhandle, $account_id, $character_uid, $addType, $arrCalcPrices[$i]);
				}
				else
				{
					$response = "ADD_CRYSTAL_FAIL";
					$error = "";
					break;
				}
			}
			else
			{
				$response = "NO_EXIST_EXCHANGE_ITEM";
				$error = "";
				break;
			}
		}
	}
	
	mysqli_close($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'=>$response,'error'=>$error));
}

$json = json_decode(file_get_contents('php://input'));
$account_id = $json->account_id;
$character_uid = $json->character_uid;
$login_key = $json->login_key;
$group_id = $json->group_id;
$group_calc_price = $json->group_calc_price;

if(CheckValidatedServerIP())
{
	CalcExchangeItem($account_id, $character_uid, $login_key, $group_id, $group_calc_price);
}
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	));
}

?>