<?php
include 'common.php';

function DeleteCharacterMail($dbhandle, $mail_id)
{
	//Delete Mail
	$query = "DELETE from mail_box_character where id=".$mail_id;
	$result = @mysqli_query($dbhandle,$query);
	if($result != 1)
	{		
		return false;
	}
	return true;
}

function NormalMailReceive($dbhandle, $character_uid, $mail_id, $item_id, $item_count, $item_type, $item_overlap)
{
	DeleteCharacterMail($dbhandle, $mail_id);

	$query = "INSERT INTO owned_item (character_uid, item_uid, count, is_equiped, parts_type) VALUES (".$character_uid.",".$item_id.",".$item_count.",0,".$item_type." )";
	if(AlreadyExistsItem($dbhandle, $character_uid, $item_id))
	{
		if ($item_overlap === "1")
		{
			$query = "UPDATE owned_item SET count=count+".$item_count." WHERE character_uid=".$character_uid." AND item_uid=".$item_id;
		}
	}
	
	$result = @mysqli_query($dbhandle,$query);
	if($result != 1)
	{		
		return false;
	}
	return true;
}


function ExchangeLogMailReceive($dbhandle, $character_uid, $mail_id, $item_overlap, $exchange_id)
{
	DeleteCharacterMail($dbhandle, $mail_id);

	$stmt = $dbhandle->prepare("SELECT * FROM exchange_log WHERE id=? AND buyer_uid=?");	
	$stmt->bind_param("ii", $exchange_id, $character_uid);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			mysqli_stmt_free_result($stmt);

			$query = "INSERT INTO owned_item (character_uid, item_uid, count, parts_type, enchant, is_viewed, optType1, optValue1, optType2, optValue2, optType3, optValue3, optType4, optValue4, durability, created_time)
			 VALUES (".$character_uid.",".$row["item_uid"].",".$row["count"].",".$row["parts_type"].",".$row["enchant"].",0,'".$row["optType1"]."',".$row["optValue1"].",'".$row["optType2"]."',".$row["optValue2"].",'".$row["optType3"]."',".$row["optValue3"].",'".$row["optType4"]."',".$row["optValue4"].",".$row["durability"].",'".$row["created_time"]."' )";
			if(AlreadyExistsItem($dbhandle, $character_uid, $row["item_uid"]))
			{
				if ($item_overlap === "1")
				{
					$query = "UPDATE owned_item SET count=count+".$row["count"]." WHERE character_uid=".$character_uid." AND item_uid=".$row["item_uid"];
				}
			}

			$result2 = @mysqli_query($dbhandle,$query);
			if($result2 != 1)
			{		
				return false;
			}
			return true;
		}
	}
	else
	{
		//$error = mysqli_error($dbhandle);
	}
	return false;
}
function ExchangeItemMailReceive($dbhandle, $character_uid, $mail_id, $item_overlap, $exchange_id)
{
	DeleteCharacterMail($dbhandle, $mail_id);

	$stmt = $dbhandle->prepare("SELECT * FROM exchange_item WHERE is_cancel=1 AND id=? AND owner_uid=?");	
	$stmt->bind_param("ii", $exchange_id, $character_uid);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			mysqli_stmt_free_result($stmt);

			$query = "INSERT INTO owned_item (character_uid, item_uid, count, parts_type, enchant, is_viewed, optType1, optValue1, optType2, optValue2, optType3, optValue3, optType4, optValue4, durability, created_time)
			 VALUES (".$character_uid.",".$row["item_uid"].",".$row["count"].",".$row["parts_type"].",".$row["enchant"].",0,'".$row["optType1"]."',".$row["optValue1"].",'".$row["optType2"]."',".$row["optValue2"].",'".$row["optType3"]."',".$row["optValue3"].",'".$row["optType4"]."',".$row["optValue4"].",".$row["durability"].",'".$row["created_time"]."' )";
			if(AlreadyExistsItem($dbhandle, $character_uid, $row["item_uid"]))
			{
				if ($item_overlap === "1")
				{
					$query = "UPDATE owned_item SET count=count+".$row["count"]." WHERE character_uid=".$character_uid." AND item_uid=".$row["item_uid"];
				}
			}

			$result2 = @mysqli_query($dbhandle,$query);
			if($result2 != 1)
			{		
				return false;
			}

			DeleteExchangeItem($dbhandle, $character_uid, $exchange_id);
			return true;
		}
	}
	else
	{
		//$error = mysqli_error($dbhandle);
	}
	return false;
}
function DeleteExchangeItem($dbhandle, $character_uid, $exchange_id)
{
	$stmt = $dbhandle->prepare("DELETE FROM exchange_item WHERE is_cancel=1 AND id=? AND owner_uid=?");
	$stmt->bind_param("ii",  $exchange_id, $character_uid);
	$result = $stmt->execute();
	$stmt->close();
	
	if($result)
	{
		return true;
	}
	return false;
}

function ReceiveCharacterMail($character_uid, $account_id, $login_key, $group_mail_id, $group_item_id, $group_item_count, $group_item_type, $group_item_overlap)
{
	$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 = "RECEIVE_MAIL_OK";
	$error = "";
	
	$split = ",";
	$arrMailIds = explode($split, $group_mail_id);
	$arrItemIds = explode($split, $group_item_id);
	$arrItemCount = explode($split, $group_item_count);
	$arrItemTypes = explode($split,$group_item_type);
	$arrItemOverlap = explode($split, $group_item_overlap);

	for($i=0;$i< sizeof($arrMailIds);$i++)
	{
		$stmt = $dbhandle->prepare("SELECT * FROM mail_box_character WHERE id=?");	
		$stmt->bind_param("i", $arrMailIds[$i]);
		$stmt->execute();
		$result = $stmt->get_result();
		$row = $result->fetch_assoc();
		
		mysqli_stmt_free_result($stmt);

		$type = $row["type"];
		
		if($type === "Normal")
		{
			$receive = NormalMailReceive($dbhandle, $character_uid, $arrMailIds[$i], $arrItemIds[$i], $arrItemCount[$i], $arrItemTypes[$i], $arrItemOverlap[$i]);
			if (!$receive)
			{
				$response = "RECEIVE_MAIL_FAILED";
				break;
			}
		}
		else if ($type === "Exchange_log")
		{
			$receive = ExchangeLogMailReceive($dbhandle, $character_uid, $arrMailIds[$i], $arrItemOverlap[$i], $row["exchange_id"]);
			if (!$receive)
			{
				$response = "RECEIVE_MAIL_FAILED";
				break;
			}
		}
		else if ($type === "Exchange_item")
		{
			$receive = ExchangeItemMailReceive($dbhandle, $character_uid, $arrMailIds[$i], $arrItemOverlap[$i], $row["exchange_id"]);
			if (!$receive)
			{
				$response = "RECEIVE_MAIL_FAILED";
				break;
			}
		}
		else
		{
			$response = "RECEIVE_MAIL_FAILED";
			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,'list_mail_id'=>$group_mail_id));
}

$json = json_decode(file_get_contents('php://input'));
$character_uid = $json->character_uid;
$account_id = $json->account_id;
$login_key = $json->login_key;
$group_mail_id = $json->group_mail_id;
$group_item_id = $json->group_item_id;
$group_item_count = $json->group_item_count;
$group_item_type = $json->group_item_type;
$group_item_overlap = $json->group_item_overlap;



if(CheckValidatedServerIP())
{
	ReceiveCharacterMail($character_uid, $account_id, $login_key, $group_mail_id, $group_item_id, $group_item_count, $group_item_type, $group_item_overlap);
}
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	));
}

?>