<?php
include 'common.php';

include 'wallet_common.php';








function CheckDup_Tx($dbhandle, $tx_hash)
{
	
	
	$stmt = $dbhandle->prepare("SELECT COUNT(*) as cnt FROM wallet_exchange_elt_to_wp_log WHERE tx_hash=?");	
	$stmt->bind_param("s", $tx_hash);
	$stmt->execute();
	$result = $stmt->get_result();	
	
	if($result)
	{	
		if($row = $result->fetch_assoc())
		{
			mysqli_stmt_free_result($stmt);

			if($row["cnt"] > 0)
			{
				return false;
			}
			else
			{
				return true;
			}
			
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}		
}

function LogObtainCrystal($dbhandle,$account_id,$character_uid, $tx_hash, $elt_amount, $crystal_amount)
{
	
	if(!CheckDup_Tx($dbhandle, $tx_hash))
	{
		$response = "EXCHANGE_ELT_TO_WP_FAILED";
		$error = "tx duplication error" ;
		EchoResponse($response, $error);
		exit;
				
		return false;
	}
	
	$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);

			$prev_crystal = $row["cash"];			
		
			$stmt2 = $dbhandle->prepare("INSERT INTO wallet_exchange_elt_to_wp_log (user_id, character_uid,  elt_amount, wp_amount, prev_wp, tx_hash) values(?,?,?,?,?,?)");
			$stmt2->bind_param("siiiis", $account_id, $character_uid, $elt_amount, $crystal_amount, $prev_crystal, $tx_hash);
			$result2 = $stmt2->execute();
			
			$stmt2->close();
			
			if($result2)
			{
				return true;
			}
			else
			{
				$response = "EXCHANGE_ELT_TO_WP_FAILED&LOG_INSERT_ERROR";
				$error = mysqli_error($dbhandle);				
				//$response = $account_id .",". $character_uid ."," . $elt_amount .",". $wp_amount ."," . $prev_wp .",".  $tx_hash ;
				EchoResponse($response,$error);
				exit;
				
				return false;
			}
			

			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}


function ObtainCrystal($dbhandle, $account_id,$character_uid, $crystal_amount)
{			
	if($crystal_amount >0)
	{			
		
		$current_crystal = GetCrystal($dbhandle, $account_id);
		
		if($current_crystal != -1)
		{
			if($current_crystal + $crystal_amount > PHP_INT_MAX)
			{
				$error = "Can't obtain wp any more (Max Total Amount Error)";
				return $error;
			}
			else
			{
				
				$stmt = $dbhandle->prepare("update account set cash=cash+? where user_id=?");
				$stmt->bind_param("is", $crystal_amount, $account_id);
				$result = $stmt->execute();
				$stmt->close();
				
				
				$error = "";
				if($result)
				{
					return "SUCCESS";
				}
				else
				{
					$error = mysqli_error($dbhandle);
					return $error;
				}	
				 
			}
		}
		else
		{
			$error = "get current wp failed!";
			return $error;
		}
		
		
	}
	else
	{
		$error = "invalid  amount";
		return $error;
	}
 
   
}

function ExchangeTokenToCrystal($account_id, $login_key, $character_uid, $wallet_pwd_hash, $token_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_ELT_TO_CRYSTAL_FAILED";
	$error = "";
	
	
	//1. 월렛정보 가져와서 //현재 wallet_address 는 사용하지 않음
	list($wallet_id,$wallet_address) = GetWalletInfo($dbhandle, $account_id,$login_key);
		
	
	//2. wallet api url 로 exchange request 해야함.				
	$checksum = md5($wallet_id . EXCHANGE_CHECKSUM . $wallet_pwd_hash . $token_amount);
	// get함수 호출	
	$curl_response = get(WALLET_API_URL .'/_burn_token', array(
		'wallet_id' => $wallet_id,
		'wallet_pwd_hash'=> $wallet_pwd_hash,
		'amount_to_burn' => $token_amount,
		'app_key' => $app_key,
		'checksum' => $checksum));	
	$resObj = json_decode($curl_response);
	//3. check tx 
	if($resObj !=null && $resObj->response == 'LOG_SUCCESS_BURN_TX_PENDING')
	{
		$crystal_amount = $token_amount; //todo : exchange rate
		$tx_hash = $resObj->tx;
		
		
	
		//2. WP obtain log 		
		if(LogObtainCrystal($dbhandle, $account_id,$character_uid, $tx_hash, $token_amount, $crystal_amount))
		{
			$response = "LOG_SUCCESS_BURN_TX_PENDING";	
			
			//3. obtain wp 
			
			// $result = ObtainCrystal($dbhandle, $account_id,$character_uid, $token_amount, $crystal_amount);
			// if($result == "SUCCESS")
			// {
			// 	$response = "EXCHANGE_ELT_TO_WP_OK";	
			// }
			// else
			// {
			// 	$error = $result;
			// }
		}
		else
		{
			$error = "WP obtain log error";
		}
		
		
	}
	else
	{
		if($resObj == null)
		{
			$error = "Transaction is not available";
		}
		else
		{
			
			$error =  $resObj->response;
		}			
		

	}
	
	
	 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'=>$tx_hash,'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;
$token_amount = $json->token_amount;  // token amount to burn
$wallet_pwd_hash = $json->wallet_pwd_hash;
$checksum = $json->checksum;
	
$check1 = $account_id . $login_key . $character_uid;	
$check2 = $wallet_pwd_hash . $token_amount ;
$app_key = 'test';

if(CheckSum($check1,$check2,$checksum))
{	
	ExchangeTokenToCrystal($account_id, $login_key, $character_uid, $wallet_pwd_hash, $token_amount, $app_key);
}



	

?>