<?php
include 'common.php';


function UpdateExpAndLevel_ByKillmonster($account_id, $char_uid, $level, $exp, $gold, $killed_monster_class, $quest_kill_count, $add_stat, $login_key)
{
	$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;
	}
	
	
	
	$update_query = "update character_list set level=".$level.", character_exp=".$exp.", gold = gold+".$gold.", quest_kill_count=quest_kill_count+".$quest_kill_count.", stat_point=stat_point+".$add_stat." where user_id='".$account_id."' and character_uid='".$char_uid."'";

	//Query Result
	$result = @mysqli_query($dbhandle,$update_query);
	$response = "SAVE_EXP_FAILED";
	$error = "";
	if($result)
	{
		$response = "SAVE_EXP_OK";
		// don't use for upate/insert query, because these query result is true/false, not mysqli_result object
		//mysqli_free_result($result); 
	}
	else
	{
		$error = mysqli_error($dbhandle);
	}
	
	 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, 'added_gold'=>$gold, 'added_stat_point'=>$add_stat, 'updated_level'=>$level, 'updated_exp'=>$exp, 'killed_monster_class'=>$killed_monster_class, 'quest_kill_count'=>$quest_kill_count));
}


$json = json_decode(file_get_contents('php://input'));
$account_id = $json->account_id;
$char_uid = $json->char_uid;
$login_key = $json->login_key;
$level = $json->level;
$exp = $json->exp;
$gold = $json->gold;
$killed_monster_class = $json->killed_monster_class;
$quest_kill_count = $json->quest_kill_count;
$add_stat = $json->add_stat;




if(CheckValidatedServerIP())
{
	UpdateExpAndLevel_ByKillmonster($account_id, $char_uid, $level, $exp, $gold, $killed_monster_class, $quest_kill_count, $add_stat, $login_key);

}
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	));
}

?>