<<?php
include("../config.php3");
include($BIB."bib_generic.php3");


####################
# Administration script defaults
####################
# pas de timeout possible qql soit l'action effectuée
set_time_limit($TIME_LIMIT);

# le script continue une fois qu'il est lancé qql soit l'état de la connection après
//ignore_user_abort(true);


ini_set("memory_limit","2048M");



function init_player_tab(&$player_tab)
{

	// on récupère tout le monde
	$query = "SELECT Id, NickName, RootPId, Score, KF, Niveau FROM Players ORDER By Score DESC, Time ASC";
	echo "<br>Recup des scores en cours : ".$query."<br>";
	$all_players = main_db_query($query);
	while ($player = db_fetch_array($all_players))
	{
		$players_rootpid_tab[$player['Id']] = $player['RootPId'];
		$players_nickname_tab[$player['Id']] = $player['NickName'];
		$players_score_tab[$player['Id']] = $player['Score'];
		$players_kf_tab[$player['Id']] = $player['KF'];
		$players_niveau_tab[$player['Id']] = $player['Niveau'];
	}

	// on range les résultats
	arsort($players_score_tab);
	arsort($players_kf_tab);
	arsort($players_niveau_tab);

	$i = 1;
	while (list ($playerId, $playerScore) = each ($players_score_tab))
	{
		$player_tab[$playerId][Score] = $playerScore;
		$player_tab[$playerId][ScoreRank] = $i;
		$player_tab[$playerId][NickName] = $players_nickname_tab[$playerId];
		$i++;
	}
	
	$i = 1;
	while (list ($playerId, $playerKF) = each ($players_kf_tab))
	{
		$player_tab[$playerId][KF] = $playerKF;
		$player_tab[$playerId][KFRank] = $i;
		$player_tab[$playerId][RootNickName] = $players_nickname_tab[$players_rootpid_tab[$playerId]];
		$i++;
	}

	$i = 1;
	while (list ($playerId, $playerNiveau) = each ($players_niveau_tab))
	{
		$player_tab[$playerId][Niveau] = $playerNiveau;
		$player_tab[$playerId][NiveauRank] = $i;
		$i++;
	}

	return 1;
}


function init_playerscores_tab(&$LastScores, $TourId, $date_derniere_archive="")
{
	if ($date_derniere_archive != "")
		$select_date = " AND Date='".$date_derniere_archive."' ";
	else
		$select_date = " ";
	$query = "SELECT Id, PlayerId, ScoreRank, KFRank, NiveauRank, Score, KF, Niveau FROM PlayerScores WHERE TourId='".$TourId."' ".$select_date." ORDER By Score DESC";
	echo "<br> Rech : ".$query."<br>";
	$PlayerScores = main_db_query($query);
	while ($PlayerScore = db_fetch_array($PlayerScores))
	{
		$playerId = $PlayerScore['PlayerId'];
		$LastScores[$playerId][PlayerScoreId] = $PlayerScore['Id'];
		$LastScores[$playerId][Score] = $PlayerScore['Score'];
		$LastScores[$playerId][ScoreRank] = $PlayerScore['ScoreRank'];

		$LastScores[$playerId][KF] = $PlayerScore['KF'];
		$LastScores[$playerId][KFRank] = $PlayerScore['KFRank'];

		$LastScores[$playerId][Niveau] = $PlayerScore['Niveau'];
		$LastScores[$playerId][Niveau] = $PlayerScore['NiveauRank'];
	}
}

