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


################################
# SQL FUNCTIONS
################################
function selectMotionTypesAnswers($questionId)
{
	return main_db_query("SELECT * FROM QMotionTypesAnswers WHERE MotionId='".$questionId."'");
}

function countMotionTypesAnswers($motionId)
{
	return db_fetch_array(main_db_query("SELECT count(*) AS Total FROM QMotionTypesAnswers WHERE MotionId='".$motionId."'"));
}

function insertMotionTypesAnswers ($reponses, $motionId, $gain)
{
	main_db_query ("INSERT INTO QMotionTypesAnswers (Answer, MotionId, Price) VALUES ('".$reponses."', '".$motionId."', '".$gain."')");
}

function deleteMotionTypesAnswers($questionId)
{
	main_db_query("DELETE FROM QMotionTypesAnswers WHERE MotionId='".$questionId."'");
}

function selectMotionsByCategory($categoryId)
{
	return main_db_query("SELECT MotionId FROM QMotions WHERE Category='".$categoryId."'");
}

function selectMotionsByCategory2($categoryId)
{
	return main_db_query("SELECT * FROM QMotions WHERE Category='".$categoryId."' ORDER BY Type ASC, MotionId ASC");
}

function selectMotionsByMotionId($questionId)
{
	return main_db_query("SELECT MotionId FROM QMotions WHERE MotionId='".$questionId."' LIMIT 0,1");
}

function selectMotionsByMotionId2($questionId)
{
	return db_fetch_array ( main_db_query("SELECT * FROM QMotions WHERE MotionId='".$questionId."'"));
}

function getMotion($category, $question, $type)
{
	return db_fetch_array ( main_db_query("SELECT MotionId FROM QMotions WHERE ".
			"Category = '".$category."' AND Title='".$question."' AND Type = '".$type."'"));
}

function deleteMotionByMotionId($questionId)
{
	main_db_query("DELETE FROM QMotions WHERE MotionId='".$questionId."'");
}

function deleteMotion($category, $question, $type)
{
	main_db_query ("DELETE FROM QMotions WHERE Category = '".$category."' AND Title='".$question."' AND Type = '".$type."'");
}

function updateMotion($category, $question, $type, $questionId)
{
	main_db_query("UPDATE QMotions Set Category='".$category."', Title='".$question."', Type='".$type."' WHERE MotionId='".$questionId."'");
}

function insertMotion($category, $question, $type, $questionId)
{
	main_db_query ("INSERT INTO QMotions (MotionId, Category, Title, Type) VALUES ('".$questionId."', '".$category."', '".$question."', '".$type."')");
}

function insertMotion2($category, $question, $type)
{
	main_db_query ("INSERT INTO QMotions (Category, Title, Type) VALUES ('".$category."', '".$question."', '".$type."')");
}

function getCategory($CategoryId)
{
	return db_fetch_array ( main_db_query ("SELECT * FROM QCategories WHERE CategoryId='".$CategoryId."'"));
}

function selectCategoriesByTime($ShowTime, $EndTime)
{
	return main_db_query ("SELECT * FROM QCategories WHERE ShowTime>='".$ShowTime."' AND EndTime<='".$EndTime."'");
}

function selectCategoriesByTime2($aDate)
{
	return main_db_query ("SELECT * FROM QCategories WHERE ShowTime<='".$aDate."' AND EndTime>='".$aDate."'");
}

function insertCategory($Container, $Name, $EndTime, $ShowTime)
{
	main_db_query ("INSERT INTO QCategories (Container, Name, Endtime, ShowTime) VALUES ('".$Container."', '".$Name."', '".$EndTime."', '".$ShowTime."')");
}

function deleteCategory($CategoryId)
{
	main_db_query ("DELETE FROM QCategories WHERE CategoryId='".$CategoryId."'");
}
################################

#################################
#         functions             #
#################################

