<?php
include 'common.php';
include 'server_exchange_common.php';

function DeleteExchangeItem($dbhandle, $id)
{
	$stmt = $dbhandle->prepare("DELETE FROM exchange_item WHERE id=?");
	$stmt->bind_param("i",  $id);
	$result = $stmt->execute();
	$stmt->close();
	
	if($result)
		return true;
	return false;
}
function InsertExchangeLog($dbhandle, $seller_uid, $buyer_uid, $item_uid, $count, $price, $parts_tpye, $enchant, $is_viewed, $optType1, $optValue1, $optType2, $optValue2, $optType3, $optValue3, $optType4, $optValue4, $durability, $created_time, $register_date)
{	
	$now = new DateTime('now', new DateTimeZone('UTC'));
	$strTime =  date_format($now, "Y-m-d H:i:s");

	$stmt = $dbhandle->prepare("INSERT INTO exchange_log (seller_uid, buyer_uid, item_uid, count, price, parts_type, enchant, is_viewed, optType1, optValue1, optType2, optValue2, optType3, optValue3, optType4, optValue4, durability, created_time, register_date, deal_date, is_calc) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)");
	$stmt->bind_param("iiiiiiiisdsdsdsdisss", $seller_uid, $buyer_uid, $item_uid, $count, $price, $parts_tpye, $enchant, $is_viewed, $optType1, $optValue1, $optType2, $optValue2, $optType3, $optValue3, $optType4, $optValue4, $durability, $created_time, $register_date, $strTime);
	$result = $stmt->execute();
	$stmt->close();

	if ($result)
		return true;
	return false;
}
function CheckCopyMail($dbhandle, $character_uid, $exchange_id)
{
	$type = 'Exchange_log';

	$stmt = $dbhandle->prepare("SELECT count(*) as cnt FROM mail_box_character WHERE character_id=? AND type=? AND exchange_id=?");
	$stmt->bind_param("isi", $character_uid, $type, $exchange_id);
	$stmt->execute();
	$result = $stmt->get_result();

	if ($result)
	{
		if($row = $result->fetch_assoc())
		{
			$count = $row["cnt"];
			mysqli_stmt_free_result($stmt);

			if ($count > 0)
			{
				return false;
			}
		}
	}
	return true;
}
function SendExchangeMail($dbhandle, $character_uid, $item_uid, $count, $enchant, $exchange_id)
{
	if (CheckCopyMail($dbhandle, $character_uid, $exchange_id) == false)
	{
		return false;
	}

	mysqli_query($dbhandle,"set session character_set_connection=utf8;");
	mysqli_query($dbhandle,"set session character_set_results=utf8;");
	mysqli_query($dbhandle,"set session character_set_client=utf8;");

	$now = new DateTime('now', new DateTimeZone('UTC'));
	$strTime =  date_format($now, "Y-m-d H:i:s");
	
	$type = 'Exchange_log';

	if ($lang == 'kr')
	{
		$title = '거래소';
		$content = '거래소 구매 아이템';	
	}
	else if ($lang == 'th')
	{
		$title = 'ประมูล';
		$content = 'ซื้อของ';
	}
	else
	{
		$title = 'Auction';
		$content = 'Buy Item';
	}
	
	$time_limit = 720;

	$stmt = $dbhandle->prepare("INSERT INTO mail_box_character (character_id, type, title, content, item_id, item_count, item_enchant, exchange_id, time_limit, time_send) values(?,?,?,?,?,?,?,?,?,?)");
	$stmt->bind_param("isssiiiiis", $character_uid, $type, $title, $content, $item_uid, $count, $enchant, $exchange_id, $time_limit, $strTime);
	$result = $stmt->execute();
	$stmt->close();

	if ($result)
		return true;
	return false;
}

