<?php

# suivant l'origine, cette fonction retourne le bon template à charger et remplace les tags
function loadMail($origine, $style, $message, $guestUrl, $template = "")
{
	global $GAME_NAME, $GAME_DIR, $SITES_ORIGINES, $ORIGINE, $LOGIN_PAGE, $SERVER_URL;
	global $member, $player;
	
	if ($template != "")
		$msg = loadTemplate($GAME_DIR."Mailing/".$template);
	else
	{
		$msg = loadTemplate($GAME_DIR."Mailing/template_invitation.html");
	}
		
	$msg = replaceTag("__FONT__", $style, $msg);
	$msg = replaceTag("__FATHEREMAIL__", $member['Email'], $msg);
	$msg = replaceTag("__MSG__", $message, $msg);
	$msg = replaceTag("__FULLNAME__", stripslashes($member['FirstName']." ".$member['Name']), $msg);
	$msg = replaceTag("__URL__", $guestUrl, $msg);
	$msg = replaceTag("__SERVEUR_URL__", $SERVER_URL, $msg);

	return $msg;
}


############## Send an invitation
function sendmail($guestemail, $guestId, $message, $template = "")
{
	global $GAME_NAME, $GAME_DIR, $SITES_ORIGINES, $ORIGINE, $LOGIN_PAGE, $SERVER_URL;
	global $REGISTRATION_PAGE, $member;
 
	$subject= $GAME_NAME." ?! ".stripslashes($member['FirstName']." ".$member['Name'])." vous invite ..."; 
		
	$msg = loadMail($member['Origine'], "<font face=verdana size=2 color=black>", nl2br($message), $REGISTRATION_PAGE."?id=".$guestId, $template);

	generic_mail($guestemail, $subject, $msg,
		     "From: ".$member['Email']."\n" . 
		     "Reply-To: ".$member['Email']."\n" . 
		     "X-Mailer: PHP/" . phpversion()."\n".
		     "MIME-Version: 1.0\n".
		     "Content-Type: text/html; charset=iso-8859-1"."\n"
		     );
}

###############

function invite($guestemail, &$player, &$member, &$message, $checkGuestAlreadyInvited = true)
{
	global $GAME_NAME;

	$result = $error = "";
    $emails = extractemail($guestemail);

	if (count($emails) <= 0)
		$error= "Veuillez indiquer l'email de votre invite SVP";
		
    for ($i = 0; $i < count($emails); $i++)
	{
    	$guestemail = trim($emails[$i]);

		if (checkemail($guestemail))
		{
		    # Checking membership
	      	$rowmember = main_db_query("SELECT * FROM Members WHERE Email = '$guestemail'");
			
	      	if ($guestmember = db_fetch_array($rowmember))
			{
				# Already a member
				$error = $guestemail . " est déjà inscrit sur ".$GAME_NAME.", il ne peut être invité<br>";
      		}
			else
			{
				$rowguest = db_fetch_array(main_db_query("SELECT * FROM Guests WHERE Email = '$guestemail' AND FatherPId = '".$player[Id]."'"));
				
				if ($rowguest['Id'] > 0)
				{
					if ($checkGuestAlreadyInvited)
						# Already a member
						$error .= "Vous avez déjà invité ".$guestemail . " !<br>";
					else
					{
						# Ici cela concerne les relance. Ie, il peut réinviter la personne (si celle-ci n'est pas inscrite
					  	sendmail($guestemail, $rowguest['GuestId'], $message, "template_invitation_relance.html");
					}
				}
				else
				{
			  		# New guest

					# ajout du guest dans la table Guests
				  	main_db_query("INSERT INTO Guests (Email, FatherPId, GuestId) VALUES ('$guestemail', $player[Id], '')");
				  	
					# recup de l'id inséré dans la table Guest
					$newGuest = db_fetch_array(main_db_query("SELECT Id FROM Guests WHERE Email = '$guestemail' ORDER BY Id DESC LIMIT 0,1"));
					
					# on construit le GuestId
					# $newGuest[Id] est unique, md5(uniqid(rand())) est une chaine sur 32 char, on a donc un
					# id unique (grace à newGuestId et imprédictible grace au md5(...)
					$id = $newGuest[Id].md5(uniqid(rand()));
					
					# on update le guest Id ainsi composé
					main_db_query("UPDATE Guests SET GuestId='".$id."' WHERE Id='".$newGuest[Id]."'");
					
					# Sending invitation message
				  	sendmail($guestemail, $id, $message, "template_invitation.html");
					$result .= "Votre invitation a été envoyée à $guestemail.<br>";
					//$result = "<div class=smallBoldDark>Bravo, vous avez invité ".."<br>nous vous informerons dès que celui-ci s'inscrira au jeu !<br><br>Souhaitez-vous parrainer une autre personne ?</div>";
				}
			}
  		}
  		elseif ($guestemail != "")
		{
	    	$error= $guestemail." n'est pas une adresse valide";
	    }
	}
	
	if ($result != "")
		$result = "<div class=smallBoldBlue>".$result."</div><br>";
		
	return array($error, $result);
}


# If active : process and/or display the invitation form
$error = "";
# If form has been filled out
if (isset($invitation))
{
	if (empty($guestemail1))
	{
    	$error= "Veuillez indiquer l'email de votre invité SVP";
	}
	
	if (empty($error))
	{
		$emails = $guestemail1.",".$guestemail2.",".$guestemail3.",".$guestemail4;
		list($error, $result) = invite($emails, $player, $member, $message);
  	}
}


$form_action = $sess->action($ADD_FRIENDS_PAGE);
$form_name = "invit";

$msg = loadMail($member['Origine'], "<font face=arial size=1 color=005f3f>", "<div class=smallBoldDark>Votre message :<br><textarea tabindex=2 name=message cols=40 rows=5></textarea></div>", $SERVER_URL."lien_de_parrainage");


//if (!isset($result))
	//$result = "<span class=smallbolddark>Voici l'email qui sera envoyé à votre ami :</span>";


include("invitation.inc");




?> 
