<?php
include 'common.php';

include 'wallet_common.php';



function IsTxAvailable($wallet_id, $app_key)
{
	$checksum = md5($wallet_id . EXCHANGE_CHECKSUM . $app_key);
	$curl_response = get(WALLET_API_URL .'/is_tx_available', array(
		'wallet_id' => $wallet_id,			
			'app_key' => $app_key,
			'checksum' => $checksum));		

	//$resObj = json_decode($curl_response);
	if($curl_response == 'available')
	{
		return true;
	}
	
	return false;

}


function CosumeCrystal($dbhandle, $account_id,$character_uid, $crystal_amount_to_consume, $wallet_id, $app_key)
{			
	if($crystal_amount_to_consume >0 )
	{			
		if(IsTxAvailable($wallet_id, $app_key))
		{		
			
			$current_crystal = GetCrystal($dbhandle, $account_id);
			
			if($current_crystal != -1) // -1 is db error
			{
				
				
				
				if($current_crystal < $crystal_amount_to_consume)
				{
					$error = "Not enough Crystal";
					return $error;
				}
				else
				{				
					
					$stmt = $dbhandle->prepare("update account set cash=cash-? where user_id=?");
					$stmt->bind_param("is", $crystal_amount_to_consume, $account_id);
					$result = $stmt->execute();
					$stmt->close();
					
					
					
					$error = "";
					if($result)
					{
						return "CONSUME_SUCCESS";//true;
					}
					else
					{
						$error = mysqli_error($dbhandle);
						return $error;
					}
					
					 
				}
			}
			else
			{
				$error = "get current wp failed!";
				return $error;
			}
		}
		else
		{
			$error = "Transaction is not available";
			return $error;
		}
		
		
		
		
	}
	else
	{
		$error = "invalid amount";
		return $error;
	}
 
   
}

 

function LogUpdateConsumCrystal($dbhandle, $account_id,$character_uid,$seq, $tx_hash)
{
	$stmt = $dbhandle->prepare("update wallet_exchange_wp_to_elt_log set tx_hash=?  where user_id=? and character_uid=? and seq=?");
	$stmt->bind_param("ssis", $tx_hash, $account_id, $character_uid, $seq);
	$result = $stmt->execute();
	$stmt->close();
	
	
	$error = "";
	if($result)
	{
		return true;
	}
	else
	{
		$error = mysqli_error($dbhandle);
		return false;
	}
}

function LogConsumCrystal($dbhandle, $account_id, $character_uid, $consumed_crystal_amount, $token_amount)
{
		
	
	$stmt = $dbhandle->prepare("SELECT cash FROM account WHERE user_id=?");	
	$stmt->bind_param("s", $account_id);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			mysqli_stmt_free_result($stmt);

			$cur_crystal = $row["cash"];

				
			


			//$stmt2 = $dbhandle->prepare("insert into wallet_exchange_wp_to_elt_log (user_id, character_uid, wp_amount, elt_amount, cur_wp) values(?,?,?,?,?)");
			//$stmt2->bind_param("siiii", $account_id, $character_uid, $cur_crystal, $token_amount, $cur_wp);

			$stmt2 = $dbhandle->prepare("insert into wallet_exchange_wp_to_elt_log (user_id, character_uid, wp_amount, elt_amount, cur_wp) values(?,?,?,?,?)");
			$stmt2->bind_param("siiii", $account_id, $character_uid, $consumed_crystal_amount, $token_amount, $cur_crystal);
			$result2 = $stmt2->execute();
			
			$stmt2->close();
			
			if($result2)
			{
				$newNo = mysqli_insert_id($dbhandle);
				return $newNo;
			}
			else
			{			
				
				return -1;
			}
			

			
		}
		else
		{
			return -2;
		}
	}
	else
	{
		return -3;
	}
}


function ExchangeCrystalToToken($account_id, $login_key, $character_uid, $wallet_pwd_hash, $crystal_amount, $app_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();
		return;
	}
	$response = "EXCHANGE_CONSUME_CRYSTAL_FAILED";
	$error = "";
	
	
	
			
	
	//1. 월렛정보 가져와서
	list($wallet_id,$wallet_address) = GetWalletInfo($dbhandle, $account_id,$login_key);
	
	//2. 먼저 crystal 소모
	$token_amount = $crystal_amount; //todo : 
	$result = CosumeCrystal($dbhandle, $account_id,$character_uid, $crystal_amount, $wallet_id, $app_key);
	
	//EchoResponse('test',$result);
	//mysqli_close($dbhandle);
	//return;
	
	if($result == 'CONSUME_SUCCESS')	
	{
		//3. WP 소모로그 및 seq구하기(wallet_exchange_wp_to_elt_log)
		$seq = LogConsumCrystal($dbhandle,$account_id,$character_uid, $crystal_amount, $token_amount);		
		$error = $seq;
		
		$checksum = md5($seq . EXCHANGE_CHECKSUM . $wallet_id . $crystal_amount);
			
		$txHash = null;
		//4. wallet api url 로 exchange request 해야함.		
		$curl_response = get(WALLET_API_URL .'/_mint_token', array(
		'wallet_id' => $wallet_id,
			'wallet_pwd_hash'=> $wallet_pwd_hash,
			'amount_to_mint' => $token_amount,
			'seq' => $seq,
			'app_key' => $app_key,
			'checksum' => $checksum));		

		$resObj = json_decode($curl_response);
		
		if($resObj != null && $resObj->response == "LOG_SUCCESS_MINT_TX_PENDING")
		{
			//5.wallet api 로 부터 OK 가 오면, $seq 값, $tx 값으로 wallet_exchange_wp_to_elt_log 로그 업데이트 하고 tx_status는 아직 0 이다.
			// 나중에 wallet_exchange_on_event에서 pending tx 가 처리 될 경우 tx_status=1이 된다.	
			if(LogUpdateConsumCrystal($dbhandle, $account_id,$character_uid, $resObj->seq, $resObj->tx))
			{
				$response = "LOG_CONSUME_CRYSTAL_OK";
				$txHash = $resObj->tx;
				//$error = $resObj->tx .":".$resObj->seq ;
			}	
		}
		else 
		{
			if($resObj != null)
			{
				$response = $resObj->response;
				$error = $resObj->response;
			}
			else
			{
				$response = "NO_RESPONSE_FROM_API_SERVER";
				$error = "No response error";
			}
			
		}
		
		
	}
	else
	{
		$error = $result; // if not success, $result is 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,'tx_hash'=>$txHash,'error'=>$error));
}

$json = json_decode(file_get_contents('php://input'));
$account_id = $json->account_id;
$login_key = $json->login_key;
$character_uid = $json->character_uid;
$crystal_amount = $json->wp_amount;
$wallet_pwd_hash = $json->wallet_pwd_hash;
$checksum = $json->checksum;
		
$check = $wallet_pwd_hash.$crystal_amount;
$app_key = 'test';
if(CheckSum($account_id,$check,$checksum))
{	
	ExchangeCrystalToToken($account_id, $login_key, $character_uid, $wallet_pwd_hash, $crystal_amount, $app_key);
}



	

?>