<?php


function PrintLoginKeyError()
{
	$response = "LOGIN_KEY_ERROR";	
	$error = "LOGIN_KEY_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));
}

function CheckSum($first,$last,$check_sum)
{
	
	$hash = md5($first . "codbs&#cofla" . $last);
	if($hash != $check_sum)
	{
		return false;
	}
	
	return true;
}

function CheckLoginKey($dbhandle, $account_id, $login_key)
{
	$return =false;
	
	
	$stmt = $dbhandle->prepare("select count(*) as cnt from account where user_id=? and login_key=?");	
	$stmt->bind_param("ss", $account_id, $login_key);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	if( $num["cnt"] > 0 )
	{
		$return = true;
	}
	
	mysqli_stmt_free_result($stmt);
	
	//$strQuery = "select count(*) from account where user_id='".$account_id."' and login_key='".$login_key."'";
	//if($query_result = mysqli_query($dbhandle, $strQuery)){
	//	$data = mysqli_fetch_row($query_result);
	//	if( $data[0] > 0 )
	//	{
	//		$return = true;
	//	}
	//	mysqli_free_result($query_result); 
	//}
	
	return $return;
}

function CheckServerVersion_v2($client_version)
{
	$dbhandle = DB_Connect();
		//Select DB
		$db_selected = mysqli_select_db($dbhandle, DB_NAME)
		or die("Could not select db");
		
	$stmt = $dbhandle->prepare("select version from force_update_version order by id desc limit 1");	
	//$stmt->bind_param("ss", $account_id, $login_key);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	$game_version =  $num["version"];
	mysqli_stmt_free_result($stmt);
	
	mysqli_close($dbhandle);

	$client_ver_string = explode('.', $client_version );
	$server_ver_string = explode('.',$game_version);
	if($client_ver_string[0] < $server_ver_string[0] || $client_ver_string[1] < $server_ver_string[1]|| $client_ver_string[2] < $server_ver_string[2])
	{
		$response = "VERSION_FAILED"; 
		//$notice = "Please update new version";
		$notice = "최신버전으로 업데이트 해주세요";
		
		$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,'notice'=>$notice));
		return false;
	}
	return true;
}

function CheckServerVersion_v3($client_version, $platform, $lang)
{
	$dbhandle = DB_Connect();
		//Select DB
		$db_selected = mysqli_select_db($dbhandle, DB_NAME)
		or die("Could not select db");
		
	$stmt = $dbhandle->prepare("select version from force_update_version order by id desc limit 1");	
	//$stmt->bind_param("ss", $account_id, $login_key);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	$game_version =  $num["version"];
	mysqli_stmt_free_result($stmt);
	
	mysqli_close($dbhandle);

	$client_ver_string = explode('.', $client_version );
	$server_ver_string = explode('.',$game_version);
	if($client_ver_string[0] < $server_ver_string[0] || $client_ver_string[1] < $server_ver_string[1]|| $client_ver_string[2] < $server_ver_string[2])
	{
		$response = "VERSION_FAILED"; 
		$notice = "Please update new version";
		if($lang == 'kr')
			$notice = "최신버전으로 업데이트 해주세요";
		else
			$notice = "Please update new version";
		
		/*
		#if GOOGLE_STORE
    public static string MarketUrl = "market://details?id=com.Fingereyes.Elios";
#elif ONE_STORE
    public static string MarketUrl = "onestore://common/product/bg_update/OA00751734";
#else
    public static string MarketUrl = "market://details?id=com.Fingereyes.Elios";
#endif
		*/
		$download_url = "https://www.quantumchain.ai";
		if(strtolower($platform) == 'pc')
		{
			$download_url = "https://www.quantumchain.ai";
		}
		
		
		
		$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,'notice'=>$notice, 'download_url'=>$download_url));
		return false;
	}
	return true;
}

