<?php

#####################################
# LOCAL FUNCTIONS
#####################################

function errorPage($error)
{
	sendFatalError("Pb de création de player:".print_r($error, 1));
}

function creationMembre($Login, $Email, $Password, $Vip, $Origine, $tabParams)
{
	global $GAME_NAME,$SERVER_URL,$FROM_FIELD,$REPLY_TO_FIELD;
	global $REGISTRATION_CONFIRM,$REGISTRATION_CONFIRM_PAGE;
	
		#ici on envoie un mail de confirmation d'inscription
		$subject="Bienvenue sur ".$GAME_NAME." !";
		if( $REGISTRATION_CONFIRM == true )
			$msg = loadTemplate("Mailing/template_confirm_registration.html");
		else
			$msg = loadTemplate("Mailing/template_end_registration.html");
		
		$url_confirm = $REGISTRATION_CONFIRM_PAGE."?l=".$Login."&k=".encryptePassword($Origine."_".$Login);
		
//		$msg = replaceTag("__FULLNAME__", stripslashes($tabParams[FirstName]." ".$tabParams[Name]), $msg);
		$msg = replaceTag("__LOGIN__", $Login, $msg);
		$msg = replaceTag("__PASSWORD__", $Password, $msg);
		$msg = replaceTag("__URL_CONFIRM__", $url_confirm, $msg);
		$msg = replaceTag("__GAMEURL__", $SERVER_URL, $msg);
	
		generic_mail($Email, $subject, $msg,
				"From: ".$GAME_NAME." <".$FROM_FIELD.">\n" . 
				"Reply-To: $FROM_FIELD\n" . 
				"X-Mailer: PHP/" . phpversion()."\n".
				"MIME-Version: 1.0\n".
				"Content-Type: text/html; charset=iso-8859-1"."\n"
		);

		# # # le password ne doit pas être stocké, on le crypte
		$Password = encryptePassword($Password);

		return new Membre($Login, $Email, $Password, $Vip, $Origine, $tabParams); 

}

function resendConfirmationMail($Login, $Email,$Origine)
{
	global $GAME_NAME,$SERVER_URL,$FROM_FIELD,$REPLY_TO_FIELD;
	global $REGISTRATION_CONFIRM,$REGISTRATION_CONFIRM_PAGE;
	
		#ici on envoie un mail de confirmation d'inscription
		$subject="Bienvenue sur ".$GAME_NAME." !";

		$msg = loadTemplate("Mailing/template_confirm_registration.html");
				
		$url_confirm = $REGISTRATION_CONFIRM_PAGE."?l=".$Login."&k=".encryptePassword($Origine."_".$Login);
		
//		$msg = replaceTag("__FULLNAME__", stripslashes($tabParams[FirstName]." ".$tabParams[Name]), $msg);
		$msg = replaceTag("__LOGIN__", $Login, $msg);
		$msg = replaceTag("__PASSWORD__", "Vous seul le connaissez", $msg);
		$msg = replaceTag("__URL_CONFIRM__", $url_confirm, $msg);
		$msg = replaceTag("__GAMEURL__", $SERVER_URL, $msg);
	
		generic_mail($Email, $subject, $msg,
				"From: ".$GAME_NAME." <".$FROM_FIELD.">\n" . 
				"Reply-To: $FROM_FIELD\n" . 
				"X-Mailer: PHP/" . phpversion()."\n".
				"MIME-Version: 1.0\n".
				"Content-Type: text/html; charset=iso-8859-1"."\n"
		);

		

		

}

#####################################
# MAIN
#####################################