?>
<html>
<head></head>
<link rel="stylesheet" href="admin.css">
<body rightmargin=0>
<div align=center class=trTitle>Archivage des scores</div>
<br>
<?php
//debug("Affichage page Archivage");
if ($submit=="Archiver")
{
	//debug("Achvage demandé");
	# recup de la date
	if ($aDate == "")
		$aDate = date("Y-m-d H:i:s", my_local_time());

	if ($auto == 1)
	{
		//debug("Achvage Automatique");
		echo "Archivage automatique<br>";
		// on passe en auto
		
		// 1. récup du TourId
		$cur_tour = db_fetch_array(main_db_query("SELECT Id, Name FROM Tours WHERE ShowTime<='".$aDate."' AND EndTime>='".$aDate."' ORDER BY EndTime DESC LIMIT 0,1"));
		echo "Tour ".$cur_tour['Id']." : ".$cur_tour['Name']."<br>";
		
		$TourId = $cur_tour['Id'];
		// 2. On archive tout le monde
		$all = 1;
		$joueurs_actifs = 0;
	}


	if ($TourId == "")
	{
		$TourId = 0;
	}
	
	if ($TourId == 0)
	{
		echo "Pas de tours !";
		return;
	}
	//debug("Achvage init player tab");
	init_player_tab($player_tab);
	//debug("Achvage sortie player tab");
	// quelle est la date de la dernière archive ?
	$query = "SELECT Date FROM PlayerScores WHERE TourId='".$TourId."' ORDER By Date DESC Limit 0,1";
	echo $query;
	$dateRow = db_fetch_array(main_db_query($query));
	
	if ($dateRow['Date'] != "")
	{
		$date_derniere_archive = $dateRow['Date'];
		echo "Dernière archive : ".$date_derniere_archive."<br>";
	}
	else
	{
		echo "Pas de dernière archive<br>";
		$date_derniere_archive = "";
	}
	//debug("Achvage init_playerscores_tab");
	init_playerscores_tab($LastScores, $TourId, $date_derniere_archive);
	//debug("Achvage sortie playerscores_tab");

	$Critere_Restriction = "";
	$Critere_Limite = "";
	
	if (($Critere_Score == 1) && ($Score_Min >=0))
		$Critere_Restriction .= " Score >= ".$Score_Min;
		
	if ($Critere_Classement == 1)
		$Critere_Limite .= " LIMIT ".($Classement_Min-1).", ".($Classement_Max - $Classement_Min +1);
	else
		echo "Pas de critère de classement (".$Critere_Classement.")<br>";
	
	if (($joueurs_actifs == 1) && ($TourId>0))
	{
		$Tour = db_fetch_array(main_db_query("SELECT * FROM Tours WHERE Id='".$TourId."' LIMIT 0,1"));
		$Players = main_db_query("SELECT DISTINCT(PlayerId) FROM Paris WHERE Date >='".$Tour['ShowTime']."' AND Date <= '".$Tour['EndTime']."'");
	}
	else
	{
		// 1 on récupère les joueurs voulus.
		if (($all == 1) || ($Critere_Restriction == ""))
		{
			$Players = main_db_query("SELECT Id FROM Players ORDER By Score DESC, Time ASC ".$Critere_Limite);
			flush();
		}
		else
		{
			$Players = main_db_query("SELECT Id FROM Players WHERE ".$Critere_Restriction." ORDER By Score DESC, Time ASC  ".$Critere_Limite);
		}
	}

	// maintenant qu'on a les players, on va les archiver l'un après l'autre.
	//-1 pour unlimited !
	$max_i = -1;
	$i = 0;
	//debug("Achvage on parcours les joueurs");
	while (($Player = db_fetch_array($Players)) && ($i < $max_i or $max_i == -1))
	{
		$i++;
		echo ".";
		if (($i%200) == 0)
			echo "<br>";

		flush();
		$playerId = $Player['Id'];
		$NickName = $player_tab[$playerId][NickName];
		$rootNickName = $player_tab[$playerId][RootNickName];
		$score = $player_tab[$playerId][Score];
		$rank = $player_tab[$playerId][ScoreRank];
		
		$KF = $player_tab[$playerId][KF];
		$rankKF = $player_tab[$playerId][KFRank];

		$Niveau = $player_tab[$playerId][Niveau];
		$rankNiveau = $player_tab[$playerId][NiveauRank];
		
		if ($LastScores[$playerId][PlayerScoreId] > 0)
		{
			# VarScore variation de la place suivant les points
			$VarScore = ($rank - $LastScores[$playerId][ScoreRank]);
		
			# VarKF variation de la place suivant les KF
			$VarKF = ($rankKF - $LastScores[$playerId][KFRank]);

			# VarNiveau variation de la place suivant les Niveaux
			$VarNiveau = ($rankNiveau - $LastScores[$playerId][NiveauRank]);

			$query = "INSERT DELAYED INTO PlayerScores ".
			"(PlayerId, PlayerName, RootName, Score, ScoreVariation, ScoreRank, ScoreRankVariation, Date, TourId, KF, KFVariation, KFRank, KFRankVariation, Niveau, NiveauVariation, NiveauRank, NiveauRankVariation) VALUES ".
			"('".$playerId."', '".addslashes($NickName)."', '". addslashes($rootNickName)."', '".$score."', '".($score - $LastScores[$playerId]['Score'])."', '".$rank."', '".$VarScore."', '".$aDate."', '".$TourId."', ".
			"'".$KF."', '".($KF - $LastScores[$playerId][KF])."', '".$rankKF."', '".$VarKF."', ".
			"'".$Niveau."', '".($Niveau - $LastScores[$playerId][Niveau])."', '".$rankNiveau."', '".$VarNiveau."')";

		}
		else
		{
			$VarScore = 0;
			$VarKF = 0;
			$VarNiveau = 0;

			$query = "INSERT DELAYED INTO PlayerScores ".
			"(PlayerId, PlayerName, RootName, Score, ScoreVariation, ScoreRank, ScoreRankVariation, Date, TourId, KF, KFVariation, KFRank, KFRankVariation, Niveau, NiveauVariation, NiveauRank, NiveauRankVariation) VALUES ".
			"('".$playerId."', '".addslashes($NickName)."', '".addslashes($rootNickName)."', '".$score."', '0', '".$rank."', '0', '".$aDate."', '".$TourId."', ".
			"'".$KF."', '0', '".$rankKF."', '0', ".
			"'".$Niveau."', '0', '".$rankNiveau."', '0')";
		}
		
//		echo $query."<br>";
		main_db_query($query);
		# ici on met à jour la table des Players
		main_db_query("UPDATE Players SET ScoreRankVariation='".$VarScore."', KFRankVariation='".$VarKF."', NiveauRankVariation='".$VarNiveau."' WHERE Id='".$Player['Id']."'");
	}
	//debug("Achvage fin de parcours des joueurs");
	echo "Archviage terminé<br>";
}
elseif (($submit=="Supprimer") && ($TourId > 0))
{
	$dateRow = db_fetch_array(main_db_query("SELECT Date FROM PlayerScores WHERE TourId='".$TourId."' ORDER By Date DESC Limit 0,1"));
	if ($dateRow['Date'] != "")
	{
		main_db_query("DELETE FROM PlayerScores WHERE Date='".$dateRow['Date']."' AND TourId='".$TourId."'");
		echo "<font color=red>effacement OK (de l'archive du tour $TourId, datée du ".$dateRow['Date'].")!</font><br>";
	}
}

