<?php
	set_time_limit(0);
	
	$then = time();
	
	$includes = array(
		"../include/config.php",
		"../include/functions.php",
	);
	
	foreach($includes as $file) {
		if(file_exists($file)) {
			include($file);
		} else {
			die("Eroare la includerea fisierelor necesare!");
		}
	}
	
	// Conectare la bazele de date
	$DBlist = array(
		"account",
		"player",
		"website",
	);
	
	foreach($DBlist as $db) {
		if(isset($databases[$db])) {
			error_reporting(0);
			$DBCon[$db] = mysqli_connect($databases[$db]["host"] . ":" . $databases[$db]["port"], $databases[$db]["user"], $databases[$db]["password"], $databases[$db]["name"]);
			if(!$DBCon[$db]) {
				die(mysqli_connect_error($DBCon[$db]));
			}
			error_reporting(-1);
		} else {
			die("No information found in order to connect to database '$db'.");
		}
	}
	$CacheDelete = mysqli_query($DBCon["website"], "TRUNCATE `highscore_cache`");
	
	if(!$CacheDelete) {
		die(mysqli_error($DBCon["website"]));
	}
	
	$PlayerSQL = mysqli_query($DBCon["player"], "SELECT `player`.`account_id`, `player`.`name`, `player`.`job`, `player_index`.`empire`, `player`.`level`, `player`.`exp` FROM `player` LEFT JOIN `player_index` ON `player`.`account_id` = `player_index`.`id` WHERE `player`.`level` >= 10 AND `player`.`name` NOT LIKE '[%]%' ORDER BY `level` DESC, `exp` DESC");
	if(!$PlayerSQL) {
		die(mysqli_error($DBCon["player"]));
	} else {
		$Result = array();
		$Position = 1;
		while($Row = mysqli_fetch_array($PlayerSQL)) {
			$AccountID = $Row["account_id"];
			$AccountSQL = mysqli_query($DBCon["account"], "SELECT `status` FROM `account` WHERE `id` = $AccountID;");
			$AccountSQLResult = mysqli_fetch_array($AccountSQL);
			if($AccountSQLResult["status"] == "OK") {
				$Name = $Row["name"];
				$Job = $Row["job"];
				if($Job == 0 || $Job == 4) { // Warrior
					$Job = 0;
				} elseif($Job == 1 || $Job == 5) { // Ninja
					$Job = 1;
				} elseif($Job == 2 || $Job == 6) { // Sura
					$Job = 2;
				} elseif($Job == 3 || $Job == 7) { // Shaman
					$Job = 3;
				}	
				$Empire = (isset($Row["empire"]) && !empty($Row["empire"]))  ? $Row["empire"] : "1";
				$Level = (isset($Row["level"]) && !empty($Row["level"]))  ? $Row["level"] : "1";
				$Exp = (isset($Row["exp"]) && !empty($Row["exp"]))  ? $Row["exp"] : "0";
				
				$CacheAppend = mysqli_query($DBCon["website"], "INSERT INTO `highscore_cache` (`name`, `job`, `empire`, `level`, `exp`) VALUES ('$Name', $Job, $Empire, $Level, $Exp);");
				if(!$CacheAppend) {
					die(mysqli_error($DBCon["website"]));
				} else {
					$Position++;
				}
			}
		}
	}
	
	echo "Cache Jucatori actualizat cu succes. Timp scurs: " . gmdate("H:i:s", time() - $then);
?>