<?php
include("../config.php3");
include($BIB."bib_generic.php3");
include($BIB."bib_admin.php3");
include($BIB."bib_mailing.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);

####################
# constants
####################

$MAIL_RESULT_TEMPLATE = $GAME_DIR."/mailing/template_resultats.html";
$MAIL_RESULT_TEMPLATE_LYCOS = $GAME_DIR."/mailing/template_resultats_lycos.html";
$MAIL_RESULT_TEMPLATE_M6 = $GAME_DIR."/mailing/template_resultats_m6.html";
?>
<html>
<head></head>
<link rel="stylesheet" href="admin.css">
<body rightmargin=0>
<div align=center class=trTitle>Mise à jour des scores</div>
<br>
<?php
####################
# Start functions
####################
function buildMatchsTab($matchIds)
{
	while($matchId = db_fetch_array($matchIds))
	{
		$match = db_fetch_array(main_db_query("SELECT * FROM Matchs WHERE MatchId='".$matchId[MatchId]."'"));
		$tabMatchs[$match[MatchId]][Team1] = $match[Team1];
		$tabMatchs[$match[MatchId]][Team2] = $match[Team2];
		$tabMatchs[$match[MatchId]][Result] = $match[Result];
	}
	return $tabMatchs;
}

function buildResults($rate,$tabMatchs,&$tabGainAll)
{
	while(list($matchId,$rest) = each($tabMatchs))
	{
		# recup des gains en prono
		getTab_gainProno($matchId,$rest[Result],$tabGainAll);
		

		# si on recup des points de ses filleuls
		if ($rate>0)
		{
			# on a les gains des joueurs ayant pariés à ce match
			# on va maintenant ajouter les gains des filleuls
			getTab_gainFilleuls($matchId,$rate,$tabGainAll);
		}

		//echo "<br>id : ".$matchId." - ".count($tabGainAll);
		
		
		# on recupere le tableau de gain total
		getTab_gainTotal($matchId,$tabGainAll);
	}
}

function viewArray(&$tabGainAll)
{
	if (count($tabGainAll)>0)
		reset($tabGainAll);

	while(list($playerId,$match)=each($tabGainAll))
	{
		echo "playerId:".$playerId."<br>";
		while(list($matchId,$rest)=each($match))
		{
			echo "matchId:".$matchId."<br>";
			echo "Bet:".$rest[Bet]."<br>";
			echo "Amount:".$rest[Amount]."<br>";
			echo "gainProno:".$rest[gainProno]."<br>";
			echo "gainFilleul:".$rest[gainFilleul]."<br>";
			echo "gainTotal:".$rest[gainTotal]."<br>";
		}
	}
	
	if (count($tabGainAll)>0)
		reset($tabGainAll);

}

function mail_result_template($MessageHaut,$MessageBas,$player,$rate,$tabMatchs,&$tabGainAll, $color1, $color2)
{
	global $BET_NOT_SENT,$MAIL_RESULT_TEMPLATE,$tabIn,$ARCHIVES_DIR,$ORIGINE_KTF;
	global $BG_COLOR_FOND_1, $BG_COLOR_FOND_4, $BG_COLOR_FOND_6, $KF_PERFECT, $KF_CORRECT, $IMAGES_DIR;
	
	$MessageHaut=nl2br($MessageHaut);
	$MessageBas=nl2br($MessageBas);
	
	# composition du mail

	$mail="";
	for($r=0;$r < count($tabIn);$r++)
	{
		$tabInVal = chop($tabIn[$r]);
		
		switch($tabInVal)
		{
						
			case "__PLAYER_NICKNAME__":
				$mail .= "Bonjour ".$player[NickName]." !\n";
				break;
				
			case "__MESSAGE_UP__":
				$mail .= $MessageHaut."\n";
				break;
				
				
			case "__RESULTS__":
				if($player["Origine"]==$ORIGINE_KTF)
				{
					# on recupere le tag de pub
					eval(file_get_contents($ARCHIVES_DIR."pub_mail.html"));				
					# le tableau de résultats
					$mail .="<table width=100% border=0 cellspacing=1 cellpadding=0>\n";
					$mail .="<tr><td colspan=5 align=center>".$pub_banner."<br></td></tr>\n";
					$mail .= "<tr>\n";
				}
				else
				{
					$mail .="<table width=100% border=0 cellspacing=1 cellpadding=0>\n";
					$mail .= "<tr>\n";
				}
				$mail .= "<td align=center colspan=3><font size=1 face=verdana color=".$BG_COLOR_FOND_1."><b>Match</b></td>\n";
				$mail .= "<td colspan=1 align=left><font size=1 face=verdana color=".$BG_COLOR_FOND_1."><b>&nbsp;Mon résultat&nbsp;</b></td>\n";
				$mail .= "<td colspan=1 align=right><font size=1 face=verdana color=".$BG_COLOR_FOND_1."><b>Points&nbsp;</b></td>\n";
				$mail .= "</tr>\n";
				$mail .= "<tr>\n";
				$ligne_image = "<img src=\"".$IMAGES_DIR."lignes/ligne_".substr($BG_COLOR_FOND_6, 1).".gif\">";
				$mail .= "<td colspan=5 height=1 align=left >";
				for ($ligne_index = 0 ; $ligne_index < 25 ; $ligne_index++)
					$mail .= $ligne_image;
				$mail .= "</td >\n";
				$mail .= "</tr>\n";
				$mail .= "<tr>\n";
				$mail .= "<td colspan=5 height=3 align=left ></td>\n";
				$mail .= "</tr>\n";
				
				$i=0;
				while(list($matchId,$properties) = each($tabMatchs))
				{
					$pari = $tabGainAll[$player[Id]][$matchId][Bet];
					if ($pari == "")
						continue;
					$color = ($i % 2 == 0) ? $color2 : $color1;
					$i++;
					$mail.= "<tr><td bgcolor=$color align=right><font size=1 face=verdana color=".$BG_COLOR_FOND_1.">".$properties[Team1];
					$mail.= "</font></td>\n";
					$mail.= "<td bgcolor=$color align=center><font size=1 face=verdana color=".$BG_COLOR_FOND_1.">";
					$mail.= "&nbsp;".$properties[Result]."&nbsp;";
					$mail.= "</font></td>\n";
					$mail.= "<td bgcolor=$color align=left><font size=1 face=verdana color=".$BG_COLOR_FOND_1.">";
					$mail.= $properties[Team2];
					$mail.= "</font></td>\n";
					
					# ici on détermine la couleur d'affichage pour indiquer si c un perfect, correct etc...
					if ($properties[Result] != "0")
					{
						$gain_points = $tabGainAll[$player[Id]][$matchId][gainProno];
						$gain = $tabGainAll[$player[Id]][$matchId][gainKF];
						if ($gain_points > 0)
							$gain_points = "+".$gain_points;
						
						$gain_suffixe = "</font>";
						if ( $gain == $KF_PERFECT)
						{
							$gain_points_prefixe = "<font size=1 face=verdana color=".$BG_COLOR_FOND_1."><b>";
							$gain_prefixe = $gain_points_prefixe."Perfect";
							$gain_suffixe = "</b>".$gain_suffixe;
						}
						elseif ($gain == $KF_CORRECT)
						{
							$gain_points_prefixe = "<font size=1 face=verdana color=".$BG_COLOR_FOND_4.">";
							$gain_prefixe = $gain_points_prefixe."Correct";
						}
						else
						{
							$gain_points_prefixe = "<font size=1 face=verdana color="."#FF7777".">";
							$gain_prefixe = $gain_points_prefixe."Echec";
						}
		
						$gain = $gain_prefixe."&nbsp;(".$pari.")</font>";
						$gain_points = $gain_points_prefixe.$gain_points."</font>";
					}	
					else
					{
						$gain_points_prefixe = "<font color="."#9F9F9F".">";
						$gain_prefixe = $gain_points_prefixe;
						$gain = $gain_prefixe."-".$gain_suffixe;
						$gain_points = $gain_prefixe.$gain_suffixe;
					}
	
				$mail.=	"<td bgcolor=$color align=left>&nbsp;\n";
				$mail .= $gain;
				$mail .= "</td>\n";
				$mail.=	"<td bgcolor=$color align=right>\n";
				$mail .= $gain_points;
				$mail .= "&nbsp;</td>\n";

				$mail.="</tr>\n";
				}
				
				$mail.="<tr><td colspan=5>&nbsp;</td>\n";

				
				$mail.="</tr></table>\n";
				break;
				
			case "__MESSAGE_DOWN__":
				$mail.= $MessageBas."\n";
				break;
				
			default:
				$mail .= chop($tabInVal)."\n";
		}
	}
	return $mail;
}
####################
# End function
####################

# on recupere les matchs pour lesquels les résultats n'ont pas été envoyés
$matchIds = main_db_query("SELECT DISTINCT(MatchId) FROM Paris WHERE Done='".$BET_NOT_SENT."'");

# on construit un tableau des proprietés de ces matchs
$tabMatchs = buildMatchsTab($matchIds);

if ($send_mail)
{
	echo "</td></tr></table>";
	
	$subject = stripslashes($subject);
	$MessageBas = stripslashes($MessageBas);
	$MessageHaut = stripslashes($MessageHaut);
	
	# on lit le template
	$tabIn = file($MAIL_RESULT_TEMPLATE);

	# on construit le tableau de résultats sur ces matchs
	buildResults($rate,$tabMatchs,$tabGainAll);
	
	echo count($tabGainAll);
	flush();
//	viewArray($tabGainAll);
	reset($tabGainAll);
	# recup les id des players qui recevront un mail
	$PlayerIds = main_db_query("SELECT DISTINCT(PlayerId) FROM Paris WHERE Done='".$BET_NOT_SENT."' ORDER BY PlayerId ASC");
	$nb_players = db_num_rows($PlayerIds);

	$iii = 0;
	$i=0;
	while($PlayerId = db_fetch_array($PlayerIds) && $i<=1)
	{
		$i++;
		
		# recup du membre et du player
		$member=getmember2($PlayerId[PlayerId]);
		$player=getplayer2($PlayerId[PlayerId]);
		
		$brand = $member['Origine'];
		switch($brand)
		{
			case $ORIGINE_LYCOS:
			// on n'écrit pas aux joueurs de Lycos
			/*
			$tabIn = file($MAIL_RESULT_TEMPLATE_LYCOS);
			$mEmail = $member[Email2];
  			$color1 = "#FFFFFF";
			$color2 = "#FFF0C0";
			*/
			break;
			
			case $ORIGINE_KTF:
			default:
			$tabIn = file($MAIL_RESULT_TEMPLATE);
			$mEmail = $member[Email];
			$color1="#FFFFFF";
			$color2="#F0F0F0";
			break;
			
			case $ORIGINE_M6:
			default:
			$tabIn = file($MAIL_RESULT_TEMPLATE_M6);
			$mEmail = $member[Email];
			$color1="#FFFFFF";
			$color2="#F0F0F0";
			echo "x";flush();
			break;
		}


		if (($DEBUG!=1) || ($member['Email'] == "serei@viralgames.com"))
		{
			# on attend un peu pour le mailer
			waitMail($member[Email]);
			
			# seul les mails KTF sont envoyés
			if ($brand == $ORIGINE_KTF or $brand == $ORIGINE_M6)
			{
				# envoi du mail
			    generic_mail($member[Email], $subject, mail_result_template($MessageHaut,$MessageBas,$player,$rate,$tabMatchs,$tabGainAll, $color1, $color2),
					 "From: $FROM_FIELD\n" . 
					 "Reply-To: $REPLY_TO_FIELD\n" . 
					 "X-Mailer: PHP/" . phpversion()."\n".
					 "MIME-Version: 1.0\n".
							 "Content-Type: text/html; charset=iso-8859-1"."\n");
			}
		}
		else
		{
			if ($i<5)
			{
			    generic_mail("serei@viralgames.com", $subject, mail_result_template($MessageHaut,$MessageBas,$player,$rate,$tabMatchs,$tabGainAll, $color1, $color2),
					 "From: $FROM_FIELD\n" . 
					 "Reply-To: $REPLY_TO_FIELD\n" . 
					 "X-Mailer: PHP/" . phpversion()."\n".
					 "MIME-Version: 1.0\n".
							 "Content-Type: text/html; charset=iso-8859-1"."\n");
				echo "[".$member[Email]." - ".$subject."]<br>\n";
				echo mail_result_template($MessageHaut,$MessageBas,$player,$rate,$tabMatchs,$tabGainAll, $color1, $color2);
				echo "<hr>";
				flush();
			}
			else
			{
				echo "Fin des emails de test";
				exit;
			}
		}

		if ($DEBUG!=1)
		main_db_query("UPDATE Paris SET Done='".$BET_SENT."' WHERE PlayerId='".$PlayerId[PlayerId]."' AND Done='".$BET_NOT_SENT."'");
	}

	/*if ($DEBUG!=1)
		main_db_query("UPDATE Paris SET Done='".$BET_SENT."' WHERE Done='".$BET_NOT_SENT."'");
*/
	echo "<b>Terminé !</b><br>";
	echo "Nb de mails à envoyer : ".$nb_players;
	echo "<br>Nb mails envoyés : ".$i;
}
else
{
	echo "<table border=0 cellpadding=4 cellspacing=4 class=univers>";
	echo "<tr class=trTitle><td colspan=4 align=center >Liste des résultats à envoyer</td></tr>";
	echo "<tr class=trTitle><td>Match N°</td><td>Equipe1</td><td>Equipe2</td><td>Resultat</td></tr>";

	if (count($tabMatchs)>0)
	{
		while(list($matchId,$properties) = each($tabMatchs))
		{
			$color = ($i % 2 == 0)?"#FFFFFF":"#F0F0F0";
			$i++;
			echo "<tr bgcolor=$color class=stdDark><td>".$matchId;
			echo "</td><td>".$properties[Team1];
			echo "</td><td>".$properties[Team2];
			echo "</td><td>".$properties[Result]."</td></tr>";
		}
		echo "</table>";
	}
	else
		echo "<font color=red>Pas de résultats à envoyer</font><br>";


?>

<form method=post>
	<input type=hidden name=send_mail value=1>
	Sujet du mail : <input size=40 type=text name=subject>
	<br><br>
	Message Haut<br><textarea name=MessageHaut rows=10 cols=35></textarea>
	<br><br>
	<font color=green>Ici s'intercale le tableau des résultats</font>
	<br><br>
	Message Bas<br><textarea name=MessageBas rows=10 cols=35></textarea>
	<br>
(Si c'est le cas) <input type=text size=3 name=rate value=0>% des points des filleuls gagnés par le parrain
<br>
<input type=checkbox name=DEBUG value=1>DEBUG MODE
	<br><br>
	<input type=submit>	
</form>

<?php
}
?>

</body>
</html>
