<?php
include 'common.php';


function DailyCheckEventCheck($event_id, $account_id, $login_key, $index, $lang, $multiCountInOneSlot){
	//Connect DB
	$dbhandle = DB_Connect();
	
	
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");

	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;");
	

	if(!CheckLoginKey($dbhandle, $account_id, $login_key))
	{
		PrintLoginKeyError();
		mysqli_close($dbhandle);
		return;
	}

	
	$stmt = $dbhandle->prepare("SELECT last_checked, last_rewarded from event_dailycheck_data where event_id=? and account_id=?");	
	$stmt->bind_param("is", $event_id, $account_id);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			$last_checked = $row["last_checked"];
			$rewards = $row["last_rewarded"];
			mysqli_stmt_free_result($stmt);

			UpdateDailyCheckReward($dbhandle, $event_id, $account_id, $index, $last_checked, $rewards, $lang, $multiCountInOneSlot);
		}
	}
	else
	{
		//실패
		$return = "DAILYCHECK_EVENT_CHECK_FAILED";
		$error = mysqli_error($dbhandle);
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckCheck($response);
	}

	mysqli_close($dbhandle);
}

function UpdateDailyCheckReward($dbhandle, $event_id, $account_id, $index, $last_checked, $rewards, $lang, $multiCountInOneSlot)
{
	$split = "/";

	$arrReward = explode($split,$rewards);
	if (sizeof($arrReward) <= $index || $index < 0)
	{
		//실패
		$return = "DAILYCHECK_EVENT_CHECK_FAILED";
		$error = "Index is out of range";
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckCheck($response);
		return;
	}

	if ($arrReward[$index] === "0")
	{
		$last_rewarded = "";
		for ($i=0;$i<sizeof($arrReward);$i++)
		{
			if ($index == $i)
			{
				$last_rewarded = $last_rewarded."1";
			}
			else
			{
				$last_rewarded = $last_rewarded.$arrReward[$i];
			}
			
			if ($i != sizeof($arrReward) - 1)
			{
				$last_rewarded = $last_rewarded."/";
			}
		}

		$stmt = $dbhandle->prepare("UPDATE event_dailycheck_data set last_rewarded=? where event_id=? and account_id=?");
		$stmt->bind_param("sis", $last_rewarded, $event_id, $account_id);
		$result = $stmt->execute();
		$stmt->close();

		if($result)
		{
			GetRewardInfo($dbhandle, $event_id, $account_id, $index, $last_checked, $last_rewarded, $lang, $multiCountInOneSlot);
		}
		else
		{
			//실패
			$return = "DAILYCHECK_EVENT_CHECK_FAILED";
			$error = mysqli_error($dbhandle);
			$list = "";

			$response = array('result'=>$return,'error'=>$error,'list'=>$list);
			EchoDailyCheckCheck($response);
		}
	}
	else
	{
		//실패
		//이미 보상 받음
		$return = "DAILYCHECK_EVENT_CHECK_FAILED";
		$error = "Already get a reward";
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckCheck($response);
	}
}
function GetRewardInfo($dbhandle, $event_id, $account_id, $index, $last_checked, $last_rewarded, $lang, $multiCountInOneSlot)
{
	$stmt = $dbhandle->prepare("SELECT rewards, rewards_count from event_dailycheck_info where event_id=?");	
	$stmt->bind_param("i", $event_id);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			$rewards = $row["rewards"];
			$rewards_count = $row["rewards_count"];
			mysqli_stmt_free_result($stmt);

			$split = "/";
			$arrRewards = explode($split,$rewards);
			$arrRewardsCount = explode($split,$rewards_count);

			$rewardID = $arrRewards[$index];
			$rewardCount = $arrRewardsCount[$index];
			if ($multiCountInOneSlot === "0")
			{
				$rewardCount = "1";
			}

			SendRewardItemByAccountMail($dbhandle, $event_id, $account_id, $rewardID, $rewardCount, $last_checked, $last_rewarded, $lang);
		}
	}
	else
	{
		//실패
		$return = "DAILYCHECK_EVENT_CHECK_FAILED";
		$error = mysqli_error($dbhandle);
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckCheck($response);
	}
}
function SendRewardItemByAccountMail($dbhandle, $event_id, $account_id, $rewardID, $rewardCount, $last_checked, $last_rewarded, $lang)
{
	$now = new DateTime();
	//$now->setTimezone(new DateTimeZone('UTC'));
	$strTime =  date_format($now, "Y-m-d H:i:s");

	$title = "";
	$content = "";
	if ($lang === 'kr')
	{
		$title = "[이벤트 보상]";
		$content = "출석 이벤트 보상";
	}
	else if ($lang === 'th')
	{
		$title = "[รางวัลกิจกรรม]";
		$content = "รางวัลกิจกรรม";
	}
	else
	{
		$title = "[Event reward]";
		$content = "Event reward";
	}
	

	$strQuery = "INSERT INTO mail_box_account (account_id, title, content, item_id, item_count, time_limit, time_send) VALUES ('".$account_id."', '".$title."', '".$content."', ".$rewardID.", ".$rewardCount.", 720, '".$strTime."')";

	//Query Result
	if($result = @mysqli_query($dbhandle, $strQuery))
	{
		//성공
		$return = "DAILYCHECK_EVENT_CHECK_OK";
		$error = "";
		$list = $event_id.",". $account_id.",".$last_checked.",".$last_rewarded;

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckCheck($response);
	}
	else
	{
		//실패
		$return = "DAILYCHECK_EVENT_CHECK_FAILED";
		$error = "Mail DB Insert Error";
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckCheck($response);
	}
}

function EchoDailyCheckCheck($response)
{
	$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);
}

$lang = $_GET['lang'];

$json = json_decode(file_get_contents('php://input'));
$event_id = $json->event_id;
$account_id = $json->account_id;
$login_key = $json->login_key;
$index = $json->index;
$multiCountInOneSlot = $json->multiCountInOneSlot;

if(CheckValidatedServerIP())
{
	DailyCheckEventCheck($event_id, $account_id, $login_key, $index, $lang, $multiCountInOneSlot);
}
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	));
}


?>