if (isset($Vip))
{
	# on recherche dans la base locale si le vip existe
	$unmember = getMemberFromVip($Vip);

	if (!$unmember)
	{
		$Time		=	date("Y-m-d H:i:s", my_local_time());
		$IP			=	$REMOTE_ADDR;
		$Host		=	$HTTP_HOST;
		$Browser	=	$HTTP_USER_AGENT;
		if( $REGISTRATION_CONFIRM == true )
			$Confirme = 0;
		else
			$Confirme = 1;

		foreach( $TABPARAMS_MEMBER_CLASS as $propriete )
			$tabParamsMember[$propriete]=$$propriete;

		# on crée l'objet membre
		$oMembre = creationMembre($Login, $Email, $Password, $Vip, $Origine, $tabParamsMember);

		# on créer le membre en BDD
		$member = $oMembre->createInDB();
		
		if ($member)
		{
			$Time			=	date("Y-m-d H:i:s", my_local_time());
			$LastConnect	=	date("Y-m-d H:i:s", my_local_time());
			$cguValid		=	1;
			$Offsprings=$GrandSons=$GrandGrandSons=$Rank=0;
			$Score=$Parties=$SonsPoints=$TourScore=$CreditsDepenses=0;
			$CreditsAchetes=$Gain=$EquipeId=$AffichEquipe=$GratisDepenses=0;
			$Score=$KF=$NB_PTS_INSCRIPTION;
			
			foreach( $TABPARAMS_PLAYER_CLASS as $propriete )
				$tabParamsPlayer[$propriete]=$$propriete;

			# vérifie si le pseudo est déjà utilisé
			$oncePseudo = isNickExists($NickName);
			if (($oncePseudo) and ( $oncePseudo['MemberId'] != $member['Id'] ) )
			{
				$NickExist = 1;
			}
			else
			{
				$NickExist = 0;
				$oPlayer = new Joueur($NickName, $member['Id'],$tabParamsPlayer);
				$player = $oPlayer->createInDB();
				$oPlayer->updatePlayerAscending(false);
				# s'il a été parrainé
				$GuestId = $sess->guestid;
				if ($GuestId != "")
				{
					# si c'est le cas, on récupère le fatherPId
					$father = getFatherFromGuest($GuestId);
					if ($father['Id'] > 0)
					{
						# met à jour l'enregistrement de la table des Guests
						updateGuest($GuestId, $member['Id']);
						
						# met à jour les ascendant du player
						$oPlayer->updatePlayerAscending($father);
						
						# On ajoute un 100KF au parrain (on ne peut obtenir que 10 fois ce bonus)
						if($father['KFOfferts'] < (10*100))
							main_db_query("UPDATE Players SET KFOfferts=KFOfferts+100,KF=KF+100 WHERE Id=".$father['Id']);
						
						# On ajoute un ticket par filleul
					  	//addticket2histo($father['Id'],$TICKET_RAISON["FILLEUL"],$TICKET_NB["FILLEUL"]);
						
						$query = "SELECT * FROM PlayerOptions WHERE PlayerId='".$father[Id]."' ORDER BY OptionName DESC";
						$player_options_rows=db_fetch_row(main_db_query($query));

						$player_option_rows=main_db_query("INSERT INTO PlayerOptions (PlayerId,OptionName,Value) VALUES ('".$father['Id']."',".($player_options_rows[1]+1).",'".$player['Id']."')");
						$player_option_rows=main_db_query("INSERT INTO PlayerOptions (PlayerId,OptionName,Value) VALUES ('".$player['Id']."',1,'".$father['Id']."')");
					}
					else
						$oPlayer->updatePlayerAscending(false);
				}
				else
					$oPlayer->updatePlayerAscending(false);
				
				$player_option_rows=main_db_query("INSERT INTO PlayerOptions (PlayerId,OptionName,Value) VALUES ('".$player['Id']."',0,'".$player['Id']."')");
			}
		}
		else
		{	
			# il y a eu un pb on n'a pas pu créer le joueur, il faut
			# router vers une page d'erreur
			errorPage(array($Email, $Password, $Vip, $Origine, $date, $REMOTE_ADDR, $HTTP_HOST, $HTTP_USER_AGENT, $Gender, $Name, $FirstName, $Age, $Address, $Zip, $Town, $Telephone, $tabParams));
			exit();
		}

	}

	$sess->memberid = $member['Id'];
	$sess->save();

	if( $NickExist == 1 )
		{	
			# il y a eu un pb on n'a pas pu créer le joueur, il faut
			# router vers une page d'erreur
			errorPage(array($Email, $Password, $Vip, $Origine, $date, $REMOTE_ADDR, $HTTP_HOST, $HTTP_USER_AGENT, $Gender, $Name, $FirstName, $Age, $Address, $Zip, $Town, $Telephone, $tabParams));
			exit();
		}
	
	if( $REGISTRATION_CONFIRM == true)
	{
		$sess->memberid = -1;
		$sess->save();
		//$sess->redirect($CLOSING_REGISTRATION_PAGE, "Email=".$Email."&NickName=".$Login);
		$sess->redirect($COREG_REGISTRATION_PAGE, "ref=".$member['Id']);
		
	}


}
else
{

	include("config.php3");
	include($BIB."bib_generic.php3");
	include($BIB."bib_check_members.php3");
	include($BIB."bib_mailing.php3");

	$sess = open_page($sessid);
	if( $go )
	{
		include($BIB.$ORIGINE."_bib_check_members_vip.php3");
		
		$row = checkmember($Login, $Password);

		switch($row['Id'])
		{
			case -1:
				# il n'existe pas chez le partenaire
				header("Location:".$LOGIN_PAGE."?errorLogin=".urlencode("Identifiant ou mot de passe incorrect !"));
				exit();
			case 0:
				# il existe chez le partenaire mais pas en local
				$Login		=	$Login;
				$Email		=	$row['Email'];
				$Origine	=	$ORIGINE;
				# # # création d'un VIP Unique 
				$Vip		=	getUVip( $Login , $Origine);

				$Gender		=	$row['Gender'];
				$Name		=	$row['Name'];
				$FirstName	=	$row['FirstName'];
				$Age		=	$row['Age'];
				$Address	=	$row['Address'];
				$Zip		=	$row['Zip'];
				$Town		=	$row['Town'];
				$Country	=	$row['Country'];

				if( $REGISTRATION_CONFIRM == true )
					$Confirme = 0;
				else
					$Confirme = 1;

				$Time		=	date("Y-m-d H:i:s", my_local_time());
				$IP			=	$REMOTE_ADDR;
				$Host		=	$HTTP_HOST;
				$Browser	=	$HTTP_USER_AGENT;
				
				# # création du nouveau member
				# # # récupération du GuestId en cas de parainnage
				$guestid = $HTTP_COOKIE_VARS['GuestId'];
	
				# # # on ajoute le nouveau membre en base locale
				foreach( $TABPARAMS_MEMBER_CLASS as $propriete )
					$tabParams[$propriete]=$$propriete;

				# on crée l'objet membre
				$oMembre = creationMembre($Login, $Email, $Password, $Vip, $Origine, $tabParams);

				# on créer le membre en BDD
				$member = $oMembre->createInDB();

				# # sauvegarde du MemberId dans la session

				$sess->memberid = $member['Id'];
				$sess->origine = $ORIGINE;	
				$sess->save();	

			break;
			default:
				
				//Si le compte n'est pas confimé on rebalance un email
				if( $row['Confirme'] == 0 )
				{
					resendConfirmationMail($Login, $row['Email'],$ORIGINE);
					$sess->memberid = -1;
					$sess->origine = $ORIGINE;	
					$sess->save();
					$sess->redirect($CLOSING_REGISTRATION_PAGE,"Email=".$row[Email]."&NickName=".$Login);
				}
				//Compte confirmé
				else
				{
					$sess->memberid = $row['Id'];
					$sess->origine = $ORIGINE;	
					$sess->save();
				}
		}
	}
}

if ($sess->memberid == -1)
	$sess->redirect($LOGIN_PAGE, "");
	
$player = getplayer($sess->memberid);
$member = getmember($sess->memberid);

# Connection chez le partenaire
trace_partenaire();

# on autorise qu'une seule session par joueur
$sess->clear_similar_sessions();

# on indique la date de dernière connexion
setLastConnect($player['Id']);

#Si le membre n'a jamais validé le formulaire de coregistration, on lui présente, sinon on va directement à la page d'accueil
if($member['coregOk']==0){
	$sess->redirect($SERVER_URL."login_box-2.core.php3", "");
}else{
	$sess->redirect($MEMBER_PAGE,"");	
}

?>