<?php

//learn_exam.inc.php
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="container my-5">
    <h2>Exam</h2>
    <form id="examForm">
        <?php foreach($questions as $i => $q): ?>
            <div class="card mb-3">
                <div class="card-body">
                    <p><strong>Q<?= $i+1 ?>. <?= htmlspecialchars($q['question']) ?></strong></p>
                    <?php
                        $options = [
                                1 => 'option1',
                                2 => 'option2',
                                3 => 'option3',
                                4 => 'option4'
                            ];

            foreach($options as $value => $col):
                    if(empty($q[$col])) continue;
                ?>
                <div class="form-check">
                    <input class="form-check-input"
                        type="radio"
                        name="answer[<?= $q['id'] ?>]"
                        id="q<?= $q['id'] ?>_<?= $value ?>"
                        value="<?= $value ?>"
                        required>
                    <label class="form-check-label"
                        for="q<?= $q['id'] ?>_<?= $value ?>">
                        <?= htmlspecialchars($q[$col]) ?>
                    </label>
                </div>
                <?php endforeach; ?>

                </div>
            </div>
        <?php endforeach; ?>
        <button type="submit" class="btn btn-primary">Send</button>
    </form>

    <div id="result" class="mt-4"></div>
</div>

<script>
document.getElementById('examForm').addEventListener('submit', async function(e){
    e.preventDefault();

    let form = e.target;
    let answers = {};

    new FormData(form).forEach((value, key)=>{
        // key = "answer[1]" -> extraire id
        let match = key.match(/\[(\d+)\]/);
        if(match){
            answers[match[1]] = value;
        }
    });

    let payload = {
        formation_ref: "<?= $formation_ref ?>",
        answers: answers
    };

    let resDiv = document.getElementById('result');
    resDiv.innerHTML = 'Processing...';

    try{
        let resp = await fetch('learn_exam_submit.php', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body: JSON.stringify(payload)
        });

        let data = await resp.json();

        if(data.success){
            let html = `<p>Score: ${data.score}%</p>`;
            html += `<p>${data.passed ? "🎉 Congratulations, you success !" : "😔 Echec, please tray again"}</p>`;
           if(data.certificate_ref){
                html += `
                    <p>
                        <a href="certificate.php?ref=${data.certificate_ref}" target="_blank">
                            📄 Show certificat
                        </a>
                    </p>
                `;
            }

            resDiv.innerHTML = html;
        } else {
            resDiv.innerHTML = 'Erreur: '+(data.error || 'unknown');
        }
    }catch(err){
        resDiv.innerHTML = 'Erreur: '+err.message;
    }
});
</script>
