<?php
include 'common.php';

function SetPotionUnEquiped($dbhandle,$char_uid,$owned_uid_unequip)
{
	//장착 해제 처리
	$query = "update owned_item set is_equiped=0 where owned_item_uid=".$owned_uid_unequip." and character_uid='".$char_uid."'";

	//Query Result
	$result = @mysqli_query($dbhandle,$query);
	if($result)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function SetPotionEquiped($account_id, $login_key, $char_uid, $owned_uid_equip, $owned_uid_unequip)
{
	$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;
	}
	
	//기존 장착중이던 포션은 unequip 처리 해야함
	if($owned_uid_unequip != -1)
		SetPotionUnEquiped($dbhandle,$char_uid,$owned_uid_unequip);
	
	
	//장착 처리
	$query = "update owned_item set is_equiped=1 where owned_item_uid=".$owned_uid_equip." and character_uid='".$char_uid."'";
	

	//Query Result
	$result = @mysqli_query($dbhandle,$query);
	$response = "EQUIP_POTION_FAILED";
	$error = "";
	if($result)
	{
		$response = "EQUIP_POTION_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));
}



if(CheckValidatedServerIP())
{
	$char_uid = $_GET['char_uid'];	
	$owned_uid_equip = $_GET['owned_uid_equip'];
	$account_id = $_GET['account_id'];
	$login_key = $_GET['login_key'];
	$owned_uid_unequip = $_GET['owned_uid_unequip'];
	
	SetPotionEquiped($account_id, $login_key,$char_uid, $owned_uid_equip,$owned_uid_unequip);
}
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	));
}

?>