function BuyExchangeItem($id, $character_uid, $account_id, $login_key, $lang)
{
	$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 = "BUY_EXCHANGE_ITEM_FAILED";
	$error = "";

	if (CheckExchangeIsMaintenance($dbhandle))
	{
		$return = "EXCHANGE_UNDER_MAINTENANCE";
	}
	else
	{
		//크리스탈 소모
		//exchange_item db제거
		//exchange_log db생성
		//구매 아이템 메일보내기

		mysqli_begin_transaction($dbhandle);

		$stmt = $dbhandle->prepare("SELECT * FROM exchange_item WHERE is_cancel=0 AND id=?");
		$stmt->bind_param("i", $id);
		$stmt->execute();
		$result = $stmt->get_result();

		if ($result)
		{
			if($row = $result->fetch_assoc())
			{
				mysqli_stmt_free_result($stmt);

				$registDate = new DateTime($row['register_date'], new DateTimeZone('UTC'));
				$endTime = $registDate->add(new DateInterval('P2D')); //2일
				$now = new DateTime('now', new DateTimeZone('UTC'));
				
				if ($now->getTimestamp() <= $endTime->getTimestamp())
				{
					if ($row['owner_uid'] != $character_uid)
					{
						if (_ConsumeCrystal($dbhandle, $account_id, $row["price"]))
						{
							if (DeleteExchangeItem($dbhandle, $id))
							{
								if (InsertExchangeLog($dbhandle, $row['owner_uid'], $character_uid, $row['item_uid'], $row['count'], $row['price'], $row['parts_type'], $row['enchant'], $row['is_viewed'], $row['optType1'], $row['optValue1'], $row['optType2'], $row['optValue2'], $row['optType3'], $row['optValue3'], $row['optType4'], $row['optValue4'], $row['durability'], $row['created_time'], $row['register_date']))
								{
									$insert_id = mysqli_insert_id($dbhandle);
									if(SendExchangeMail($dbhandle, $character_uid, $row['item_uid'], $row['count'], $row['enchant'], $insert_id, $lang))
									{
										$return = "BUY_EXCHANGE_ITEM_OK";
										$error = "";

										mysqli_commit($dbhandle);
									}
									else
									{
										$return = "BUY_EXCHANGE_ITEM_SEND_MAIL_FAIL";
										$error = "Send mail failed";

										mysqli_rollback($dbhandle);
									}
								}
								else
								{
									$return = "BUY_EXCHANGE_ITEM_INSERT_LOG_FAIL";
									$error = "Insert exchange log failed";

									mysqli_rollback($dbhandle);
								}
							}
							else
							{
								$return = "BUY_EXCHANGE_ITEM_DELETE_FAIL";
								$error = "Delete exchange item failed";

								mysqli_rollback($dbhandle);
							}
						}
						else
						{
							$return = "BUY_EXCHANGE_ITEM_NOT_ENOUGH_CRYSTAL";
							$error = "Not enough crystal";

							mysqli_rollback($dbhandle);
						}
					}
					else
					{
						$return = "BUY_EXCHANGE_ITEM_SELLER_BUYER_SAME_PERSON";
						$error = "Seller Buyer same person";

						mysqli_rollback($dbhandle);
					}
					
				}
				else
				{
					$return = "BUY_EXCHANGE_ITEM_EXPIRATION";
					$error = "Expiration date";

					mysqli_rollback($dbhandle);
				}
			}
			else
			{
				$return = "NOT_EXIST_EXCHANGE_ITEM";
				$error = "";

				mysqli_rollback($dbhandle);
			}
		}
		else
		{
			$return = "DB_ERROR";
			$error = mysqli_error($dbhandle);

			mysqli_rollback($dbhandle);
		}
	}

	

	$response = array('result'=>$return,'error'=>$error,'list'=>"");

	$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($response);
		
	mysqli_close($dbhandle);
}

$id = $_GET['id'];
$character_uid = $_GET['character_uid'];
$account_id = $_GET['account_id'];
$login_key = $_GET['login_key'];
$lang = $_GET['lang'];

if(CheckValidatedServerIP())
{
	BuyExchangeItem($id, $character_uid, $account_id, $login_key, $lang);
}
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	));
}

?>