/* insere une question et ses réponses dans la BDD */
/*
$question: chaine de caractères de la question (ex: "comment vas tu?")
$reponses: tableau de chaines de caractères des réponses possibles
avec la bonne réponse en première position
(ex: ("bien","mal","je ne sais pas") )
$type: integer, type de la question ( 1, 2, 3 ou 4)
$category: integer, représente le pack auquel la question appartient
*/

function delete_question($questionId)
{
	deleteMotionTypesAnswers($questionId);
	deleteMotionByMotionId($questionId);
}

function delete_categorie($categoryId)
{
	$Motions = selectMotionsByCategory($categoryId);
	while ($Motion = db_fetch_array($Motions))
		delete_question($Motion['MotionId']);
	
	deleteCategory($categoryId);
}


function insere_question($question, $reponses, $nbReponses, $numBonneReponse, $type, $category, $questionId=0)
{
	global $LAST_MOTION_TYPE;

	// on ajoute des slashes pour invalider les éventuels caractères
	// spéciaux dans la question
	$question = AddSlashes ($question);
	
	// on vérifie qu'une question de même type et de même catégorie
	// n'a pas déjà été entrée dans la table
	// Non : l'unicité du type n'est plus garantie
	
	if (false)
	{
		// dans ce cas, on mets à jour la table avec la nouvelle question
		deleteMotion($category, $question, $type);
	}
	else
	{
		if ($questionId > 0)
		{
			$PrevRows = selectMotionsByMotionId($questionId);
			if (db_num_rows($PrevRows) > 0)
				updateMotion($category, $question, $type, $questionId);				
			else
				insertMotion($category, $question, $type, $questionId);
				
			$motionId = $questionId;
		}
		else
		{
			// insertion de la question dans la table des motions
			insertMotion2($category, $question, $type);

			// récupération de l'id de la motion que l'on vient d'insérer
			$motionIdRow = getMotion($category, $question, $type);
			$motionId =  $motionIdRow[MotionId];
		}
	}
	// définition de la valeur des bonnes et des mauvaises réponses en fonction
	// du type de la question
	switch ($type)
	{
		case $LAST_MOTION_TYPE:
			$gain = 2;
			$perte = 0;
			break;
		default:
			$gain = 1;
			$perte = 0;
			break;
	}
	
	// on supprime les éventuelles réponses déjà associées à cette motion
	deleteMotionTypesAnswers($motionId);
	
	// insertion des réponses
	for ($i=0;$i<$nbReponses;$i++)
	{
		$reponses[$i] = AddSlashes($reponses[$i]);
		if ($i == $numBonneReponse)
		{
			// insertion de la bonne réponse
			insertMotionTypesAnswers ($reponses[$i], $motionId, $gain);
		}
		else
		{
			// insertion d'une mauvaise réponse
			insertMotionTypesAnswers ($reponses[$i], $motionId, $perte);
		}
	}
}