elseif (($submit=="Remplacer") && ($TourId > 0))
{
	$dateRow = db_fetch_array(main_db_query("SELECT Date FROM PlayerScores WHERE TourId='".$TourId."' ORDER By Date DESC Limit 0,1"));
	if ($dateRow['Date'] != "")
	{
		$rows = main_db_query("SELECT PlayerId, Score, KF, Niveau FROM PlayerScores WHERE Date='".$dateRow['Date']."' AND TourId='".$TourId."'");
		while($row = db_fetch_array($rows))
		{
			main_db_query("UPDATE Players SET Score='".$row['Score']."', KF='".$row['KF']."', Niveau='".$row['Niveau']."' WHERE Id='".$row['PlayerId']."'");
		}
	
		echo "<font color=red>Remplacement des scores actuel par l'archive du tour $TourId, datée du ".$dateRow['Date']."! OK !</font><br>";
	}	
}

elseif (($submit == "Afficher") && ($TourId > 0))
{
	// Quelle date prendre ?
	$DateRow = db_fetch_array(main_db_query("SELECT Date FROM PlayerScores WHERE TourId='".$TourId."' ORDER By Date DESC Limit 0,1"));
	if ($all == 1)
	{
		$ShowScores = main_db_query("SELECT * FROM PlayerScores WHERE TourId='".$TourId."' AND Date='".$DateRow['Date']."' ORDER By Score DESC");
	}
	else
	{
		$ShowScores = main_db_query("SELECT * FROM PlayerScores WHERE TourId='".$TourId."' AND Date='".$DateRow['Date']."' ORDER By Score DESC LIMIT ".($Classement_Min-1).", ".($Classement_Max - $Classement_Min +1));
	}

?>
<div class=trTitle>Les joueurs de la dernière archive du tour <?php echo $TourId?></div>
<table border=0 cellpadding=4 cellspacing=4 class=univers>
	<tr class=trTitle>
		<td >No</td>
		<td >Id Joueur</td>	
		<td >Nom Joueur</td>		
		<td >Dynastie</td>
		<td >Score</td>		
		<td >Variation Score</td>		
		<td >Classement Score</td>		
		<td >Variation Classement Score</td>		
		<td >KFs</td>		
		<td >Variation KF</td>		
		<td >Classement KF</td>		
		<td >Variation Classement KF</td>		
		<td >Niveau</td>		
		<td >Variation Niveau</td>		
		<td >Classement Niveau</td>		
		<td >Variation Classement Niveau</td>		
	</tr>
<?php
# on affiche les matchs dont les résultats on été rentrés pour tel category

while($ShowScore = db_fetch_array($ShowScores))
{
	$color = ($r % 2 == 0)? "#FFFFFF":"#E8E8E8";
	$r++;
	echo "<tr bgcolor=".$color.">";
	echo "<td>".$ShowScore['Id']."</td>";
	echo "<td>".$ShowScore['PlayerId']."</td>";
	echo "<td>".$ShowScore['PlayerName']."</td>";
	echo "<td>".$ShowScore['RootName']."</td>";
	echo "<td>".$ShowScore['Score']."</td>";
	echo "<td>".$ShowScore['ScoreVariation']."</td>";
	echo "<td>".$ShowScore['ScoreRank']."</td>";
	echo "<td>".$ShowScore['ScoreRankVariation']."</td>";
	echo "<td>".$ShowScore['KF']."</td>";
	echo "<td>".$ShowScore['KFVariation']."</td>";
	echo "<td>".$ShowScore['KFRank']."</td>";
	echo "<td>".$ShowScore['KFRankVariation']."</td>";
	echo "<td>".$ShowScore['Niveau']."</td>";
	echo "<td>".$ShowScore['NiveauVariation']."</td>";
	echo "<td>".$ShowScore['NiveauRank']."</td>";
	echo "<td>".$ShowScore['NiveauRankVariation']."</td>";
	echo "</tr>";
	if ($r == 0)
		$ShowDate = $ShowScore['Date'];
}

echo "</table><br>Date d'archivage : ".$ShowDate."<br>";
}

