<?php
include 'common.php';


function ConsumeCash_ChargeGold($account_id, $character_uid, $crystal_price, $charge_gold, $login_key)
{	
	//--------------------------------------------------
	$response = "CONSUME_CASH_FAILED";
	if($crystal_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_cash = GetCash($dbhandle,$account_id);
		if($current_cash < $crystal_price)
		{
			$error = "Not enough crystal";
		}
		else
		{
			
			$stmt = $dbhandle->prepare("update account set cash=cash-? where user_id=?");
			$stmt->bind_param("is", $crystal_price, $account_id);
			$result = $stmt->execute();
			//$stmt->close();
			
			
			
			
			$error = "";
			if($result)
			{
				
				$stmt = $dbhandle->prepare("update character_list set gold=gold+? where user_id=? and character_uid=?");
				$stmt->bind_param("isi", $charge_gold, $account_id,$character_uid);
				$result2 = $stmt->execute();				
				
				if($result2)
				{
					$response = "CONSUME_CASH_CHARGE_GOLD_OK";
					
					
				}
				
				_ConsumeCrystal_Log($dbhandle, $account_id, $crystal_price);
			}
			else
			{
				$response = "CONSUME_CASH_OK&CHARGE_GOLD_FAILED";
				$error = mysqli_error($dbhandle);
			}
			
			 $stmt->close();
		}
		
		mysqli_close($dbhandle);
		
	}
	else
	{
		$error = "invalid crystal 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())
{
	ConsumeCash_ChargeGold($_GET['account_id'], $_GET['character_uid'], $_GET['crystal_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	));
}

?>