<?php
	function file_get_contents_curl($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
		curl_setopt($ch, CURLOPT_URL, $url);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}

	function GetLang(){
		$lang = strtolower(DEFAULT_LANG); // default language.

		if (!empty($_SESSION["user_id"])){
			$file = $_SESSION["user_lang"];
			if (file_exists("config/languages/lang.".$file.".php")){
				return $file;
			}
			elseif (file_exists("../config/languages/lang.".$file.".php")){
				return $file;
			}
			elseif (file_exists("../../config/languages/lang.".$file.".php")){
				return $file;
			}
			else{
				return strtolower($lang);
			}
		}
		else{
			if (file_get_contents_curl("http://ip-api.com/json/")){
				$url = json_decode(file_get_contents_curl("http://ip-api.com/json/"));
				if ($url){
					$lang2 = $url->{"countryCode"};
					if (file_exists("config/languages/lang.".strtolower($lang2).".php")){
						return strtolower($lang2);
					}
				}
				return strtolower($lang);
			}
			else{
				return strtolower($lang);
			}
		}
	}

	function getBrowser(){
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if(strpos($user_agent, 'MSIE') !== FALSE)
			return 'Internet explorer';
		elseif(strpos($user_agent, 'Edge') !== FALSE)
			return 'Microsoft Edge';
		elseif(strpos($user_agent, 'Trident') !== FALSE)
			return 'Internet explorer';
		elseif(strpos($user_agent, 'Opera Mini') !== FALSE)
			return "Opera Mini";
		elseif(strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR') !== FALSE)
			return "Opera";
		elseif(strpos($user_agent, 'Firefox') !== FALSE)
			return 'Mozilla Firefox';
		elseif(strpos($user_agent, 'Chrome') !== FALSE)
			return 'Google Chrome';
		elseif(strpos($user_agent, 'Safari') !== FALSE)
			return "Safari";
		else
			return 'No hemos podido detectar su navegador';
	}

	function GetConexion(){
		return new mysqli(HOST_IP, DB_USER, DB_PASSWORD);
	}

	function GetWbbConexion(){
		return new mysqli(HOST_WBB, WBB_USER, WBB_PASSWORD);
	}

	function CheckConexion(){
		$mysqli = new mysqli(HOST_IP, DB_USER, DB_PASSWORD);
		if ($mysqli->connect_errno){
			return false;
		}
		else{
			return true;
		}
	}

	function GetRankPos($id){
		$query = "SELECT player.id,player.playtime,player.job,player.skill_group,player.name,player.level,player.gold,player.exp,player_index.empire,guild.name AS guild_name,guild.id as guild_id 
				FROM ".DB_PLAYER.".player 
				LEFT JOIN ".DB_PLAYER.".player_index 
				ON player_index.id=player.account_id 
				LEFT JOIN ".DB_PLAYER.".guild_member 
				ON guild_member.pid=player.id 
				LEFT JOIN ".DB_PLAYER.".guild 
				ON guild.id=guild_member.guild_id
				INNER JOIN ".DB_ACCOUNT.".account 
				ON account.id=player.account_id
				WHERE player.name NOT LIKE '[%]%' AND account.status !='BLOCK'
				ORDER BY player.level DESC, player.exp DESC, player.playtime ASC ;";
		$conex = mysqli_query(GetConexion(),$query);
		$pos = 1;
		while($obj = mysqli_fetch_object($conex)){
			if ($obj->id == $id)
				break;
			$pos++;
		}
		return $pos;
	}

	function GetInfoFromAccount($id,$table){
		return mysqli_fetch_object(mysqli_query(GetConexion(), "select ".$table." from ".DB_ACCOUNT.".account where id = ".$id." limit 1;"))->$table;
	}

	function GetInfoByRace($id, $id2){
		return mysqli_fetch_object(mysqli_query(GetConexion(), "select COUNT(*) as count from ".DB_PLAYER.".player where job = ".$id." or job = ".$id2." limit 1;"))->count;
	}

	function GetItemCount(){
		return mysqli_fetch_object(mysqli_query(GetConexion(), "select COUNT(*) as count from ".DB_PLAYER.".item limit 1;"))->count;
	}
	function GetYangCount(){
		return mysqli_fetch_object(mysqli_query(GetConexion(), "select SUM(gold) as count from ".DB_PLAYER.".player limit 1;"))->count;
	}
	function GetInfoFromGuild($id,$table){
		$guild_id = mysqli_fetch_object(mysqli_query(GetConexion(), "select guild_id from ".DB_PLAYER.".guild_member where pid = ".$id." limit 1;"));
		if (empty($guild_id->guild_id))
			return "None";

		return mysqli_fetch_object(mysqli_query(GetConexion(), "select ".$table." from ".DB_PLAYER.".guild where id = ".$guild_id->guild_id." limit 1;"))->$table;
	}

	function GetInfoFromPlayer($id,$table){
		return mysqli_fetch_object(mysqli_query(GetConexion(), "select ".$table." from ".DB_PLAYER.".player where id = ".$id." limit 1;"))->$table;
	}

	function GetSafeboxPassword($id){
		$pwd = mysqli_fetch_object(mysqli_query(GetConexion(), "select password from ".DB_PLAYER.".safebox where account_id = ".$id." limit 1;"))->password;
		return $pwd ? $pwd : "00000";
	}

	function GetTotalAccounts(){
		return mysqli_fetch_assoc(mysqli_query(GetConexion(), "SELECT COUNT(*) as count FROM ".DB_ACCOUNT.".account;"))["count"];
	}

	function GetTotalPlayers(){
		return mysqli_fetch_assoc(mysqli_query(GetConexion(), "SELECT COUNT(*) as count FROM ".DB_PLAYER.".player;"))["count"];
	}
	
	function GetPlayersOnline($type=0){
		if ($type == 0)
			$query = mysqli_fetch_assoc(mysqli_query(GetConexion(), "SELECT COUNT(*) as count FROM ".DB_PLAYER.".player WHERE DATE_SUB(NOW(), INTERVAL 10 minute) < last_play;"))["count"];
		else
			$query = mysqli_fetch_assoc(mysqli_query(GetConexion(), "SELECT COUNT(*) as count FROM ".DB_PLAYER.".player WHERE DATE_SUB(NOW(), INTERVAL 1 day) < last_play;"))["count"];
		return $query;
	}

	function GetChannelStatus($port=1){
		$online = @fsockopen(HOST_IP, $port, $errno, $errstr, 1);
		if ($online)
			return "online";
		return "offline";
	}

	function GetTop5(){
		$query = "SELECT player.id,player.playtime,player.job,player.skill_group,player.name,player.level,player.gold,player.exp,player_index.empire,guild.name AS guild_name,guild.id as guild_id 
			FROM ".DB_PLAYER.".player 
			LEFT JOIN ".DB_PLAYER.".player_index 
			ON player_index.id=player.account_id 
			LEFT JOIN ".DB_PLAYER.".guild_member 
			ON guild_member.pid=player.id 
			LEFT JOIN ".DB_PLAYER.".guild 
			ON guild.id=guild_member.guild_id
			INNER JOIN ".DB_ACCOUNT.".account 
			ON account.id=player.account_id
			WHERE player.name NOT LIKE '[%]%' AND account.status !='BLOCK'
			ORDER BY player.level DESC, player.exp DESC, player.playtime ASC 
			LIMIT 5;";
		$conex = mysqli_query(GetConexion(),$query);
		$text = "";
		while($obj = mysqli_fetch_object($conex)){
			$text = $text.$obj->job."|".$obj->name."|".$obj->guild_name."|".$obj->level."#";
		}
		return $text;
	}

	function GetRaceImgById($job){
		if($job == 0){
			return "warrior_m.png";
		}elseif($job == 1){
			return "assassin_w.png";
		}elseif($job == 2){
			return "sura_m.png";
		}elseif($job == 3){
			return "shaman_w.png";
		}elseif($job == 4){
			return "warrior_w.png";
		}elseif($job == 5){
			return "assassin_m.png";
		}elseif($job == 6){
			return "sura_w.png";
		}elseif($job == 7){
			return "shaman_m.png";
		}elseif($job == 8){
			return "wolfman_m.png";
		}
	}

	function GetCategoryName($id){
		return mysqli_fetch_object(mysqli_query(GetConexion(), "select name from ".DB_WEB.".support_categories where id = ".$id." limit 1;"))->name;
	}

	function GetSupportCategories(){
		$return = "";
		$a = mysqli_query(GetConexion(),"select id,name from ".DB_WEB.".support_categories;");
		while ($idx = mysqli_fetch_assoc($a)){
			$return .= "<option value='".$idx["id"]."'>".$idx["name"]."</option>";
		}
		return $return;
	}

	function time_elapsed_string($datetime, $full = false){
		if ($datetime == NULL){
			return "";
		}
		$now = new DateTime;
		$ago = new DateTime($datetime);
		$diff = $now->diff($ago);

		$diff->w = floor($diff->d / 7);
		$diff->d -= $diff->w * 7;

		$string = array(
			'y' => 'year',
			'm' => 'month',
			'w' => 'week',
			'd' => 'day',
			'h' => 'hour',
			'i' => 'minute',
			's' => 'sencond',
		);
		foreach ($string as $k => &$v) {
			if ($diff->$k) {
				$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
			} else {
				unset($string[$k]);
			}
		}

		if (!$full) $string = array_slice($string, 0, 1);
		return $string ? implode(', ', $string) . ' ago' : 'just now';
	}

	function RandomString($idx=0)
	{
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		if ($idx > 0){
			$charactersLength = $idx;
		}
		for ($i = 0; $i < $charactersLength; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}

	function IsAdmin($name){
		if (mysqli_fetch_assoc(mysqli_query(GetConexion(), "select COUNT(*) as count from ".DB_ACCOUNT.".account where real_name = '".$name."' and web_admin > 0 limit 1;"))["count"] > 0)
			return true;
		return false;
	}
	
	function GetDataFromCache($file,$arg){
		$GetDataFromCache = parse_ini_file('config/cache/cache.ini',true);
		if(isset($GetDataFromCache[$file][$arg])){
			return $GetDataFromCache[$file][$arg];
		}
		else{
			// how to update cache?
			// delete file cache.ini, reload stuff and save it.
			return ""; // here update cron
		}
	}

	function write_php_ini($array, $file)
	{
		$res = array();
		foreach($array as $key => $val)
		{
			if(is_array($val))
			{
				$res[] = "[$key]";
				foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
			}
			else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
		}
		safefilerewrite($file, implode("\r\n", $res));
	}

	function safefilerewrite($fileName, $dataToSave)
	{    if ($fp = fopen($fileName, 'w'))
		{
			$startTime = microtime(TRUE);
			do
			{            $canWrite = flock($fp, LOCK_EX);
			   // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
			   if(!$canWrite) usleep(round(rand(0, 100)*1000));
			} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
	
			//file was locked so now we can store information
			if ($canWrite)
			{            fwrite($fp, $dataToSave);
				flock($fp, LOCK_UN);
			}
			fclose($fp);
		}
	
	}

	function Pagination($item_count, $limit, $cur_page, $link){
		$page_count = ceil($item_count/$limit);
		$current_range = array(($cur_page-2 < 1 ? 1 : $cur_page-2), ($cur_page+2 > $page_count ? $page_count : $cur_page+2));

		// First and Last pages
		$first_page = $cur_page > 3 ? '<li><a href="'.sprintf($link, '1').'">1</a></li>'.($cur_page < 5 ? ' ' : '') : null;
		$last_page = $cur_page < $page_count-2 ? ($cur_page > $page_count-4 ? ' ' : '').'<li><a href="'.sprintf($link, $page_count).'">'.$page_count.'</a></li>' : null;

		// Previous and next page
		$previous_page = $cur_page > 1 ? '<li><a href="'.sprintf($link, ($cur_page-1)).'">&laquo;</a></li>' : null;
		$next_page = $cur_page < $page_count ? '<li><a href="'.sprintf($link, ($cur_page+1)).'">&raquo;</a></li>' : null;

		// Display pages that are in range
		for ($x=$current_range[0];$x <= $current_range[1]; ++$x)
			$pages[] = '<li '.($x == $cur_page ? 'class="active"' : $x).'><a href="'.sprintf($link, $x).'">'.$x.'</a></li>';

		if ($page_count > 1)
			return '<div class="pagination">'.$previous_page.$first_page.implode(' ', $pages).$last_page.$next_page.'</div>';
	}

	function GetTicketStatus($idx){
		$status = [
			1 => "Open",
			2 => "Closed",
		];
		return $status[$idx];
	}

	$raza = [
		'0' => "Warrior (m)",
		'1' => "Ninja (f)",
		'2' => "Sura (m)",
		'3' => "Sham&aacute;n (f)",
		'4' => "Warrior (f)",
		'5' => "Ninja (m)",
		'6' => "Sura (f)",
		'7' => "Sham&aacute;n (m)",
		'8' => "Lycan (m)",
		'9' => "Keyto (f)"
	];

	$empire = [
		"1" => "Chunjo",
		"2" => "Shinsoo",
		"3" => "Jinno",
	];
?>