<?php
include 'common.php';

include 'wallet_common.php';




function GetTxInfo($dbhandle, $tx_hash)
{
	
	
	$stmt = $dbhandle->prepare("SELECT user_id, wp_amount 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);			

			return array($row["user_id"],$row["wp_amount"]);		
		}
		
	}
	
	return null;
}




function IsPendingTxExist($dbhandle, $tx_hash, $tx_type)
{
	if($tx_type == 'burn')
	{
		$stmt = $dbhandle->prepare("SELECT COUNT(*) as cnt FROM wallet_exchange_elt_to_wp_log WHERE tx_hash=? and completed=0 ");	
		$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 true;
				}
				
				
			}
			
		}
	}
	else if($tx_type == 'mint')
	{
		$stmt = $dbhandle->prepare("SELECT COUNT(*) as cnt FROM wallet_exchange_wp_to_elt_log WHERE tx_hash=? and tx_status=0 ");	
		$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 true;
				}
				
				
			}
			
		}
	}
	else
	{
		return false;
	}
}



function LogUpdate_ExchangeTx($dbhandle, $tx_hash, $tx_status, $tx_type, $completed)
{
	
	//$now = new DateTime();
	//$now->setTimezone(new DateTimeZone('Asia/Seoul'));
	//$strTime =  date_format($now, "Y-m-d H:i:s");
	if($tx_type == 'burn')
	{
		$stmt = $dbhandle->prepare("UPDATE wallet_exchange_elt_to_wp_log set completed = ?, tx_status=? where tx_hash =? ");
		$stmt->bind_param("iss", $completed, $tx_status, $tx_hash);
		$result = $stmt->execute();
		
		$stmt->close();
		
		if($result)
		{
			return true;
		}
		else
		{
			$response = "EXCHANGE_LOG_UPDATE_ERROR";
			$error = mysqli_error($dbhandle);				
			//$response = $account_id .",". $character_uid ."," . $elt_amount .",". $wp_amount ."," . $prev_wp .",".  $tx_hash ;
			EchoResponse($response,$error);
			exit;		
			
		}
		
	
		return false;
	}
	else if($tx_type == 'mint')
	{
		

		$stmt = $dbhandle->prepare("UPDATE wallet_exchange_wp_to_elt_log set completed = ?, tx_status = ? where tx_hash =? ");
		$stmt->bind_param("iss", $completed, $tx_status, $tx_hash);
		$result = $stmt->execute();
		
		$stmt->close();
		
		if($result)
		{
			return true;
		}
		else
		{
			$response = "EXCHANGE_LOG_UPDATE_ERROR";
			$error = mysqli_error($dbhandle);				
			//$response = $account_id .",". $character_uid ."," . $elt_amount .",". $wp_amount ."," . $prev_wp .",".  $tx_hash ;
			EchoResponse($response,$error);
			exit;		
			
		}
		

		return false;

	}
	else
	{
		return false;
	}
	
	
}


function ObtainCrystal($dbhandle, $account_id, $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 ExchangeOnEvent($tx_hash)
 {
	$dbhandle = DB_Connect();
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");
	
	
	
	$response = "EXCHANGE_ELT_TO_CRYSTAL_FAILED";
	$error = "";
	
	//1. check if tx is mined
	$curl_response = get(WALLET_API_URL .'/check_tx_status', array(
	'tx_hash' => $tx_hash));	
	$resObj = json_decode($curl_response);

	if($resObj !=null && $resObj->response == '1')
	{
		//$error = "status:" . $resObj->response;
		$txStatus = $resObj->response;
		$txType = $resObj->type;
		$error = "tx_type:" . $txType;


		
		if($txType == 'burn')
		{
			if(IsPendingTxExist($dbhandle, $tx_hash, $txType))
			{
				//2. crystal obtain log 		
				$completed = 1;
				if(LogUpdate_ExchangeTx($dbhandle, $tx_hash, $txStatus, $txType, $completed))
				{
				// 	//3. obtain crystal 
					list($account_id,$crystal_amount) = GetTxInfo($dbhandle, $tx_hash);
						
					$result = ObtainCrystal($dbhandle, $account_id, $crystal_amount);
					if($result == "SUCCESS")
					{				
						$current_crystal = GetCrystal($dbhandle, $account_id);
						$response = "EXCHANGE_ELT_TO_CRYSTAL_OK";	
					}
					else
					{
						$error = $result;
					}
				}
			}
			else
			{
				$response = "EXCHANGE_TX_NOT_EXIST";
				$error = "The transaction is not exist or already competed" ;
			}
		} 
		else if($txType == 'mint')
		{
			$completed = 1;
			if(LogUpdate_ExchangeTx($dbhandle, $tx_hash, $txStatus, $txType, $completed))
			{
				//list($account_id,$crystal_amount) = GetTxInfo($dbhandle, $tx_hash);
				//$current_crystal = GetCrystal($dbhandle, $account_id);
				$response = "EXCHANGE_CRYSTAL_TO_ELT_OK";	
			}


		}
		else
		{
			$response = "WRONG_TX_TYPE";
			$error = "tracsaction type is wrong";
		}			

	}
	// failed tx 
	else if($resObj !=null && $resObj->response == '0')
	{
		//@todo : 실패한 블록이므로, 다시 체크 할 필요 없으므로  tx_status =0, completed=1 로 업데이트를 하고
		// burn 일 경우는 크리스탈도 충전이 안됬으니 완료.
		// *** mint 일 경우는 미리 소진시킨 크리스탈을 환원 가능하도록 UI 제공해야 한다. ***
		$txStatus = $resObj->response;
		$txType = $resObj->type;
		$completed = 1;
		if(LogUpdate_ExchangeTx($dbhandle, $tx_hash, $txStatus, $txType, $completed))
		{
			$error = "status:" . $resObj->response;		
			$response = "EXCHANGE_TX_STATUS_FAILED";
		}	
	}
	//still pending
	else if($resObj !=null && $resObj->response == '')
	{
		$error = "status:" . $resObj->response;		
		$response = "EXCHANGE_TX_STATUS_PENDING";	
		
	}
	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, 'crystal'=>$current_crystal, 'error'=>$error));
 }


$json = json_decode(file_get_contents('php://input'));
$tx_hash = $json->tx_hash;

ExchangeOnEvent($tx_hash);

	

?>