<?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 `guild_highscore_cache`");
	
	if(!$CacheDelete) {
		die(mysqli_error($DBCon["website"]));
	}
	
	$GuildSQL = mysqli_query($DBCon["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");
	if(!$GuildSQL) {
		die(mysqli_error($DBCon["player"]));
	} else {
		$Result = array();
		$Position = 1;
		while($Row = mysqli_fetch_array($GuildSQL)) {
			$Name = (isset($Row["name"]) && !empty($Row["name"]))  ? $Row["name"] : "(ERROR)";
			$Master = (isset($Row["master"]) && !empty($Row["master"]))  ? $Row["master"] : "(ERROR)";
			$Empire = (isset($Row["empire"]) && !empty($Row["empire"]))  ? $Row["empire"] : "1";
			$Level = (isset($Row["level"]) && !empty($Row["level"]))  ? $Row["level"] : "1";
			$LadderPoint = (isset($Row["ladder_point"]) && !empty($Row["ladder_point"]))  ? $Row["ladder_point"] : "1";
			
			$CacheAppend = mysqli_query($DBCon["website"], "INSERT INTO `guild_highscore_cache` (`name`, `master`, `empire`, `level`, `ladder_point`) VALUES ('$Name', '$Master', $Empire, $Level, $LadderPoint);");
			if(!$CacheAppend) {
				die(mysqli_error($DBCon["website"]));
			} else {
				$Position++;
			}
		}
	}
	
	echo "Cache Bresle actualizat cu succes. Timp scurs: " . gmdate("H:i:s", time() - $then);
?>