function addQuestions($CategoryId, $fileName)
{
	global $NB_QUESTIONS_FIRST_TYPE, $FIRST_MOTION_TYPE, $SECOND_MOTION_TYPE, $SUBSIDIAIRE_TYPE, $NB_QUESTIONS_LAST_TYPE;
	global $NB_QUESTIONS;
	
	$type = $FIRST_MOTION_TYPE;
	$NB_REPONSES_SUBSIDIAIRES = 6;

	if ($CategoryId <= 0)
		return 0;
	
	// on vire les questions qui existent
	$Motions = selectMotionsByCategory($CategoryId);
	while ($Motion = db_fetch_array($Motions))
		delete_question($Motion['MotionId']);
	
	// on lit le fichier contenant les questions et les réponses dans un tableau


//	$tab = file (stripslashes($fileName));
	$tab = file ($fileName);
	
	$imax = sizeof ($tab);
	$question="";
	$NouvelleCategorie=1;
	$numCategorie=0;
	echo "Le fichier contient ".$imax." lignes.<br>";
	// on examine les lignes du fichier une par un<e

	$Nb_Question = 0;
	for ($i=0;$i<$imax;$i++)
	{
		flush();
		$tab[$i] = trim($tab[$i]);
		
		// la question n'est pas encore définie, donc la ligne
		// en cours contient la question
		if ($question=="")
		{
			$question = eregi_replace("\r\n","",$tab[$i]);
			echo "Ajout de la question ".($Nb_Question+1).": ".$question."<br>";
			$nbReponses=0;
		}
		// si la question est définie et que la ligne en
		// cours n'est pas vide, c'est qu'elle contient une réponse
		elseif (($tab[$i]!="\r\n") && ($tab[$i]!="\r") && ($tab[$i]!="\n") && ($tab[$i]!=""))
		{
			// on teste si il s'agit de la bonne réponse à la question
			if (ereg("\*",$tab[$i]))
			{
				$tab[$i] = ereg_replace("\*","",$tab[$i]);
				$numBonneReponse = $nbReponses;
			}
			
			// on insère cette réponse dans le tableau des réponses
			$reponses[$nbReponses] = eregi_replace("\r\n","",$tab[$i]);
			echo "Reponse ".($nbReponses+1)." : ".$reponses[$nbReponses]."<br>";
			$nbReponses++;
		}
		// la ligne en cours est vide, on viens donc de finir de lire une
		// question avec ses réponses, on rentre cette Motion dans la BDD
		else
		{
			echo "Cette question est complète. On l'insère.<br>";

			if ($nbReponses >= $NB_REPONSES_SUBSIDIAIRES)
				$type = $SUBSIDIAIRE_TYPE;
			insere_question ($question, $reponses, $nbReponses, $numBonneReponse, $type, $CategoryId);
			$Nb_Question++;
			$question = "";

			// update du type :
/*			if ($Nb_Question >= $NB_QUESTIONS)
				$type = $SUBSIDIAIRE_TYPE;*/
			if ($Nb_Question >= $NB_QUESTIONS_FIRST_TYPE)
				$type = $SECOND_MOTION_TYPE;
			else
				$type = $FIRST_MOTION_TYPE;
		}
	}
	// et la dernière question :
	$type = $SUBSIDIAIRE_TYPE;
	if (($question != "") && ($nbReponses > 0) && ($numBonneReponse > 0) && ($numBonneReponse <= $nbReponses))
	{
		echo "Cette (dernière) question est complète. On l'insère.<br>";
		insere_question ($question, $reponses, $nbReponses, $numBonneReponse, $type, $CategoryId);
	}
}


#################################
#        end functions          #
#################################

?>

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

