<?php
include 'common.php';

function OwnedTransformingUpgrade($account_id, $char_uid, $owned_transforming_uid, $card_inven_uid, $card_update_count, $gold_update, $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;
	}
	
	
	$error = "";
	if(UpdateTransformingCardCount($dbhandle, $char_uid, $card_inven_uid, $card_update_count ) && UpdateGold($dbhandle, $gold_update, $char_uid))
	{
		$response = "OWNED_TRANSFORMING_UPGRADE_FAILED";
		
		$update_query = "update owned_transforming set level=level+1 where owned_transforming_uid=".$owned_transforming_uid." and character_uid=".$char_uid;

		//Query Result
		$result = @mysqli_query($dbhandle,$update_query);			
		$error = "";
		if($result)
		{
			$response = "OWNED_TRANSFORMING_UPGRADE_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);
		}	
			
	}
	else
	{
		$response = "UPDATE_TRANSFORMING_CARD_COUNT_FAILED";
		$error = "DB Error";
	}
	
	 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())
{
	OwnedTransformingUpgrade($_GET['account_id'], $_GET['char_uid'], $_GET['owned_transforming_uid'], $_GET['card_inven_uid'], $_GET['card_update_count'], $_GET['gold_update'], $_GET['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	));
}

?>