?>
<table border=1 class=univers>
	<tr class=trTitle>
		<td align=center colspan=9>Liste des Tours</td>
	</tr>
	<tr class=trTitle>
		<td >N°</td>
		<td >Nom</td>	
		<td >ShowTime</td>		
		<td >EndTime</td>
		<td >Done</td>		
	</tr>
<?php
# on affiche les matchs dont les résultats on été rentrés pour tel category
$TourRows = main_db_query("SELECT * FROM Tours ORDER By ShowTime ASC");

while($TourRow = db_fetch_array($TourRows))
{
	if (time_diff_now($TourRow[ShowTime]) > 0 and time_diff_now($TourRow[EndTime]) < 0)
		echo "<tr bgcolor=yellow>";
	elseif (time_diff_now($TourRow[ShowTime]) > 0)
		echo "<tr bgcolor=#CCCCCC>";
			
	echo "<td>".$TourRow['Id']."</td>";
	echo "<td>".$TourRow['Name']."</td>";
	echo "<td>".$TourRow['ShowTime']."</td>";
	echo "<td>".$TourRow['EndTime']."</td>";
	echo "<td>".$TourRow['Done']."</td>";
	echo "</tr>";
}

?>

</table>
<br>
<hr>
<br>
<form>
Archiver :
<br>
Numéro du tour : <input type=text name=TourId value="<?php echo $TourId?>">
<br>
<input type=radio name=joueurs_actifs value=1>&nbsp;Archiver les joueurs actifs de ce tour
<br>
<input type=radio name=joueurs_actifs value=0>&nbsp;Archiver ...
<br>
<input type=checkbox name=Critere_Classement value="1"> Restreindre au joueurs classés ...<br>
De la place : <input type=text name=Classement_Min value="<?php echo $Classement_Min ?>"> (à partir de 1)
<br>
à la place  : <input type=text name=Classement_Max value="<?php echo $Classement_Max ?>">
<br>
<input type=checkbox name=all value=1> Tous
<br>
<input type=checkbox name=Critere_Score value=1> Dont le score est supérieur à <input type=Text name=Score_Min value="<?php echo $Score_Min?>">&nbsp;points
<br><br>
<input type=submit name=submit value="Archiver">
<br><br>
</form>
<hr>
<form>
Effacer :
<br>
La dernière archive du tour : <input type=text name=TourId value="<?php echo $TourId?>">
<br>
<input type=submit name=submit value="Supprimer">
<br><br>
</form>
<hr>
<form>
Remplacer (ATTENTION à annuler tous les matchs éventuels entre le score actuel et la dernière archive !!!) :
<br>
La dernière archive du tour : <input type=text name=TourId value="<?php echo $TourId?>">
<br>
<input type=submit name=submit value="Remplacer">
<br><br>
</form>

<hr>
<form>
Afficher :
<br>
L'archive du tour : <input type=text name=TourId value="<?php echo $TourId?>">
<br>
De la place : <input type=text name=Classement_Min value="<?php echo $Classement_Min ?>"> (à partir de 1)
<br>
à la place  : <input type=text name=Classement_Max value="<?php echo $Classement_Max ?>">
<br>
Ou <input type=checkbox name=all value=1> Tous
<br>
<input type=submit name=submit value="Afficher">
<br><br>
</form>

