<?php
/* return user's results */

//reconnection in case of session time out
if(!checkOrigin('qcmReader', array('qcm'=>$_POST['qcm'])) || !isset($_POST['user']))
{
	relocate(getError('Vous devez r&eacute;pondre &agrave; un QCM pour acc&eacute;der &agrave; &agrave; la page de r&eacute;sultats'));
}
else
{
	//reconnect session
	setSession($_POST['user']);
	
	//input Qcm data
	$iQcmId = $_POST['qcm'];
	$asQcm = getQcm($iQcmId);
	$sQcmName = $asQcm[QCM_TABLE];
	
	//display QCM results
	$iNbRightAnswers = 0;
	$iNbQuestions = getNbQuestions($iQcmId);
	foreach($asQcm[QUESTION_TABLE] as $iQuestionId => $asQuestion)
	{
		$bAnswerUserResult = true;
		$asDisplayRightResults = $asDisplayUserResults = '';
		$asDisplayResults[$iQuestionId] = '<tr><td>'.$asQuestion[QUESTION_TABLE].'</td>';
		foreach($asQuestion[ANSWER_TABLE] as $iAnswerId => $asAnswer)
		{
			$bUserAnswer = isset($_POST[QUESTION_TABLE.$iQuestionId.ANSWER_TABLE.$iAnswerId.RIGHT_ANSWER.$iAnswerId]);
			$bRightAnswer = ($asAnswer[RIGHT_ANSWER] == '1'); 
			$bAnswerUserResult = ($bAnswerUserResult && $bUserAnswer==$bRightAnswer);
			$asDisplayRightResults .= $asAnswer[RIGHT_ANSWER]?'<p>&bull; '.$asAnswer[ANSWER_TABLE].'</p>':'' ;
			$asDisplayUserResults .= $bUserAnswer?'<p>&bull; '.$asAnswer[ANSWER_TABLE].'</p>':'' ;
			
		}
		$asDisplayResults[$iQuestionId] .= '<td class="left">'.$asDisplayRightResults.'</td><td class="left">'.$asDisplayUserResults.'</td>';
		if($bAnswerUserResult)
		{
			$asDisplayResults[$iQuestionId] .= "<td class=\"true\">Vrai</td>";			
			$iNbRightAnswers++;
		}
		else
		{
			$asDisplayResults[$iQuestionId] .= "<td class=\"false\">Faux</td>";
		}
		$asDisplayResults[$iQuestionId] .= '</tr>';
	}

	//Update results table
	$sUpdateResult = '';
	$bplayed = checkPreviousResults($_SESSION['user'], $iQcmId);
	if($bplayed)
	{
		$sUpdateResult = '(Votre note n\'a pas &eacute;t&eacute; enregistr&eacute;e)';
	}
	else
	{
		addResult($_SESSION['user'], $iQcmId, $iNbRightAnswers/$iNbQuestions);
		addFeed('CREATE', $_SESSION['firstName'].' '.$_SESSION['lastName'], RESULT_TABLE, getTextFromId(QCM_TABLE, $iQcmId));
	}
}
?>
<table>
	<tr>
		<th colspan="4" class="rounded"><p class="tresimportant"><?php echo $sQcmName; ?> - R&eacute;sultats</p></th>
	</tr>
	<tr><td class="blank"></td></tr>
	<tr>
		<th class="top-left-rounded" width="40%"><p>Question</p></th>
		<th width="25%"><p>Bonnes r&eacute;ponses</p></th>
		<th width="25%"><p>Vos r&eacute;ponses</p></th>
		<th width="10%" class="top-right-rounded"><p>Votre r&eacute;sultat</p></th>
	</tr>
	<?php echo implode("\n", $asDisplayResults); ?>
	<tr>
		<td colspan="4" class="bottom-left-rounded bottom-right-rounded">
			<p class="tresimportant"><?php echo ucwords($_SESSION['firstName'].' '.$_SESSION['lastName']).', votre note : '.round($iNbRightAnswers/$iNbQuestions*20, 2).'/20'; ?></p>
			<p><?php echo $sUpdateResult; ?></p>
		</td>
	</tr>
</table>