<?php
include 'common.php';


function ConsumeWP_ChargeGold($account_id, $character_uid, $wp_price, $charge_gold, $login_key)
{	
	//--------------------------------------------------
	$response = "CONSUME_CASH_FAILED";
	if($wp_price >0)
	{
		
		$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;
		}
		
		$current_wp = GetWP($dbhandle,$account_id, $character_uid);
		if($current_wp < $wp_price)
		{
			$error = "Not enough WP : " . $current_wp;
		}
		else
		{
			
			
			
			$error = "";
			
				
			$stmt = $dbhandle->prepare("update character_list set wp=wp-? , gold=gold+? where user_id=? and character_uid=?");
			$stmt->bind_param("iisi", $wp_price, $charge_gold, $account_id,$character_uid);
			$result = $stmt->execute();				
			
			if($result)
			{
				$response = "CONSUME_WP_CHARGE_GOLD_OK";				
				
				_ConsumeWP_Log($dbhandle,$account_id, $character_uid, $wp_price);
			}
			else
			{
				$response = "CONSUME_WP_OK&CHARGE_GOLD_FAILED";
				$error = mysqli_error($dbhandle);
			}
				
			 $stmt->close();
			
		}
		
		mysqli_close($dbhandle);
		
	}
	else
	{
		$error = "invalid wp amount";
	}
 
    $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())
{
	ConsumeWP_ChargeGold($_GET['account_id'], $_GET['character_uid'], $_GET['wp_price'], $_GET['charge_gold'],$_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	));
}

?>