<?php
include 'common.php';


function AlreadyExistsEvent($dbhandle,$event_id, $account_id)
{
	$return =false;
	
	
	$stmt = $dbhandle->prepare("select count(*) as cnt from event_dailycheck_data where event_id=? and account_id=?");	
	$stmt->bind_param("is", $event_id, $account_id);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	mysqli_stmt_free_result($stmt);
	
	if($num["cnt"] > 0)
	{
		$return = true;
	}
	
	return $return;
}

function InsertCheckEventData($dbhandle, $event_id, $account_id, $current_time)
{
	$last_rewarded = "";
	$day = GetDailyCheckTerm($dbhandle, $event_id);
	for ($i=0;$i<$day;$i++)
	{
		if ($i < $day - 1)
		{
			$last_rewarded = $last_rewarded."0/";
		}
		else
		{
			$last_rewarded = $last_rewarded."0";
		}
	}
	$query = "INSERT INTO event_dailycheck_data (event_id, account_id, last_checked, last_rewarded, last_check_time) values (".$event_id.",'".$account_id."',1,'".$last_rewarded."','".$current_time."')"; 
	$result = @mysqli_query($dbhandle,$query);
	if($result == 1)
	{
		//성공
		$return = "DAILYCHECK_EVENT_DATA_OK";
		$error = "";
		$list = $event_id.",". $account_id.",1,".$last_rewarded.",".$current_time;

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckData($response);

		//mysqli_free_result($result);
	}
	else
	{
		//실패
		$return = "DAILYCHECK_EVENT_DATA_FAILED";
		$error = "Insert DB Error";
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckData($response);
	}
	
}
function CheckLastCheckDate($dbhandle, $event_id, $account_id, $current_time)
{
	$query = "SELECT * from event_dailycheck_data where event_id=".$event_id." and account_id='".$account_id."'";

	$result = mysqli_query($dbhandle, $query);
	if ($result)
	{
		//성공
		while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
		{
			$dateTime = new DateTime($row["last_check_time"]);
			$dateTime->modify('+1 day');
			$nextDay = new DateTime($dateTime->format('Y-m-d'));
			$curDay = new DateTime($current_time);

			if ($nextDay < $curDay)
			{
				//출석체크 가능
				UpdateCheckEventData($dbhandle, $event_id, $account_id, $current_time);
			}
			else
			{
				$return = "DAILYCHECK_EVENT_DATA_OK";
				$error = "";
				$list = $event_id.",". $account_id.",".$row["last_checked"].",".$row["last_rewarded"].",".$row["last_check_time"];

				$response = array('result'=>$return,'error'=>$error,'list'=>$list);
				EchoDailyCheckData($response);
			}

			break;
		}
		mysqli_free_result($result);
	}
	else
	{
		//실패
		$return = "DAILYCHECK_EVENT_DATA_FAILED";
		$error = "Select DB Error";
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckData($response);
	}
	
}
function UpdateCheckEventData($dbhandle, $event_id, $account_id, $current_time)
{
	$query = "UPDATE event_dailycheck_data set last_checked=last_checked+1, last_check_time='".$current_time."' where event_id=".$event_id." and account_id='".$account_id."'";
	$result = @mysqli_query($dbhandle,$query);
	if ($result == 1)
	{
		//성공
		$selectQuery = "SELECT * from event_dailycheck_data where event_id=".$event_id." and account_id='".$account_id."'";

		$selectResult = mysqli_query($dbhandle, $selectQuery);
		if ($selectResult)
		{
			//성공
			while($row = mysqli_fetch_array($selectResult, MYSQLI_ASSOC))
			{
				//성공
				$return = "DAILYCHECK_EVENT_DATA_OK";
				$error = "";
				$list = $event_id.",". $account_id.",".$row["last_checked"].",".$row["last_rewarded"].",".$current_time;

				$response = array('result'=>$return,'error'=>$error,'list'=>$list);
				EchoDailyCheckData($response);
			}
			mysqli_free_result($selectResult);
		}
		else
		{
			//실패
			$return = "DAILYCHECK_EVENT_DATA_FAILED";
			$error = "Select DB Error";
			$list = "";

			$response = array('result'=>$return,'error'=>$error,'list'=>$list);
			EchoDailyCheckData($response);
		}
		//mysqli_free_result($result);
	}
	else
	{
		//실패
		$return = "DAILYCHECK_EVENT_DATA_FAILED";
		$error = "Update DB Error";
		$list = "";

		$response = array('result'=>$return,'error'=>$error,'list'=>$list);
		EchoDailyCheckData($response);
	}
	
}

function DailyCheckEventData($event_id, $account_id, $login_key, $current_time){
	//Connect DB
	$dbhandle = DB_Connect();
	
	
	$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;
	}

	$existEvent = AlreadyExistsEvent($dbhandle, $event_id, $account_id);
	if ($existEvent)
	{
		CheckLastCheckDate($dbhandle, $event_id, $account_id, $current_time);
	}
	else
	{
		InsertCheckEventData($dbhandle, $event_id, $account_id, $current_time);
	}
	
	mysqli_close($dbhandle);
}

function EchoDailyCheckData($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);
}

function GetDailyCheckTerm($dbhandle, $event_id)
{
	$query = "SELECT day from event_dailycheck_info where event_id=".$event_id."";

	if ($result = mysqli_query($dbhandle, $query))
	{
		while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
		{
			return intval($row["day"]);
		}
	}
}

$json = json_decode(file_get_contents('php://input'));
$event_id = $json->event_id;
$account_id = $json->account_id;
$login_key = $json->login_key;
$current_time = $json->current_time;

if(CheckValidatedServerIP())
{
	DailyCheckEventData($event_id, $account_id, $login_key, $current_time);
}
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	));
}


?>