function ConsumeCash_v2($account_id,$price, $login_key)
{	
	//--------------------------------------------------
	$response = "CONSUME_CASH_FAILED";
	if($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();
			return;
		}
		
		$current_cash = GetCash($dbhandle,$account_id);
		if($current_cash < $price)
		{
			$error = "Not enough crystal";
		}
		else
		{
			
			$stmt = $dbhandle->prepare("update account set cash=cash-? where user_id=?");
			$stmt->bind_param("is", $price, $account_id);
			$result = $stmt->execute();
			$stmt->close();
			
			
			/* 
			$update_query = "update account set cash=cash-".$price." where user_id='".$account_id."'";
			$result = @mysqli_query($dbhandle,$update_query); */
			
			$error = "";
			if($result)
			{
				$response = "CONSUME_CASH_OK";
				// don't use for upate/insert query, because these query result is true/false, not mysqli_result object
				//mysqli_free_result($result); 
			}
			else
			{
				$error = mysqli_error($dbhandle);
			}
			
			 
		}
		
		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));
}

function ConsumeCash($account_id,$price)
{
	
	//--------------------------------------------------
	$response = "CONSUME_CASH_FAILED";
	if($price >0)
	{
		
		$dbhandle = DB_Connect();
		//Select DB
		$db_selected = mysqli_select_db($dbhandle, DB_NAME)
		or die("Could not select db");
		
		$current_cash = GetCash($dbhandle,$account_id);
		if($current_cash < $price)
		{
			$error = "Not enough crystal";
		}
		else
		{
			
			$stmt = $dbhandle->prepare("update account set cash=cash-? where user_id=?");
			$stmt->bind_param("is", $price, $account_id);
			$result = $stmt->execute();
			$stmt->close();
			
			/* $update_query = "update account set cash=cash-".$price." where user_id='".$account_id."'";
			//Query Result
			$result = @mysqli_query($dbhandle,$update_query); */
			
			$error = "";
			if($result)
			{
				$response = "CONSUME_CASH_OK";
				// don't use for upate/insert query, because these query result is true/false, not mysqli_result object
				//mysqli_free_result($result); 
			}
			else
			{
				$error = mysqli_error($dbhandle);
			}
			
			 
		}
		
		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));
}

function AddCash($dbhandle, $account_id, $amount)
{
	
	$stmt = $dbhandle->prepare("update account set cash=cash+? where user_id=?");
	$stmt->bind_param("is", $amount, $account_id);
	$result = $stmt->execute();
	$stmt->close();
			
			
	/* $update_query = "update account set cash=cash+".$amount." where user_id='".$account_id."'";
	$result = @mysqli_query($dbhandle,$update_query); */
	
	if($result)
	{
		return true;
	}
	
	return false;
}

function LogAddCrystal($dbhandle, $account_id, $character_uid, $type, $amount)
{
	// AddCash 이후에 이 함수를 호출해야함
	// $type종류 : UNKNOWN, EXCHANGE, DAILY_EVENT

	$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);

			$final_crystal = $row["cash"];

			$now = new DateTime();
			//$now->setTimezone(new DateTimeZone('Asia/Seoul'));
			$strTime =  date_format($now, "Y-m-d H:i:s");
		
			$stmt2 = $dbhandle->prepare("INSERT INTO crystal_add_log (user_id, character_uid, add_type, amount, final_crystal, log_time) values(?,?,?,?,?,?)");
			$stmt2->bind_param("sisiis", $account_id, $character_uid, $type, $amount, $final_crystal, $strTime);
			$result2 = $stmt2->execute();
			$stmt2->close();

			return true;
		}
	}
	else
	{
		return false;
	}
}

function GetCash($dbhandle, $account_id)
{
	$cash = 0;
	
	
	$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())
		{
			$cash = $row["cash"];
			mysqli_stmt_free_result($stmt);
		}
	}
	else{
		$error = mysqli_error($dbhandle);
	}
	
	/* $strQuery = "select cash from account where user_id='".$account_id."'";
	if($query_result = mysqli_query($dbhandle, $strQuery))
	{
		$data = mysqli_fetch_row($query_result);
		if(count($data) > 0)
		{			
			$cash = $data[0];
			
			mysqli_free_result($query_result); 
		}
	}
	else{
		$error = mysqli_error($dbhandle);
	}
	*/
	
	return $cash;
}

function GetGold($dbhandle, $account_id, $char_uid)
{
	$gold = 0;
	
	
	$stmt = $dbhandle->prepare("select gold from character_list where user_id=? and character_uid=?");	
	$stmt->bind_param("si", $account_id, $char_uid);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			$gold = $row["gold"];
			mysqli_stmt_free_result($stmt);
		}
	}
	else{
		$error = mysqli_error($dbhandle);
	}
	
	
	
	/* $strQuery = "select gold from character_list where user_id='".$account_id."' and character_uid=".$char_uid;
	if($query_result = mysqli_query($dbhandle, $strQuery))
	{
		$data = mysqli_fetch_row($query_result);
		if(count($data) > 0)
		{			
			$gold = $data[0];
			
			mysqli_free_result($query_result); 
		}
	}
	else{
		$error = mysqli_error($dbhandle);
	} */
	
	return $gold;
}

