<?php
include 'common.php';

function InsertInvenPotion($account_id, $char_uid, $item_uid,$count,$parts_type)
{
	$dbhandle = DB_Connect();
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");
	
	
	if(AlreadyExistsItem($dbhandle, $char_uid,$item_uid ))
	{
		$query = "UPDATE owned_item set count=count+".$count." where character_uid=".$char_uid." and item_uid=".$item_uid;
	}
	else
	{
		$query = "INSERT INTO owned_item (character_uid, item_uid, count, is_equiped, parts_type) VALUES (".$char_uid.",".$item_uid.",1,0,".$parts_type." )";
		
	}
	
	
	//Query Result
	$result = @mysqli_query($dbhandle,$query);
	$response = "SAVE_INVEN_POTION_FAILED";
	$error = "";
	if($result)
	{
		$response = "SAVE_INVEN_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())
{
	InsertInvenPotion($_GET['account_id'], $_GET['char_uid'], $_GET['item_uid'], $_GET['count'],$_GET['parts_type']);

}
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	));
}

?>