<?php
if ($submit=="Valider")
{
	for ($i = 0; $i < $NbReponses;$i++)
	{
		$CurReponse = "Reponse".$i;
		echo $CurReponse." : ".$$CurReponse."<br>";
		$Reponses[$i] = $$CurReponse;
	}

	$ContainerName = $container[Name];

	// on regarde s'il y a déjà une question
	$Categories = selectCategoriesByTime($ShowTime, $EndTime);
	if (db_num_rows($Categories) == 0)
	{
		echo "<font color=#FF0000>Il n'y a pas de catégorie pour cette Semaine, on l'ajoute</font><br>";
		insertCategory($ContainerId, $ContainerName.$ShowTime, $EndTime, $ShowTime);
		$Categories = selectCategoriesByTime($ShowTime, $EndTime);
	}
	
	$Category = db_fetch_array($Categories);
	$CategoryId = $Category['CategoryId'];
	if (($Question != "") && ($NbReponses>0) && ($NbReponses <= count($Reponses)) && ($BonneReponse >=0) && ($BonneReponse <=count($Reponses)))
	{
		insere_question ($Question, $Reponses, $NbReponses, $BonneReponse, $Type, $CategoryId, $QuestionId);
	}
	else
	{
		echo "Missing : ".$Question.", ".$NbReponses.", ".count($Reponses).", ".$BonneReponse.".<br>";
	}
}
elseif ($submit == "Supprimer")
{
	delete_question($QuestionId);
}
elseif ($submit == "Infos")
{
	if ($Motion = selectMotionsByMotionId2($QuestionId))
	{
		$Question = $Motion['Title'];
		$Type = $Motion['Type'];
		$Reponses = selectMotionTypesAnswers($QuestionId);
		$NbReponses = 0;
		while ($Reponse = db_fetch_array($Reponses))
		{
			$CurReponseVar = "Reponse".$NbReponses;
			$$CurReponseVar = $Reponse['Answer'];
			if ($Reponse['Price']>0)
			{
				$BonneReponse = $NbReponses;
			}
			$NbReponses++;
		}
	}
}
elseif ($submit == "Ajouter")
{
	echo "Ajout de questions à la catégorie ".$CategoryId." à partir d'un fichier <br>";
	if (($CategoryId > 0) && ($fileName != ""))
	{
		addQuestions($CategoryId, $fileName);
	}
	else
	{
		echo "Elément manquant<br>";
	}
	unlink($fileName);
}
else
{
	$NbReponses = 3;

	if ($CategoryId > 0)
	{
		$CategoryRow = getCategory($CategoryId);
		$Categorydate = $CategoryRow['ShowTime'];
		$ShowTime = $CategoryRow[ShowTime];
		$EndTime = $CategoryRow[EndTime];
	}
	elseif ($CategoryDate != "")
	{
		$CategoryRow = selectCategoriesByTime2($CategoryDate);
		$CategoryId = $CurCategory['CategoryId'];
		$ShowTime = $CategoryRow[ShowTime];
		$EndTime = $CategoryRow[EndTime];
	}
	else
	{	
		if ($ShowTime == "")
			$ShowTime = "2001-08-15 12:00:00";
		if ($EndTime == "")
			$EndTime = "2001-08-15 12:00:00";
	}
}

?>

<div class=universBold>Choix d'une Semaine</div>
<br>
<form method="post" >
Afficher ci-dessous les question de la Semaine ...
<table border=0>
<tr>
	<td >Numéro :</td>
	<td><input type="text" name="CategoryId" size=5 value="<?php echo $CategoryId ?>"></td>
</tr>
<tr>
	<td >ou se déroulant le :</td>
	<td><input type="text" name="CategoryDate" value="<?php echo $CategoryDate ?>"> AAAA-MM-JJ HH:MM:SS (mettre une date incluse dans la Semaine)</td>
</tr>
</table>
<br>
<input type=submit name=submit value="rafraichir">&nbsp;Cliquez pour rafraîchir la liste ci-dessous
<br>
<br>
<hr>
<?php if ($CategoryId > 0)
{
	$CurCategory = getCategory($CategoryId);
	$Categorydate = $CurCategory['ShowTime'];
}
elseif ($CategoryDate != "")
{
	$CurCategory = selectCategoriesByTime2($CategoryDate);
	$CategoryId = $CurCategory['CategoryId'];
}


if ($CategoryId > 0)
{
echo "<div class=universBold>Liste des Question de la Semaine ".$CategoryId." (de ".$CurCategory[ShowTime]." à ".$CurCategory[EndTime].")</div>";
?>
<br>
<table border=1>
	<tr class=trTitle>
		<td>N° (Id)</td>
		<td>Question</td>
		<td>Nb<br>rép.</td>
		<td align=center>Type</td>	
	</tr>
<?php
$CurMotions = selectMotionsByCategory2($CategoryId);
while($CurMotion=db_fetch_array($CurMotions))
{
	$NbReponses = countMotionTypesAnswers($CurMotion[MotionId]);
	echo "<tr>";
		echo "<td>$CurMotion[MotionId]</td>";
		echo "<td>";
		if (($NbReponses[Total] < 3) && (($CurMotion[Type] == $FIRST_MOTION_TYPE) || ($CurMotion[Type] == $SECOND_MOTION_TYPE)))
			echo "<font color=#FF0000>".$CurMotion[Title]."</font>";
		else
			echo $CurMotion[Title];
		echo "</td>";
		echo "<td>".$NbReponses[Total]."</td>";
	switch ($CurMotion[Type])
	{
		case $FIRST_MOTION_TYPE :
			echo "<td>Première</td>";
			break;
		case $SECOND_MOTION_TYPE :
			echo "<td>Aléatoire</td>";
			break;
		default :
			echo "<td>Subsidiaire</td>";
			break;
	}
	echo "</tr>";
}
echo "</table>";
}
?>

