<?php
$nombreQuestions = 0;
$score = 0;
$questionsTraitees = 0;
$message = 'Aucun resultat a afficher.';
$resultatsParQuestion = [];

$nombreQuestionsSaisi = filter_input(INPUT_POST, 'nbq', FILTER_VALIDATE_INT);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $nombreQuestionsSaisi !== false && $nombreQuestionsSaisi !== null) {
    $nombreQuestions = $nombreQuestionsSaisi;
    $message = '';

    for ($index = 1; $index <= $nombreQuestions; $index++) {
        $reponse = filter_input(INPUT_POST, 'question' . $index, FILTER_UNSAFE_RAW);

        if ($reponse !== null) {
            $questionsTraitees++;
        }

        if ($reponse === 'vrai') {
            $score++;
            $resultatsParQuestion[] = [
                'numero' => $index,
                'classe' => 'bonne-reponse',
                'message' => 'Bonne reponse',
            ];
        } else {
            $resultatsParQuestion[] = [
                'numero' => $index,
                'classe' => 'mauvaise-reponse',
                'message' => 'Mauvaise reponse',
            ];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
    <head>
        <link rel="stylesheet" href="./css/style.css">
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.classless.min.css"
        />
        <meta charset="UTF-8" />
        <title>Exercice 4</title>
    </head>
    <body>
        <main>
            <h4>Resultat du quizz</h4>
            <?php if ($message !== '') : ?>
                <p><?php echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); ?></p>
            <?php else : ?>
                <p>
                    Vous avez obtenu
                    <?php echo htmlspecialchars((string) $score, ENT_QUOTES, 'UTF-8'); ?>
                    bonne(s) reponse(s) sur
                    <?php echo htmlspecialchars((string) $nombreQuestions, ENT_QUOTES, 'UTF-8'); ?>.
                </p>
                <p>
                    Questions repondues :
                    <?php echo htmlspecialchars((string) $questionsTraitees, ENT_QUOTES, 'UTF-8'); ?>.
                </p>
                <ul>
                    <?php foreach ($resultatsParQuestion as $resultatQuestion) : ?>
                        <li>
                            Question <?php echo htmlspecialchars((string) $resultatQuestion['numero'], ENT_QUOTES, 'UTF-8'); ?> :
                            <span class="<?php echo htmlspecialchars($resultatQuestion['classe'], ENT_QUOTES, 'UTF-8'); ?>">
                                <?php echo htmlspecialchars($resultatQuestion['message'], ENT_QUOTES, 'UTF-8'); ?>
                            </span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
            <p>
                <a href="quizz.html">Revenir au quizz</a>
            </p>
        </main>
    </body>
</html>
