<?php
include 'common.php';


function FreeRecoveryExp($account_id, $character_uid, $login_key, $drop_exp_log_id, $drop_exp, $final_level, $final_exp, $add_stat)
{
	$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 = "";
	$error = "";
	$recovery_exp = "";

	if ($add_stat < 0)
	{
		$add_stat = 0;
	}

	if (IsRecoveryCheck($dbhandle, $drop_exp_log_id))
	{
		if (CheckExpAmount($dbhandle, $drop_exp_log_id, $drop_exp))
		{
			$recovery_exp = $drop_exp;
			if (FreeExpRecoveryCount($dbhandle, $character_uid))
			{
				IsRecoveryChange($dbhandle, $drop_exp_log_id);
				$update_query = "UPDATE character_list SET level=".$final_level.", character_exp=".$final_exp.", stat_point=stat_point+".$add_stat." WHERE user_id='".$account_id."' and character_uid=".$character_uid;
				$result = @mysqli_query($dbhandle,$update_query);
				if($result)
				{
					$response = "FREE_RECOVERY_EXP_OK";
				}
				else
				{
					$response = "DB_ERROR";
					$error = mysqli_error($dbhandle);
				}
			}
			else
			{
				$response = "FREE_RECOVERY_EXP_FAILED_EXHAUSTED";
			}
		}
		else
		{
			$response = "FREE_RECOVERY_EXP_FAILED_DROPEXP_MISMACH";
		}
	}
	else
	{
		$response = "FREE_RECOVERY_EXP_FAILED_ALREADY_RECOVERY";
	}
	

	 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,'recovery_exp'=>$recovery_exp,'final_level'=>$final_level, 'final_exp'=>$final_exp));
}
function IsRecoveryChange($dbhandle, $drop_exp_log_id)
{
	$now = new DateTime('now', new DateTimeZone('UTC'));
	$strNow = $now->format('Y-m-d H:i:s');
	$stmt = $dbhandle->prepare("UPDATE drop_exp_log SET is_recovery=1, recovery_time=? WHERE id=?");
	$stmt->bind_param("si", $strNow, $drop_exp_log_id);
	$result = $stmt->execute();
	$stmt->close();
}
function IsRecoveryCheck($dbhandle, $drop_exp_log_id)
{
	$stmt = $dbhandle->prepare("SELECT is_recovery FROM drop_exp_log WHERE id=?");	
	$stmt->bind_param("i", $drop_exp_log_id);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{
		if($row = $result->fetch_assoc())
		{
			mysqli_stmt_free_result($stmt);

			$is_recovery = $row["is_recovery"];
			if ($is_recovery == 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	else
	{
		$return = "DB FAIL";
		$error = mysqli_error($dbhandle);
		$value = "";
		return false;
	}
}
function CheckExpAmount($dbhandle, $drop_exp_log_id, $drop_exp)
{
	$stmt = $dbhandle->prepare("SELECT reduced_exp FROM drop_exp_log WHERE id=?");	
	$stmt->bind_param("i", $drop_exp_log_id);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{
		if($row = $result->fetch_assoc())
		{
			mysqli_stmt_free_result($stmt);

			$reduced_exp = $row["reduced_exp"];
			if ($drop_exp == $reduced_exp)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	else
	{
		$return = "DB FAIL";
		$error = mysqli_error($dbhandle);
		$value = "";
		return false;
	}
}

function FreeExpRecoveryCount($dbhandle, $character_uid)
{
    $stmt = $dbhandle->prepare("SELECT free_recovery_exp_count, last_used_time FROM free_recovery_exp WHERE character_uid=?");	
	$stmt->bind_param("i", $character_uid);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			$count = $row["free_recovery_exp_count"];
			$time = $row["last_used_time"];
			mysqli_stmt_free_result($stmt);


			$now = new DateTime();
			$now->setTimezone(new DateTimeZone('UTC'));
			$newNow = new DateTime($now->format('Y-m-d')); //utc
			$usedTime = new DateTime($time);
			$newUsedTime = new DateTime($usedTime->format('Y-m-d'));

			$intvl = $newNow->diff($newUsedTime);
			
			if ($intvl->days >= 1)
			{
				ResetRecoveryCount($dbhandle, $character_uid);
				return true;
			}
			else
			{
				if ($count >= 1)
				{
					DecreaseRecoveryCount($dbhandle, $character_uid);
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		else
		{
			InsertRecoveryCount($dbhandle, $character_uid);
			return true;
		}
	}
	else
	{
		$return = "DB FAIL";
		$error = mysqli_error($dbhandle);
		$value = "";
		return false;
	}
}

function ResetRecoveryCount($dbhandle, $character_uid)
{
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('UTC'));
	$strNow = $now->format('Y-m-d H:i:s');

	$stmt = $dbhandle->prepare("UPDATE free_recovery_exp SET free_recovery_exp_count=2, last_used_time=? WHERE character_uid=?");
	$stmt->bind_param("si", $strNow, $character_uid);
	$result = $stmt->execute();
	$stmt->close();
}
function DecreaseRecoveryCount($dbhandle, $character_uid)
{
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('UTC'));
	$strNow = $now->format('Y-m-d H:i:s');
	
	$stmt = $dbhandle->prepare("UPDATE free_recovery_exp SET free_recovery_exp_count=free_recovery_exp_count-1, last_used_time=? WHERE character_uid=?");
	$stmt->bind_param("si", $strNow, $character_uid);
	$result = $stmt->execute();
	$stmt->close();
}
function InsertRecoveryCount($dbhandle, $character_uid)
{
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('UTC'));
	$strNow = $now->format('Y-m-d H:i:s');
	
	$stmt = $dbhandle->prepare("INSERT INTO free_recovery_exp (character_uid, free_recovery_exp_count, last_used_time) VALUE(?,2,?)");	
	$stmt->bind_param("is", $character_uid, $strNow);
	$stmt->execute();
}

$json = json_decode(file_get_contents('php://input'));
$account_id = $json->account_id;
$character_uid = $json->character_uid;
$login_key = $json->login_key;
$drop_exp_log_id = $json->drop_exp_log_id;
$drop_exp = $json->drop_exp;
$final_level = $json->final_level;
$final_exp = $json->final_exp;
$add_stat = $json->add_stat;

if(CheckValidatedServerIP())
{
	FreeRecoveryExp($account_id, $character_uid, $login_key, $drop_exp_log_id, $drop_exp, $final_level, $final_exp, $add_stat);
}
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	));
}

?>