<!--<form method="post" ENCTYPE="multipart/form-data">-->
<br>
<hr>
<div class=universBold>Edition d'une question</div>
<br>
<input type="hidden" name="ContainerId" value="1">
<table border=0>
	<tr height=40>
		<td>
			Numéro de la question :
		</td>
		<td>
			<input type="text" name="QuestionId" value="<?php echo $QuestionId?>">&nbsp;(C'est la 1ère colonne. Mettre 0 ou rien pour ajouter une question)
		</td>
	</tr>
	<tr height=40>
		<td>
			Texte de la question : 
		</td>
		<td>
			<input type="text" name="Question" value="<?php echo $Question?>" size="50">
		</td>
	</tr>
	<tr height=40>
		<td>
			Type de la question : 
		</td>
		<td>
			<select name=Type>
				<option <?php if ($Type==$FIRST_MOTION_TYPE) echo "selected"?> value="<?php echo $FIRST_MOTION_TYPE?>">première
				<option <?php if ($Type==$SECOND_MOTION_TYPE) echo "selected"?> value="<?php echo $SECOND_MOTION_TYPE?>">Aléatoire
				<option <?php if ($Type==$SUBSIDIAIRE_TYPE) echo "selected"?> value="<?php echo $SUBSIDIAIRE_TYPE?>">Bonus
			</select>
		</td>
	</tr>
	<tr>
		<td>
			Date de début d'affichage :
		</td>
		<td>
			<input type="text" name="ShowTime" value="<?php echo $ShowTime ?>"> AAAA-MM-JJ HH:MM:SS
		</td>
	</tr>
	<tr>
		<td>
			Date de fin d'affichage :
		</td>
		<td>
			<input type="text" name="EndTime" value="<?php echo $EndTime ?>"> AAAA-MM-JJ HH:MM:SS
		</td>
	</tr>
	<tr height=40>
		<td>
			Nombre de réponses possibles :
		</td>
		<td>
			<select name=NbReponses>
				<?php
					for ($i=1 ; $i <= $NB_MAX_REPONSES ; $i++)
					{
						if ($i == $NbReponses)
							echo "<option selected value=".$i.">".$i;
						else
							echo "<option value=".$i.">".$i;
					}
				?>
			</select>
		</td>
	</tr>
<?php
echo "Bonne réponse : ".$BonneReponse."<br>";
for ($i = 0; $i < $NB_MAX_REPONSES ; $i++)
{
	echo "<tr><td>Réponse ".($i+1)." : </td>\n";
	$CurReponse = "Reponse".$i;
	echo "<td><input size=40 type=\"text\" name=\"Reponse".$i."\" value=\"".$$CurReponse."\">";

	echo "&nbsp;<input type=\"radio\" name=\"BonneReponse\" value=\"".$i."\"";
	if ($BonneReponse == $i)
		echo " checked";
	echo ">C'est la bonne réponse</td>\n";
	echo "</tr>\n";
}
?>
</table>
<br>
<input type=submit name=submit value="Infos">&nbsp;
<input type=submit name=submit value="Valider">&nbsp;
<input type=submit name=submit value="Supprimer"><br>
</form>
<a class=under href="<?php echo $PHP_SELF ?>">Rafraichir la page</a>
</body>
</html>