<?php
	function error($id, $syserr, $WebsiteDB = null) {
		if($id >= 1 && $id <= 2) { // Erori fatale
			$errors = array(
				1 => "A intervenit o eroare la conectarea la una dintre bazele de date!",
				2 => "Nu exista informatii pentru conectarea la una dintre bazele de date!",
			);
			
			$error_id = md5(time() . $id . $syserr);
			$fh = fopen("errorlog.txt", 'a') or $error_id = "";
			fwrite($fh, "[" . $error_id . "] - {" . date("j M Y G:i:s T", time()) . "} - {" . $_SERVER['REMOTE_ADDR'] . "} - {Type: $id} ~ System details: '$syserr'.\n");
			fclose($fh);
			
			if(isset($errors[$id])) {
				$message = $errors[$id];
			} else {
				$message = "A intervenit o eroare necunoscuta. ID: $id.";
			}
			message($message, $error_id);
		} else { // Erori in baza de date
			if($syserr == "PAGE_NOT_FOUND") {
				message("", "PAGE_NOT_FOUND");
			}
			$syserr = mysqli_real_escape_string($WebsiteDB, $syserr);
			$DBInsert = mysqli_query($WebsiteDB, "INSERT INTO `error_log` (`ip`, `error_type`, `error`) VALUES ('" . $_SERVER['REMOTE_ADDR'] . "', $id, '$syserr');");
			if(!$DBInsert) {
				$fh = fopen("errorlog.txt", 'a');
				fwrite($fh, "[" . md5(time() . $id . $syserr) . "] - {" . date("j M Y G:i:s T", time()) . "} - {" . $_SERVER['REMOTE_ADDR'] . "} - {Type: $id} (Failed to insert to DB: '" . mysqli_error($WebsiteDB) . "') ~ System details: '$syserr'.\n");
				fclose($fh);
			}
		}
	}
	
	function message($message, $error_id = "") {
		include("message.php");
		if($error_id != "PAGE_NOT_FOUND") {
			die();
		}
	}
	
	function highscore($DB, $Start, $Rows, $RankingCache, $SQLAppend = "") {
		if($RankingCache) {
			$DBSelect = mysqli_query($DB["website"], "SELECT `name`, `empire`, `level`, `exp`, `date` FROM `highscore_cache`$SQLAppend ORDER BY `level` DESC, `exp` DESC LIMIT $Start, $Rows;");
		} else {
			$DBSelect = mysqli_query($DB["player"], "SELECT `player`.`name`, `player_index`.`empire`, `player`.`level`, `player`.`exp` FROM `player` LEFT JOIN `player_index` ON `player`.`account_id` = `player_index`.`id` WHERE `player`.`name` NOT LIKE '[%]%' ORDER BY `level` DESC, `exp` DESC LIMIT $Start, $Rows;");
		}
		if(!$DBSelect) {
			if($RankingCache) {
				error(9, mysqli_error($DB["website"]), $DB["website"]);
			} else {
				error(9, mysqli_error($DB["player"]), $DB["website"]);
			}
			return false;
		} else {
			$Result = array();
			$Position = $Start + 1;
			while($Row = mysqli_fetch_array($DBSelect)) {
				$Result[$Position] = $Row;
				$Position++;
			}
			return $Result;
		}
	}
	
	function guild_highscore($DB, $Start, $Rows, $RankingCache, $SQLAppend = "") {
		if($RankingCache) {
			$DBSelect = mysqli_query($DB["website"], "SELECT `name`, `master`, `empire`, `level`, `ladder_point`, `date` FROM `guild_highscore_cache`$SQLAppend ORDER BY `level` DESC, `ladder_point` DESC LIMIT $Start, $Rows;");
		} else {
			$DBSelect = mysqli_query($DB["player"], "SELECT `guild`.`name`, `player`.`name` AS `master`, `player_index`.`empire`, `guild`.`level`, `guild`.`ladder_point` FROM `guild` LEFT JOIN `player` ON `guild`.`master` = `player`.`id` LEFT JOIN `player_index` ON `player`.`account_id` = `player_index`.`id` ORDER BY `guild`.`level` DESC, `guild`.`ladder_point` DESC LIMIT $Start, $Rows;");
		}
		
		if(!$DBSelect) {
			if($RankingCache) {
				error(10, mysqli_error($DB["website"]), $DB["website"]);
			} else {
				error(10, mysqli_error($DB["player"]), $DB["website"]);
			}
			return false;
		} else {
			$Result = array();
			$Position = $Start + 1;
			while($Row = mysqli_fetch_array($DBSelect)) {
				$Result[$Position] = $Row;
				$Position++;
			}
			return $Result;
		}
	}
	
	function RandomString($Length) {
		$Characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		
		$String = "";
		for($i = 0; $i < $Length; $i++) {
			$String .= $Characters[rand(0, strlen($Characters) -1)];
		}
		
		return $String;
	}
	
	function AccountExists($Username, $DB) {
		$AccountSQL = mysqli_query($DB["account"], "SELECT * FROM `account` WHERE `login` = '$Username';");
		if(!$AccountSQL) {
			error(12, mysqli_error($DB["account"]), $DB["website"]);
			return false;
		}
		$WebsiteSQL = mysqli_query($DB["website"], "SELECT * FROM `temp_account` WHERE `login` = '$Username';");
		if(!$WebsiteSQL) {
			error(13, mysqli_error($DB["website"]), $DB["website"]);
			return false;
		}
		
		if(mysqli_num_rows($AccountSQL) == 0 && mysqli_num_rows($WebsiteSQL) == 0) {
			return false;
		} else {
			return true;
		}
	}
	
	function EmailInUse($Email, $DB) {
		$AccountSQL = mysqli_query($DB["account"], "SELECT * FROM `account` WHERE `email` = '$Email';");
		if(!$AccountSQL) {
			error(35, mysqli_error($DB["account"]), $DB["website"]);
			return false;
		}
		$WebsiteSQL = mysqli_query($DB["website"], "SELECT * FROM `temp_account` WHERE `email` = '$Email';");
		if(!$WebsiteSQL) {
			error(36, mysqli_error($DB["website"]), $DB["website"]);
			return false;
		}
		
		if(mysqli_num_rows($AccountSQL) == 0 && mysqli_num_rows($WebsiteSQL) == 0) {
			return false;
		} else {
			return true;
		}
	}
	
	function email_send($To, $Subject, $Content) {
		require_once 'phpmailer/PHPMailerAutoload.php';
		global $website;
		
		$mail = new PHPMailer();
		//$mail->isSMTP();
		//$mail->SMTPDebug = 1;
		//$mail->Host = $website["SMTPHost"];
		//$mail->Port = $website["SMTPPort"];
		//$mail->SMTPSecure = 'tls';
		//$mail->SMTPAuth = $website["SMTPAuth"];
		/*if($website["SMTPAuth"] == true) {
			$mail->Username = $website["SMTPUsername"];
			$mail->Password = $website["SMTPPassword"];
		}*/
		$mail->setFrom($website["system_email"], $website["server_name"]);
		$mail->addAddress($To);
		$mail->Subject = $Subject;
		$mail->msgHTML($Content);
		
		if (!$mail->send()) {
			return false;
		} else {
			return true;
		}
	}
	
	function emailCheck($email) {
		if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
			return false;
		}
		$email_array = explode("@", $email);
		$local_array = explode(".", $email_array[0]);
		for ($i = 0; $i < sizeof($local_array); $i++) {
			if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
				return false;
			}
		}
		if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) {
			$domain_array = explode(".", $email_array[1]);
			if (sizeof($domain_array) < 2) {
				return false;
			}
			for ($i = 0; $i < sizeof($domain_array); $i++) {
				if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
					return false;
				}
			}
		}
		return true;
	}
	
	function register($Username, $Password, $Email, $DB, $EmailConfirm = false) {
		$EmailConfirm = false; // fara verificare, comenteaza ca sa fie cu verificare
		if(emailCheck($Email) == false) {
			error(14, "Invalid email address: '$Email', aborting registration!", $DB["website"]);
			return 0;
		} elseif(strlen($Username) < 5){
			error(15, "Username '$Username' too short, aborting registration!", $DB["website"]);
			return 1;
		} elseif(strlen($Username) > 16){
			error(16, "Username '$Username' too long, aborting registration!", $DB["website"]);
			return 2;
		} elseif(strlen($Password) < 5){
			error(17, "Password '$Password' too short, aborting registration!", $DB["website"]);
			return 3;
		} elseif(strlen($Password) > 16){
			error(18, "Password '$Password' too long, aborting registration!", $DB["website"]);
			return 4;
		} elseif(AccountExists($Username, $DB) == true) {
			return 5;
		} elseif(EmailInUse($Email, $DB) == true) {
			return 6;
		} else {
			$DeleteCode = RandomString(7);
			if($EmailConfirm == false) {
				$RegisterSQL = mysqli_query($DB["account"], "INSERT INTO `account` (`login`, `password`, `email`, `social_id`, `create_time`) VALUES ('$Username', PASSWORD('$Password'), '$Email', '$DeleteCode', NOW());");
				if(!$RegisterSQL) {
					error(19, mysqli_error($DB["account"]), $DB["website"]);
					return 7;
				} else {
					return 9;
					// Log
				}
			} else {
				$CheckID = md5(time() . $Username . $Email);
				$RegisterSQL = mysqli_query($DB["website"], "INSERT INTO `temp_account` (`login`, `password`, `email`, `social_id`, `create_time`, `check_id`) VALUES ('$Username', PASSWORD('$Password'), '$Email', '$DeleteCode', NOW(), '$CheckID');");
				if(!$RegisterSQL) {
					error(20, mysqli_error($DB["website"]), $DB["website"]);
					return 7;
				} else {
					global $website;
					
					$Subject = $website["server_name"] . " - Inregistrare";
					$Content = '
						<html>
							<body>
								<div style="color:#000;background-color:#fff;font-family:HelveticaNeue, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif;font-size:14pt;">
									<blockquote style="border:none;padding:0px;">
										<div><span style="font-family:verdana, helvetica, sans-serif;">Salutare!</span></div>
									</blockquote>
									<div><span style="font-size:13px;font-family:verdana, helvetica, sans-serif;">Bine ai venit pe <span style="font-weight:bold;">' . $website["server_name"] . '</span>! Ai primit acest email ca urmare a solicitarii tale de inregisrare.</span></div>
									<div><br></div>
									<div><span style="font-size:13px;">Datele contului tau sunt:</span></div>
									<div>
										<ul>
											<li><span style="font-size:13px;"><span style="font-style:italic;">Nume de utilizator:</span> <span><span style="font-weight:bold;">' . $Username . '</span>;</span><br></span></li>
											<li><span style="font-size:13px;"><span style="font-style:italic;">Parola:</span> <span><span style=" font-weight:bold;">' . $Password . '</span>;</span><br></span></li>
											<li><span style="font-size:13px;"><span style="font-style:italic;">Cod de stergere caracter:</span> <span><span style="font-weight:bold;">' . $DeleteCode . '</span>;</span></span><br></li>
										</ul>
									</div>
									<div>
										<span style="color:rgb(205, 35, 44);font-family:garamond, \'new york\', times, serif;">Pentru a iti activa contul, <a href="' . $website["url"] . '?p=register&confirm=' . $CheckID . '" rel="nofollow" target="_blank">acceseaza acest link</a>.</span>
									</div>
									<div>
										<span style="font-size:13px;"> Daca intampini erori in accesarea link-ului, copiaza urmatoarea adresa in bara URL a browser-ului tau: <a href="' . $website["url"] . '?p=register&confirm=' . $CheckID . '">' . $website["url"] . '?p=register&confirm=' . $CheckID . '</a> .</span>
									</div>
									<div><br></div>
									<div>
										<span style="font-size:10px;">Daca nu tu ai solicitat acest e-mail, poti ignora continutul.&nbsp;</span><span style="font-size:10px;">Acest e-mail a fost trimis automat, in scopul confirmarii inregistrarii.</span>
									</div>
									<div style="color:rgb(0, 0, 0);font-size:10px;font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;font-style:normal;"><span style="font-size:10px;"><br></span></div>
									<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
										<span style="font-size:13px;font-style:italic;">Cu stima,</span>
									</div>
									<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
										<span style="font-size:small;font-style:italic;">Echipa ' . $website["server_name"] . '.</span>
									</div>
								</div>
							</body>
						</html>';
					
					$SendMail = email_send($Email, $Subject, $Content);
					if(!$SendMail) {
						error(21, "Error sending registration e-mail!", $DB["website"]);
						return 8;
					} else {
						return 9;
					}
				}
			}
		}
	}
	
	function CharInfo($AccountID, $DB) {
		$SelectSQL = mysqli_query($DB["player"], "SELECT `name`, `job`, `level`, `exp`, `playtime` FROM `player` WHERE `account_id` = $AccountID ORDER BY `level` DESC, `exp` DESC;");
		if(!$SelectSQL) {
			error(22, mysqli_error($DB["player"]), $DB["website"]);
			return false;
		} else {
			if(mysqli_num_rows($SelectSQL) == 0) {
				return false;
			} else {
				$Result = array();
				$id = 0;
				while($row = mysqli_fetch_array($SelectSQL)) {
					$Result[$id] = $row;
					$id++;
				}
				return $Result;
			}
		}
	}
	
	function MinutesToTime($minutes) {
		$d = floor ($minutes / 1440);
		$h = floor (($minutes - $d * 1440) / 60);
		$m = $minutes - ($d * 1440) - ($h * 60);
		return $d . "d, " . $h . "h, " . $m . "m";
	}
	
	function GetRaceName($Race) {
		$Races = array(
			0 => "Razboinic (M)",
			1 => "Ninja (F)",
			2 => "Sura (M)",
			3 => "Saman (F)",
			4 => "Razboinic (F)",
			5 => "Ninja (M)",
			6 => "Sura (F)",
			7 => "Saman (M)",
		);
		if(isset($Races[$Race])) {
			return $Races[$Race];
		} else {
			return "N/A";
		}
	}
	
	function GetAccountEmpire($AccountID, $DB) {
		$SelectSQL = mysqli_query($DB["player"], "SELECT `empire` FROM `player_index` WHERE `id` = $AccountID;");
		if(!$SelectSQL) {
			error(23, mysqli_error($DB["player"]), $DB["website"]);
			return "Eroare!";
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return "Eroare!";
		} else {
			$Empire = mysqli_fetch_array($SelectSQL);
			$Empire = $Empire["empire"];
			$Empires = array(
				1 => "Regatul Shinsoo",
				2 => "Regatul Chunjo",
				3 => "Regatul Jinno",
			);
			if(isset($Empires[$Empire])) {
				return $Empires[$Empire];
			} else {
				return "N/A";
			}
		}
	}
	
	function GetPlayerRank($PlayerName, $DB) {
		$SelectSQL = mysqli_query($DB["website"], "SELECT `id` FROM `highscore_cache` WHERE `name` = '$PlayerName';");
		if(!$SelectSQL) {
			error(24, mysqli_error($DB["website"]), $DB["website"]);
			return "N/A";
		} else {
			if(mysqli_num_rows($SelectSQL) == 0) {
				return "N/A";
			} else {
				$Rank = mysqli_fetch_array($SelectSQL);
				return $Rank["id"];
			}
		}
	}
	
	function ChangeEmail($AccountID, $Email, $DB) {
		$InsertSQL = mysqli_query($DB["account"], "UPDATE `account` SET `email` = '$Email' WHERE `id` = $AccountID;");
		if(!$InsertSQL) {
			error(25, mysqli_error($DB["account"]), $DB["website"]);
			return 0;
		} else {
			$DeleteSQL = mysqli_query($DB["website"], "DELETE FROM `email_change_list` WHERE `account_id` = $AccountID;");
			if(!$DeleteSQL) {
				error(26, mysqli_error($DB["website"]), $DB["website"]);
				return 1;
			} else {
				return 2;
			}
		}
	}
	
	function ChangePassword($AccountID, $Password, $DB) {
		$SelectSQL = mysqli_query($DB["account"], "SELECT * FROM `account` WHERE `id` = $AccountID;");
		if(!$SelectSQL) {
			error(33, mysqli_error($DB["account"]), $DB["website"]);
			return -2;
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return -1;
		} else {
			$InsertSQL = mysqli_query($DB["account"], "UPDATE `account` SET `password` = PASSWORD('$Password') WHERE `id` = $AccountID;");
			if(!$InsertSQL) {
				error(34, mysqli_error($DB["account"]), $DB["website"]);
				return 2;
			} else {
				$DeleteSQL = mysqli_query($DB["website"], "DELETE FROM `password_change_list` WHERE `account_id` = $AccountID;");
				if(!$DeleteSQL) {
					error(44, mysqli_error($DB["website"]), $DB["website"]);
					return 4;
				} else {
					return 3;
				}
			}
			}
	}
	
	function GetSafeboxPassword($AccountID, $DB) {
		$SelectSQL = mysqli_query($DB["player"], "SELECT `password` FROM `safebox` WHERE `account_id` = '".$AccountID."';");
		if(!$SelectSQL) {
			error(29, mysqli_error($DB["player"]), $DB["website"]);
			return -2;
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return -1;
		} else {
			$PasswordArray = mysqli_fetch_array($SelectSQL);
			$Password = $PasswordArray["password"];
			if(empty($Password) || strlen($Password)<2) {
				return "000000";
				mysqli_query($DB["player"], "UPDATE `safebox` SET `password`='000000' WHERE `account_id` = '".$AccountID."';");
			} else {
				return $Password;
			}
		}
	}
	
	function GetDeleteCode($AccountID, $DB) {
		$SelectSQL = mysqli_query($DB["account"], "SELECT `social_id` FROM `account` WHERE `id` = $AccountID;");
		if(!$SelectSQL) {
			error(30, mysqli_error($DB["account"]), $DB["website"]);
			return -2;
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return -1;
		} else {
			$DeleteCode = mysqli_fetch_array($SelectSQL);
			return $DeleteCode["social_id"];
		}
	}
	
	function ResendRegisterEmail($Email, $DB) {
		$SelectSQL = mysqli_query($DB["website"], "SELECT * FROM `temp_account` WHERE `email` = '$Email';");
		if(!$SelectSQL) {
			error(31, mysqli_error($DB["website"]), $DB["website"]);
			return 0;
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return 1;
		} else {
			global $website;
			while($CurrentAccount = mysqli_fetch_array($SelectSQL)) {
				$Subject = $website["server_name"] . " - Inregistrare";
				$Content = '
					<html>
						<body>
							<div style="color:#000;background-color:#fff;font-family:HelveticaNeue, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif;font-size:14pt;">
								<blockquote style="border:none;padding:0px;">
									<div><span style="font-family:verdana, helvetica, sans-serif;">Salutare!</span></div>
								</blockquote>
								<div><span style="font-size:13px;font-family:verdana, helvetica, sans-serif;">Bine ai venit pe <span style="font-weight:bold;">' . $website["server_name"] . '</span>! Ai primit acest email ca urmare a solicitarii tale de inregisrare.</span></div>
								<div><br></div>
								<div><span style="font-size:13px;">Datele contului tau sunt:</span></div>
								<div>
									<ul>
										<li><span style="font-size:13px;"><span style="font-style:italic;">Nume de utilizator:</span> <span><span style="font-weight:bold;">' . $CurrentAccount["login"] . '</span>;</span><br></span></li>
										<li><span style="font-size:13px;"><span style="font-style:italic;">Parola:</span> <span><span style=" font-weight:bold;">(Criptata)</span>;</span><br></span></li>
										<li><span style="font-size:13px;"><span style="font-style:italic;">Cod de stergere caracter:</span> <span><span style="font-weight:bold;">' . $CurrentAccount["social_id"] . '</span>;</span></span><br></li>
									</ul>
								</div>
								<div>
									<span style="color:rgb(205, 35, 44);font-family:garamond, \'new york\', times, serif;">Pentru a iti activa contul, <a href="' . $website["url"] . '?p=register&confirm=' . $CurrentAccount["check_id"] . '" rel="nofollow" target="_blank">acceseaza acest link</a>.</span>
								</div>
								<div>
									<span style="font-size:13px;"> Daca intampini erori in accesarea link-ului, copiaza urmatoarea adresa in bara URL a browser-ului tau: <a href="' . $website["url"] . '?p=register&confirm=' . $CurrentAccount["check_id"] . '">' . $website["url"] . '?p=register&confirm=' . $CurrentAccount["check_id"] . '</a> .</span>
								</div>
								<div><br></div>
								<div>
									<span style="font-size:10px;">Daca nu tu ai solicitat acest e-mail, poti ignora continutul.&nbsp;</span><span style="font-size:10px;">Acest e-mail a fost retrimis automat, la cererea utilizatorului.</span>
								</div>
								<div style="color:rgb(0, 0, 0);font-size:10px;font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;font-style:normal;"><span style="font-size:10px;"><br></span></div>
								<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
									<span style="font-size:13px;font-style:italic;">Cu stima,</span>
								</div>
								<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
									<span style="font-size:small;font-style:italic;">Echipa ' . $website["server_name"] . '.</span>
								</div>
							</div>
						</body>
					</html>';
				
				$SendMail = email_send($Email, $Subject, $Content);
				if(!$SendMail) {
					error(32, "Error resending registration e-mail!", $DB["website"]);
					return 2;
				}
			}
			
			return 3;
		}
	}
	
	function ActivateAccount($ConfirmCode, $DB) {
		$SelectSQL = mysqli_query($DB["website"], "SELECT * FROM `temp_account` WHERE `check_id` = '$ConfirmCode';");
		if(!$SelectSQL) {
			error(37, mysqli_error($DB["website"]), $DB["website"]);
			return 0;
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return 1;
		} else {
			while($CurrentAccount = mysqli_fetch_array($SelectSQL)) {
				$Username = $CurrentAccount["login"];
				$Password = $CurrentAccount["password"];
				$Email = $CurrentAccount["email"];
				$SocialID = $CurrentAccount["social_id"];
				$CreateTime = $CurrentAccount["create_time"];
				
				$InsertSQL = mysqli_query($DB["account"], "INSERT INTO `account` (`login`, `password`, `email`, `social_id`, `create_time`) VALUES ('$Username', '$Password', '$Email', '$SocialID', '$CreateTime');");
				if(!$InsertSQL) {
					error(38, mysqli_error($DB["website"]), $DB["website"]);
					return 2;
				}
			}
		}
		$DeleteSQL = mysqli_query($DB["website"], "DELETE FROM `temp_account` WHERE `check_id` = '$ConfirmCode';");
		if(!$DeleteSQL) {
			error(39, mysqli_error($DB["website"]), $DB["website"]);
			return 3;
		} else {
			return 4;
		}
	}
	
	function ChangePasswordEmail($Email, $DB, $Forgotten = false) {
		$SelectSQL = mysqli_query($DB["account"], "SELECT `id` FROM `account` WHERE `email` = '$Email';");
		if(!$SelectSQL) {
			error(40, mysqli_error($DB["account"]), $DB["website"]);
			return 0;
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return 1;
		} else {
			while($CurrentAccount = mysqli_fetch_array($SelectSQL)) {
				$CheckID = md5(time() . $CurrentAccount["id"] . $Email);
				$InsertSQL = mysqli_query($DB["website"], "INSERT INTO `password_change_list` (`account_id`, `check_id`) VALUES ('" . $CurrentAccount["id"] . "', '$CheckID');");
				if(!$InsertSQL) {
					error(41, mysqli_error($DB["website"]), $DB["website"]);
					return 2;
				} else {
					global $website;
					
					$Subject = $website["server_name"] . " - Schimbare parola";
					if($Forgotten == false) {
						$Content = '
							<html>
								<body>
									<div style="color:#000;background-color:#fff;font-family:HelveticaNeue, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif;font-size:14pt;">
										<blockquote style="border:none;padding:0px;">
											<div><span style="font-family:verdana, helvetica, sans-serif;">Salutare,</span></div>
										</blockquote>
										<div><span style="font-size:13px;font-family:verdana, helvetica, sans-serif;">De la echipa <span style="font-weight:bold;">' . $website["server_name"] . '</span>! Ai primit acest email fiindca a fost ceruta schimbarea parolei tale.</span></div>
										<div><br></div>
										<div>
											<span style="color:rgb(205, 35, 44);font-family:garamond, \'new york\', times, serif;">Pentru a schimba parola, <a href="' . $website["url"] . '?p=passwordchangerequest&id=' . $CurrentAccount["id"] . '&modify=' . $CheckID . '" rel="nofollow" target="_blank">acceseaza acest link</a>.</span>
										</div>
										<div><br></div>
										<div>
											<span style="font-size:13px;"> Daca intampini erori in accesarea link-ului, copiaza urmatoarea adresa in bara URL a browser-ului tau: <a href="' . $website["url"] . '?p=passwordchangerequest&id=' . $CurrentAccount["id"] . '&modify=' . $CheckID . '">' . $website["url"] . '?p=passwordchangerequest&id=' . $CurrentAccount["id"] . '&modify=' . $CheckID . '</a> .</span>
										</div>
										<div>
											<span style="font-size:10px;">Daca nu tu ai solicitat acest e-mail, poti ignora continutul.&nbsp;</span><span style="font-size:10px;">Acest e-mail a fost trimis automat, in scopul schimbarii parolei.</span>
										</div>
										<div style="color:rgb(0, 0, 0);font-size:10px;font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;font-style:normal;"><span style="font-size:10px;"><br></span></div>
										<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
											<span style="font-size:13px;font-style:italic;">Cu stima,</span>
										</div>
										<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
											<span style="font-size:small;font-style:italic;">Echipa ' . $website["server_name"] . '.</span>
										</div>
									</div>
								</body>
							</html>';
					} else {
						$Content = '
							<html>
								<body>
									<div style="color:#000;background-color:#fff;font-family:HelveticaNeue, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif;font-size:14pt;">
										<blockquote style="border:none;padding:0px;">
											<div><span style="font-family:verdana, helvetica, sans-serif;">Salutare,</span></div>
										</blockquote>
										<div><span style="font-size:13px;font-family:verdana, helvetica, sans-serif;">De la echipa <span style="font-weight:bold;">' . $website["server_name"] . '</span>! Ai primit acest email fiindca a fost sesizata situatia unei parole pierdute.</span></div>
										<div><br></div>
										<div>
											<span style="color:rgb(205, 35, 44);font-family:garamond, \'new york\', times, serif;">Pentru a schimba parola, <a href="' . $website["url"] . '?p=passwordlostrequest&id=' . $CurrentAccount["id"] . '&modify=' . $CheckID . '" rel="nofollow" target="_blank">acceseaza acest link</a>.</span>
										</div>
										<div>
											<span style="font-size:13px;"> Daca intampini erori in accesarea link-ului, copiaza urmatoarea adresa in bara URL a browser-ului tau: <a href="' . $website["url"] . '?p=passwordlostrequest&id=' . $CurrentAccount["id"] . '&modify=' . $CheckID . '">' . $website["url"] . '?p=passwordlostrequest&id=' . $CurrentAccount["id"] . '&modify=' . $CheckID . '</a> .</span>
										</div>
										<div><br></div>
										<div>
											<span style="font-size:10px;">Daca nu tu ai solicitat acest e-mail, poti ignora continutul.&nbsp;</span><span style="font-size:10px;">Acest e-mail a fost trimis automat, in scopul recuperarii parolei.</span>
										</div>
										<div style="color:rgb(0, 0, 0);font-size:10px;font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;font-style:normal;"><span style="font-size:10px;"><br></span></div>
										<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
											<span style="font-size:13px;font-style:italic;">Cu stima,</span>
										</div>
										<div style="text-align:right;color:rgb(0, 0, 0);font-family:HelveticaNeue, \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;background-color:transparent;">
											<span style="font-size:small;font-style:italic;">Echipa ' . $website["server_name"] . '.</span>
										</div>
									</div>
								</body>
							</html>';
					}
					
					$SendMail = email_send($Email, $Subject, $Content);
					if(!$SendMail) {
						error(42, "Error sending password change e-mail!", $DB["website"]);
						return 3;
					}
				}
			}
		}
		return 4;
	}
	
	function ChangePasswordValid($AccountID, $CheckID, $DB) {
		$SelectSQL = mysqli_query($DB["website"], "SELECT * FROM `password_change_list` WHERE `account_id` = $AccountID AND `check_id` = '$CheckID';");
		if(!$SelectSQL) {
			error(43, mysqli_error($DB["website"]), $DB["website"]);
			return false;
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return false;
		} else {
			return true;
		}
	}
	
	function GetAccountName($AccountID, $DB) {
		$SelectSQL = mysqli_query($DB["account"], "SELECT `login` FROM `account` WHERE `id` = $AccountID;");
		if(!$SelectSQL) {
			error(44, mysqli_error($DB["account"]), $DB["website"]);
			return "(Eroare)";
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return "(Cont inexistent)";
		} else {
			$AccountData = mysqli_fetch_array($SelectSQL);
			return $AccountData["login"];
		}
	}
	
	function GetPlayerName($PlayerID, $DB) {
		$SelectSQL = mysqli_query($DB["player"], "SELECT `name` FROM `player` WHERE `id` = $PlayerID;");
		if(!$SelectSQL) {
			error(45, mysqli_error($DB["player"]), $DB["website"]);
			return "(Eroare)";
		} elseif(mysqli_num_rows($SelectSQL) == 0) {
			return "(Jucator inexistent)";
		} else {
			$AccountData = mysqli_fetch_array($SelectSQL);
			return $AccountData["name"];
		}
	}
	
	function calcPages($Entries, $Page, $Limit) {
		$output = array();
		
		if($Page == 0) {
			$Page = 1;
		}
		
		$output[0] = ceil(($Entries/$Limit));
		$output[1] = ($Page * $Limit) - $Limit;
		return $output;
	}
	
	function secondsToTime($inputSeconds) {
		$secondsInAMinute = 60;
		$secondsInAnHour = 60 * $secondsInAMinute;
		$secondsInADay = 24 * $secondsInAnHour;
		$days = floor($inputSeconds / $secondsInADay);
		$hourSeconds = $inputSeconds % $secondsInADay;
		$hours = floor($hourSeconds / $secondsInAnHour);
		$minuteSeconds = $hourSeconds % $secondsInAnHour;
		$minutes = floor($minuteSeconds / $secondsInAMinute);
		$remainingSeconds = $minuteSeconds % $secondsInAMinute;
		$seconds = ceil($remainingSeconds);
		$obj = array(
			'd' => (int) $days,
			'h' => (int) $hours,
			'm' => (int) $minutes,
			's' => (int) $seconds,
		);
		return $obj;
	}
	
	function getShortNumber($amount)
	{
		$amount = (int)$amount;
		if($amount)
		{
			if($amount == 5)
				return 7606;
			elseif($amount == 6)
				return 7505;
			elseif($amount == 7)
				return 7507;
			elseif($amount == 8)
				return 7608;
			elseif($amount == 9)
				return 7676;
			elseif($amount == 10)
				return 7575;
			elseif($amount == 20)
				return 7654;
		}
		return false;
	}
	
	function getCodeStatus($code, $amount)
	{
		$number = getShortNumber($amount);
		$urlToCheck = "https://voxshop.ro/parteneri/general/api/check-code/".$code."/".$number;
		$authorization_code = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjcxMDA2OTY3LCJzdWIiOjIsImlzcyI6Imh0dHBzOlwvXC92b3hzaG9wLnJvXC9wYXJ0ZW5lcmlcL2dlbmVyYWxcL2FkbWluaXN0cmFyZVwvdG9rZW4iLCJpYXQiOjE0ODc3ODAyOTcsImV4cCI6MTgwNDAwNDI5NywibmJmIjoxNDg3NzgwMjk3LCJqdGkiOiIwZDMyMTMwMGQ5MDYzNWQ5MzQxYWQ3NzRmNmI4ODA5ZSJ9.H2jrhQBSkDQG6LxxkyHH9CtwnMq_gyasX9M7LmklS9c";
		$authorization = "Authorization: Bearer ".$authorization_code;
		
		// Get cURL resource
		$curl = curl_init();
		// Set some options - we are passing in a useragent too here
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_URL => $urlToCheck,
			CURLOPT_HTTPHEADER => array('Content-Type: application/json' , $authorization )
		));
		// Send the request & save response to $resp
		$resp = curl_exec($curl);
		$error = curl_error();
		// Close request to clear up some resources
		curl_close($curl);
		if(!$error)
		{
			$resp = json_decode($resp);
			if($resp)
			{
				$return = array('status' => (int)$resp->status_code);
				if((int)$resp->status_code === 1)
				{
					$return['tel'] = $resp->data->sender;
					$return['keyword'] = $resp->data->service;
					$return['destination'] = $resp->data->destination;
				}
				return $return;
			}
		}
		else
		{
			logTransaction(array(
				'status'	=> 'error',
				'error'		=> $error
			));
		}
	}
	
	function getTransactionError($status_code)
	{
		if($status_code == 1)
			return "Tranzactie reusita!";
		elseif($status_code == 3)
			return "Codul a fost deja folosit!";
		elseif($status_code == 4)
			return "Cod valid dar de alta valoare";
		elseif($status_code == 5)
			return "Cod invalid";
		elseif($status_code == 401)
			return "Operatiune neautorizata - contactati suportul";
		return false;
	}
?>