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


# pas de timeout possible quelle que soit l'action effectuée
set_time_limit($TIME_LIMIT);

####################
# Administration script defaults
####################
# pas de timeout possible qql soit l'action effectuée
function cmp_score($a,$b)
{
	if ($a==$b)
		return 0;
	
	if ($a>$b)
		return 1;
	else
		return 2;
}

function calcule_gain($Result,$Bet,$Amount,$rate1,$rate2)
{
	# si on a le meme resultat, score exact, on sort avec rate1
	if ($Result == $Bet)
	{
		return $Amount*$rate1;
	}
	
	# on etudie le result
	$tabResult = explode("-",$Result);
	$ResultType = cmp_score($tabResult[0],$tabResult[1]);

	# on etudie le Bet
	$tabBet = explode("-",$Bet);
	$BetType = cmp_score($tabBet[0],$tabBet[1]);

	# s'il a le gagnant, on sort avec rate2
	# sinon juste avec 1
	if ($BetType==$ResultType)
		return $Amount*$rate2;
	else
		return 0;
}

?>
<html>
<head></head>
<link rel="stylesheet" href="admin.css">
<body rightmargin=0>
<div align=center class=trTitle>stats</div>
<br>

<?php

if ($submit == "Valider")
{
	$matchs = main_db_query("SELECT MatchId, Result FROM Matchs WHERE Matchs.Date >= '".$DateFrom."' AND Matchs.Date <= '".$DateTo."' ORDER BY MatchId ASC");
	echo db_num_rows($matchs)." matchs à traiter...<br>";
	while($match = db_fetch_array($matchs))
	{
		flush();
		$result = $match['Result'];
		$matchId = $match['MatchId'];
		# récup des paris et des résultats associés
		$rows = main_db_query("SELECT DISTINCT(MatchId), PlayerId, Bet FROM Paris WHERE Paris.Done!='0' AND Paris.MatchId='".$matchId."'");	
		echo db_num_rows($rows)." paris à traiter...<br>";
		flush();
		$i=0;
		while($row = db_fetch_array($rows))
		{
			$CurMatchId = $row[MatchId];
			$CurPlayerId = $row[PlayerId];
		
			$gain_joueur = calcule_gain($result,$row[Bet], 1, $KF_GAINS_PERFECT, $KF_GAINS_CORRECT);
			$result[$CurPlayerId][KF] += $gain_joueur;
			$result[$CurPlayerId][N] ++;
			$query = "UPDATE Paris Set Result='";
			if ($gain_joueur == $KF_GAINS_PERFECT)
				$query .= $RESULTAT_PERFECT;
			elseif ($gain_joueur == $KF_GAINS_CORRECT)
				$query .= $RESULTAT_CORRECT;
			else
				$query .= $RESULTAT_ECHEC;

			$query .= "' WHERE PlayerId='".$CurPlayerId."' AND MatchId='".$CurMatchId."'";

//			echo $query.'<br>';
			main_db_query($query);	

			$i++;
			if ($i % 10000==0)
			{
				echo $i."-";
				flush();
			}
		}
	}

	echo $error;

}
?>
<form>
<table>
	<tr>
		<td>
			Du
		</td>
		<td>
			<input type=text name=DateFrom value="<?php echo $DateFrom ?>">AAAA-MM-JJ HH:MM:SS
		</td>
	</tr>
	<tr>
		<td>
			au :
		</td>
		<td>
			<input type=text name=DateTo value="<?php echo $DateTo ?>">AAAA-MM-JJ HH:MM:SS
		</td>
	</tr>
</table>
<br><br>
<input type=submit name=submit value="Valider">
</form>