<?php
include 'common.php';


function AlreadyExistsOwnedSkill($dbhandle,$char_uid, $skill_uid)
{
	$strQuery = "select count(*) from owned_skill where character_uid=".$char_uid." and skill_uid=".$skill_uid;
	if($query_result = mysqli_query($dbhandle, $strQuery)){
		$data = mysqli_fetch_row($query_result);
		if( $data[0] > 0 )
		{
			return true;
		}
	}
	
	return false;
}


function AutoSaveSkill($character_uid, $account_id, $login_key, $group_skill_id, $is_passive)
{
	$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 = "AUTO_SAVE_SKILL_FAILED";
	$error = "";

	$split = ",";

	$arrSkillIds = explode($split, $group_skill_id);

	for ($i=0; $i<sizeof($arrSkillIds);$i++)
	{
		if (AlreadyExistsOwnedSkill($dbhandle, $character_uid, $arrSkillIds[$i]))
		{
			$response = "AUTO_SAVE_SKILL_FAILED";
			$error = "AlreadyExistsOwnedSkill";
			break;
		}
		else
		{
			$insert_query = "INSERT INTO owned_skill (character_uid, skill_uid, level, is_passive) VALUES (".$character_uid.",".$arrSkillIds[$i].", 1,".$is_passive.")";
			$result = @mysqli_query($dbhandle,$insert_query);
			if($result)
			{
				$response = "AUTO_SAVE_SKILL_OK";
				$error = "";
			}
			else
			{
				$response = "AUTO_SAVE_SKILL_FAILED";
				$error = mysqli_error($dbhandle);
				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));
}

$json = json_decode(file_get_contents('php://input'));
$character_uid = $json->character_uid;
$account_id = $json->account_id;
$login_key = $json->login_key;
$group_skill_id = $json->group_skill_id;
$is_passive = $json->is_passive;




if(CheckValidatedServerIP())
{
	AutoSaveSkill($character_uid, $account_id, $login_key, $group_skill_id, $is_passive);
}
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	));
}


?>