function ConsumeGold_v2($account_id, $char_uid, $gold_price, $login_key)
{
	$response = "CONSUME_GOLD_FAILED";
	if($gold_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();
			return;
		}
		
		
		$current_gold = GetGold($dbhandle,$account_id, $char_uid);
		if($current_gold < $gold_price)
		{
			$error = "Not enough gold";
		}
		else
		{
			
			$stmt = $dbhandle->prepare("update character_list set gold=gold-? where user_id=? and character_uid=?");
			$stmt->bind_param("isi", $gold_price, $account_id,$char_uid);
			$result = $stmt->execute();
			$stmt->close();
	
	
			/* $update_query = "update character_list set gold=gold-".$gold_price." where user_id='".$account_id."' and character_uid=".$char_uid;	
	
			$result = @mysqli_query($dbhandle,$update_query); */
			
			$error = "";
			if($result)
			{
				$response = "CONSUME_GOLD_OK";
				// don't use for upate/insert query, because these query result is true/false, not mysqli_result object
				//mysqli_free_result($result); 
			}
			else
			{
				$error = mysqli_error($dbhandle);
			}
			
			 
		}
		
		mysqli_close($dbhandle);
		
	}
	else
	{
		$error = "invalid gold 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));
}

function ConsumeGold($account_id, $char_uid, $gold_price)
{
	$response = "CONSUME_GOLD_FAILED";
	if($gold_price >0)
	{
		
		$dbhandle = DB_Connect();
		//Select DB
		$db_selected = mysqli_select_db($dbhandle, DB_NAME)
		or die("Could not select db");
		
		$current_gold = GetGold($dbhandle,$account_id, $char_uid);
		if($current_gold < $gold_price)
		{
			$error = "Not enough gold";
		}
		else
		{
			
			$stmt = $dbhandle->prepare("update character_list set gold=gold-? where user_id=? and character_uid=?");
			$stmt->bind_param("isi", $gold_price, $account_id,$char_uid);
			$result = $stmt->execute();
			$stmt->close();
			
			
			/* $update_query = "update character_list set gold=gold-".$gold_price." where user_id='".$account_id."' and character_uid=".$char_uid;
			
			$result = @mysqli_query($dbhandle,$update_query);
			 */
			$error = "";
			if($result)
			{
				$response = "CONSUME_GOLD_OK";
				// don't use for upate/insert query, because these query result is true/false, not mysqli_result object
				//mysqli_free_result($result); 
			}
			else
			{
				$error = mysqli_error($dbhandle);
			}
			
			 
		}
		
		mysqli_close($dbhandle);
		
	}
	else
	{
		$error = "invalid gold 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));
}

function DevUpdateGold_v2($account_id, $char_uid, $update_gold, $login_key)
{
	$response = "UPDATE_GOLD_FAILED";
	if($update_gold >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();
			return;
		}
		
		
		$stmt = $dbhandle->prepare("update character_list set gold=? where user_id=? and character_uid=?");
		$stmt->bind_param("isi", $update_gold, $account_id,$char_uid);
		$result = $stmt->execute();
		$stmt->close();
			
		
		/* $update_query = "update character_list set gold=".$update_gold." where user_id='".$account_id."' and character_uid=".$char_uid;		
		$result = @mysqli_query($dbhandle,$update_query); */
		
		$error = "";
		if($result)
		{
			$response = "UPDATE_GOLD_OK";
			// don't use for upate/insert query, because these query result is true/false, not mysqli_result object
			//mysqli_free_result($result); 
		}
		else
		{
			$error = mysqli_error($dbhandle);
		}
		
		 mysqli_close($dbhandle);
		
		}
	else
	{
		$error = "invalid gold 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));
}

function DevUpdateGold($account_id, $char_uid, $update_gold)
{
	$response = "UPDATE_GOLD_FAILED";
	if($update_gold >0)
	{
		
		$dbhandle = DB_Connect();
		//Select DB
		$db_selected = mysqli_select_db($dbhandle, DB_NAME)
		or die("Could not select db");
		
		
		$stmt = $dbhandle->prepare("update character_list set gold=? where user_id=? and character_uid=?");
		$stmt->bind_param("isi", $update_gold, $account_id,$char_uid);
		$result = $stmt->execute();
		$stmt->close();
		
		/* 
		$update_query = "update character_list set gold=".$update_gold." where user_id='".$account_id."' and character_uid=".$char_uid;		
		$result = @mysqli_query($dbhandle,$update_query);
		 */
		$error = "";
		if($result)
		{
			$response = "UPDATE_GOLD_OK";
			// don't use for upate/insert query, because these query result is true/false, not mysqli_result object
			//mysqli_free_result($result); 
		}
		else
		{
			$error = mysqli_error($dbhandle);
		}
		
		 mysqli_close($dbhandle);
		
		}
	else
	{
		$error = "invalid gold 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));
}

function AlreadyExistsItem($dbhandle,$char_uid, $item_uid)
{
	
	
	$return =false;
	
	
	$stmt = $dbhandle->prepare("select count(*) as cnt from owned_item where character_uid=? and item_uid=?");	
	$stmt->bind_param("ii", $char_uid, $item_uid);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	mysqli_stmt_free_result($stmt);
	
	if($num["cnt"] > 0)
	{
		$return = true;
	}
	
	/* $strQuery = "select count(*) from owned_item where character_uid=".$char_uid." and item_uid=".$item_uid;
	if($query_result = mysqli_query($dbhandle, $strQuery)){
		$data = mysqli_fetch_row($query_result);
		if( $data[0] > 0 )
		{
			$return = true;
		}
		mysqli_free_result($query_result); 
	}
	 */
	return $return;
}

function UpdatePetCardCount($dbhandle, $char_uid, $card_inven_uid, $card_update_count)
{
	if($card_update_count >0)
	{
		$stmt = $dbhandle->prepare("update owned_item set count=? where owned_item_uid=? and character_uid=?");
		$stmt->bind_param("iii", $card_update_count, $card_inven_uid,$char_uid);
		$result = $stmt->execute();
		$stmt->close();
		
		if($result)
		{
			return true;
		}
	}
	else	
	{
		$stmt = $dbhandle->prepare("delete from owned_item where owned_item_uid=? and character_uid=?");
		$stmt->bind_param("ii",  $card_inven_uid,$char_uid);
		$result = $stmt->execute();
		$stmt->close();
		
		if($result)
		{
			return true;
		}
	}
	
	return false;
}


function UpdateSkillBookCount($dbhandle, $char_uid, $book_inven_uid, $book_update_count)
{
	if($book_update_count >0)
	{
		$stmt = $dbhandle->prepare("update owned_item set count=? where owned_item_uid=? and character_uid=?");
		$stmt->bind_param("iii", $book_update_count, $book_inven_uid,$char_uid);
		$result = $stmt->execute();
		$stmt->close();
		
		if($result)
		{
			return true;
		}
		//$query = "update owned_item set count=".$book_update_count." where owned_item_uid=".$book_inven_uid." and character_uid=".$char_uid;
	}
	else	
	{
		$stmt = $dbhandle->prepare("delete from owned_item where owned_item_uid=? and character_uid=?");
		$stmt->bind_param("ii",  $book_inven_uid,$char_uid);
		$result = $stmt->execute();
		$stmt->close();
		
		if($result)
		{
			return true;
		}
		
		//$query = "delete from owned_item where owned_item_uid=".$book_inven_uid." and character_uid=".$char_uid;
	}

	/* //Query Result
	$result = @mysqli_query($dbhandle,$query);
	if($result)
	{
		return true;
	} */
	
	return false;
}

function UpdateGold($dbhandle, $gold_update, $char_uid)
{
	if($gold_update <0) $gold_update = 0;
	
	
	
	$stmt = $dbhandle->prepare("update character_list set gold=? where character_uid=?");
	$stmt->bind_param("ii", $gold_update, $char_uid);
	$result = $stmt->execute();
	$stmt->close();
		
		
	/* $update_query = "update character_list set gold=".$gold_update." where character_uid='".$char_uid."'";	
	$result = @mysqli_query($dbhandle,$update_query);
	 */
	
	if($result)
	{
		return true;
	}
	
	return false;
}


function getFromUrl($url, $method = 'GET')
{   
    // Initialize
    $info   = parse_url($url);
    $req    = '';
    $data   = '';
    $line   = '';
    $agent  = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)';
    $linebreak  = "\r\n";
    $headPassed = false;
 
    // Setting Protocol
    switch($info['scheme'] = strtoupper($info['scheme']))
    {
        case 'HTTP':
            $info['port']   = 80;
            break;
 
        case 'HTTPS':
            $info['ssl']    = 'ssl://';
            $info['port']   = 443;
            break;
 
        default:
            return false;
    }
 
    // Setting Path
    if(!$info['path'])
    {
        $info['path'] = '/';
    }
 
    // Setting Request Header
    switch($method = strtoupper($method))
    {
        case 'GET':
            if($info['query'])
            {
                $info['path'] .= '?' . $info['query'];
            }
 
            $req .= 'GET ' . $info['path'] . ' HTTP/1.1' . $linebreak;
            $req .= 'Host: ' . $info['host'] . $linebreak;
            $req .= 'User-Agent: ' . $agent . $linebreak;
            $req .= 'Referer: ' . $url . $linebreak;
            $req .= 'Connection: Close' . $linebreak . $linebreak;
            break;
 
        case 'POST':
            $req .= 'POST ' . $info['path'] . ' HTTP/1.1' . $linebreak;
            $req .= 'Host: ' . $info['host'] . $linebreak;
            $req .= 'User-Agent: ' . $agent . $linebreak; 
            $req .= 'Referer: ' . $url . $linebreak;
            $req .= 'Content-Type: application/x-www-form-urlencoded'.$linebreak; 
            $req .= 'Content-Length: '. strlen($info['query']) . $linebreak;
            $req .= 'Connection: Close' . $linebreak . $linebreak;
            $req .= $info['query']; 
            break;
    }
 
    // Socket Open
    $fsock  = @fsockopen($info['ssl'] . $info['host'], $info['port']);
    if ($fsock)
    {
        fwrite($fsock, $req);
        while(!feof($fsock))
        {
            $line = fgets($fsock, 128);
            if($line == "\r\n" && !$headPassed)
            {
                $headPassed = true;
                continue;
            }
            if($headPassed)
            {
                $data .= $line;
            }
        }
        fclose($fsock);
    }
 
    return $data;
}

function CheckTicket($platform, $account_id, $ticket)
{
	if ($platform === "steam")
	{
		if (CheckSteamTicket($ticket))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if ($platform === "oculus")
	{
		if (CheckOculusTicket($ticket, $account_id))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if ($platform === "quest")
	{
		//quest는 아직 인증을 할 수 없으므로 true를 반환한다.
		return true;
	}
	
	return false;
}


function CheckSteamTicket($ticket)
{
	$appid = "696960";
	$key = "97E44C8D71A80DAD981DCB66DC684403";
	
	$url = "https://api.steampowered.com/ISteamUserAuth/AuthenticateUserTicket/v1/?key=".$key."&appid=".$appid."&ticket=".$ticket ;
	
	// {"response":{"params":{"result":"OK","steamid":"123456","ownersteamid":"123456","vacbanned":false,"publisherbanned":false}}}
	$json = json_decode(getFromUrl($url), true);
	$result = $json['response']['params']['result'];
	
	if ($result === "OK")
	{
		return true;
	}
	else
	{
		return false;
	}
}

function CheckOculusTicket($ticket, $id)
{
	$url = 'https://graph.oculus.com/user_nonce_validate'; //주소셋팅
	$postfields["access_token"] = "OC|2909051379138471|40fd4b4995279ad89236666d6f6c9c77";
	$postfields["user_id"] = $id; 
	$postfields["nonce"] = $ticket;

	$ch = curl_init(); //curl 로딩

	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
	curl_setopt($ch, CURLOPT_HEADER, 0); 
	curl_setopt($ch, CURLOPT_POST, true);

	$curl_result = curl_exec ($ch); // curl 실행 및 결과값 저장
	curl_close ($ch); // curl 종료
	
	$json_result = json_decode($curl_result); //{"is_valid":true} or {"is_valid":false}
	$is_valid = $json_result->is_valid;
	
	if ($is_valid)
	{
		return true;
	}
	else
	{
		return false;
	}
}
	



?>