<?php
chdir('../');
session_start();
date_default_timezone_set('Africa/Lagos');
require_once('public/connection.php');

if (!isset($_SESSION['student_id'])) {
    header("Location: ../index.php");
    exit;
}

include('partials/exam_header.php');

$student_id = (int) $_SESSION['student_id'];
$exam_id = isset($_GET['exam_id']) ? (int) $_GET['exam_id'] : 0;
$Qtype_raw = $_GET['type'] ?? '';
$Qtype = in_array($Qtype_raw, ['mcq','theory','fill','theory']) ? $Qtype_raw : null;
if (!$exam_id || !$Qtype) {
    echo "<div class='alert alert-danger'>Invalid request.</div>";
    include('partials/footer.php');
    exit;
}

// Fetch student
$stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$student) {
    echo "<div class='alert alert-danger'>Student not found.</div>";
    include('partials/footer.php');
    exit;
}

// Fetch exam info
$exam_stmt = $conn->prepare("
    SELECT e.*, s.subjects AS subject_name 
    FROM exams e 
    LEFT JOIN school_subjects s ON e.subject_id = s.id 
    WHERE e.id = ?
");
$exam_stmt->bind_param("i", $exam_id);
$exam_stmt->execute();
$exam = $exam_stmt->get_result()->fetch_assoc();
$exam_stmt->close();

if (!$exam) {
    echo "<div class='alert alert-danger'>Invalid Exam</div>";
    include('partials/footer.php');
    exit;
}

// --- Calculate remaining seconds using DB (prevents timezone/clock drift issues)
$session_stmt = $conn->prepare("
    SELECT TIMESTAMPDIFF(SECOND, NOW(), end_time) AS remaining_seconds
    FROM student_exam_sessions
    WHERE student_id = ? AND exam_id = ? AND qtype = ?
    LIMIT 1
");
$session_stmt->bind_param("iis", $student_id, $exam_id, $Qtype);
$session_stmt->execute();
$session_res = $session_stmt->get_result();
$session_stmt->close();

$remaining_seconds = null;
if ($session_res && $session_res->num_rows > 0) {
    $row = $session_res->fetch_assoc();
    $remaining_seconds = (int)$row['remaining_seconds'];
    if ($remaining_seconds <= 0) {
        // time already elapsed
        echo "<script>
            alert('Time for this exam has already expired.');
            window.location.href='submit_exam.php?exam_id={$exam_id}&type={$Qtype}';
        </script>";
        exit;
    }
    // compute JS timestamp to use (client current time + remaining)
    $exam_end_timestamp = (time() + $remaining_seconds) * 1000;
} else {
    // start a new session
    if ($Qtype === 'theory') {
        $duration = (int)$exam['duration_minutes'];
    } else { // mcq or other types use duration_minutes2
        $duration = (int)$exam['duration_minutes2'];
    }
    if ($duration <= 0) $duration = 1; // fallback to 1 minute

    $start_time = date("Y-m-d H:i:s");
    $end_time = date("Y-m-d H:i:s", strtotime("+{$duration} minutes"));

    $insert = $conn->prepare("
        INSERT INTO student_exam_sessions (student_id, exam_id, qtype, start_time, end_time)
        VALUES (?, ?, ?, ?, ?)
    ");
    $insert->bind_param("iisss", $student_id, $exam_id, $Qtype, $start_time, $end_time);
    $insert->execute();
    $insert->close();

    // compute end timestamp in JS ms
    $exam_end_timestamp = strtotime($end_time) * 1000;
}

// Fetch and shuffle questions (prepared, safe)
$q_stmt = $conn->prepare("SELECT * FROM questions WHERE exam_id = ? AND question_type = ? ORDER BY RAND()");
$q_stmt->bind_param("is", $exam_id, $Qtype);
$q_stmt->execute();
$questions_result = $q_stmt->get_result();
$questionList = $questions_result ? $questions_result->fetch_all(MYSQLI_ASSOC) : [];
$q_stmt->close();

// Fetch instruction if any
$instruction = "";
if ($exam_id) {
    $inst = $conn->prepare("SELECT instruction FROM exam_instructions WHERE exam_id = ? LIMIT 1");
    $inst->bind_param("i", $exam_id);
    $inst->execute();
    $inst->bind_result($instruction);
    $inst->fetch();
    $inst->close();
}
?>
<!-- SweetAlert2 CDN (kept available but we are using custom modal here) -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    @media (min-width: 1080px) {
        .sidebar-sticky { position: sticky; top: 100px; }
    }

    /* Confirmation Modal (Option A) styling */
    .confirm-modal-backdrop {
        position: fixed;
        inset: 0;
        background: rgba(0,0,0,0.55);
        z-index: 2000;
        display: none;
        align-items: center;
        justify-content: center;
    }
    .confirm-modal {
        width: 100%;
        max-width: 560px;
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 12px 30px rgba(0,0,0,0.3);
        padding: 22px;
        transform: translateY(-10px);
        transition: all .18s ease;
    }
    .confirm-modal h4 {
        margin: 0 0 8px 0;
        font-weight: 700;
    }
    .confirm-modal p { margin-bottom: 12px; color: #333; }
    .confirm-modal .confirm-count {
        font-weight: 700;
        color: #111;
        margin-bottom: 10px;
    }
    .confirm-actions {
        display:flex;
        gap:12px;
        justify-content: flex-end;
        margin-top: 12px;
    }
    .btn-cancel {
        background: transparent;
        border: 1px solid #ddd;
        padding: 8px 14px;
        border-radius: 6px;
        cursor: pointer;
    }
    .btn-confirm {
        background: linear-gradient(90deg,#28a745,#218838);
        color: #fff;
        border: none;
        padding: 8px 14px;
        border-radius: 6px;
        cursor: pointer;
    }
    .btn-confirm[disabled] {
        opacity: 0.6;
        cursor: not-allowed;
    }
</style>

<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h4 class="m-0">
        Exam: <?= htmlspecialchars($exam['class']) ?> - <?= htmlspecialchars($exam['subject_name']) ?> - <?= ucfirst(htmlspecialchars($exam['exam_type'])) ?> - <?= htmlspecialchars($Qtype) ?>
      </h4>
    </div>
  </div>

  <?php if (!empty($instruction)): ?>
    <div class="modal fade" id="instructionModal" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Exam Instruction</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="$('#instructionModal').modal('hide')">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body"><?= nl2br(htmlspecialchars($instruction)) ?></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-bs-dismiss="modal" onclick="$('#instructionModal').modal('hide')">I Understand</button>
          </div>
        </div>
      </div>
    </div>

    <script>
      window.addEventListener('load', function () {
        $('#instructionModal').modal('show');
      });
    </script>
  <?php endif; ?>

  <div class="content">
    <div class="container-fluid">
      <div class="row">
        <!-- Main -->
        <div class="col-md-9">
          <div class="mb-4">
            <div class="d-flex align-items-center">
              <span id="timer" class="badge bg-danger fs-3 p-3"></span>
              <button type="button" class="btn btn-outline-dark ms-3" onclick="toggleCalculator()">Scientific Calculator</button>
            </div>
            <div id="malpracticeAlert" class="alert alert-warning py-1 px-2 mt-2 d-inline-block" style="display: none;">
              <span id="warningCount">0</span> Tab switch warning(s)
            </div>
          </div>

          <form method="post" action="submit_exam.php" id="examForm">
            <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
            <input type="hidden" name="Qtype" value="<?= htmlspecialchars($Qtype) ?>">

            <?php if (count($questionList) > 0): ?>
              <div class="d-flex flex-wrap mb-3">
                <?php foreach ($questionList as $i => $q): ?>
                  <button type="button" class="btn btn-sm me-2 mb-2 <?= $i === 0 ? 'btn-primary' : 'btn-outline-primary' ?> review-btn" data-index="<?= $i ?>">Q<?= $i + 1 ?></button>
                <?php endforeach; ?>
              </div>

              <div id="questionCards">
                <?php foreach ($questionList as $index => $q): ?>
                  <div class="card question-card mb-3" data-index="<?= $index ?>" data-qid="<?= (int)$q['id'] ?>" style="display: <?= $index === 0 ? 'block' : 'none' ?>;">
                    <div class="card-header"><strong>Question <?= $index + 1 ?>:</strong></div>
                    <div class="card-body">
                      <div class="row align-items-start">
                        <div class="col-md-9 col-12">
                          <p class="question-text"><?= nl2br(htmlspecialchars($q['question_text'])) ?></p>
                        </div>
                        <?php if (!empty($q['question_image'])): ?>
                          <div class="col-md-3 col-12 text-md-end text-center mt-2 mt-md-0">
                            <img src="../<?= htmlspecialchars($q['question_image']) ?>" class="img-fluid rounded border" style="max-height: 140px;">
                          </div>
                        <?php endif; ?>
                      </div>

                      <?php if ($q['question_type'] === 'mcq'): ?>
                        <?php foreach (['a','b','c','d'] as $opt): ?>
                          <?php if (!empty($q['option_'.$opt])): ?>
                            <div class="form-check">
                              <input class="form-check-input" type="radio" name="answers[<?= (int)$q['id'] ?>]" value="<?= $opt ?>" id="q<?= (int)$q['id'] ?>_<?= $opt ?>">
                              <label class="form-check-label question-text" for="q<?= (int)$q['id'] ?>_<?= $opt ?>"><?= htmlspecialchars($q['option_'.$opt]) ?></label>
                            </div>
                          <?php endif; ?>
                        <?php endforeach; ?>
                      <?php elseif ($q['question_type'] === 'theory'): ?>
                        <textarea class="form-control" name="answers[<?= (int)$q['id'] ?>]" rows="4"></textarea>
                      <?php elseif ($q['question_type'] === 'fill'): ?>
                        <input type="text" class="form-control" name="answers[<?= (int)$q['id'] ?>]">
                      <?php endif; ?>

                    </div>
                  </div>
                <?php endforeach; ?>
              </div>

              <div class="d-flex justify-content-between">
                <button type="button" id="prevBtn" class="btn btn-secondary">Previous</button>
                <button type="button" id="nextBtn" class="btn btn-primary">Next</button>
                <button type="submit" class="btn btn-success d-none" id="submitBtn">Submit Exam</button>
              </div>

            <?php else: ?>
              <div class="alert alert-info">No questions available for this exam.</div>
            <?php endif; ?>

          </form>
        </div>

        <!-- Sidebar -->
        <div class="col-md-3 mt-4 mt-md-0">
          <div class="card sidebar-sticky">
            <div class="card-body text-center">
              <img src="../../<?= htmlspecialchars($student['passport'] ?: 'uploads/students/none.jpg') ?>" class="rounded-circle border mb-2" width="80" height="80" alt="Passport">
              <h5 class="mb-0"><?= htmlspecialchars($student['firstname'] . ' ' . $student['lastname']) ?></h5>
              <small class="text-muted d-block mb-2">Class: <?= htmlspecialchars($student['class']) ?></small>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</div>

<!-- Confirmation Modal Markup (Option A) -->
<div id="confirmModalBackdrop" class="confirm-modal-backdrop" role="dialog" aria-hidden="true">
  <div class="confirm-modal" role="document" aria-labelledby="confirmModalTitle">
    <h4 id="confirmModalTitle">Confirm submission</h4>
    <div class="confirm-count" id="confirmCount">You have answered 0 out of 0 questions.</div>
    <p>Are you sure you want to submit now? You won't be able to change your answers after submission.</p>
    <div class="confirm-actions">
      <button type="button" id="confirmCancel" class="btn-cancel">Go back</button>
      <button type="button" id="confirmSubmit" class="btn-confirm">Submit now</button>
    </div>
  </div>
</div>

<!-- Calculator UI (unchanged behaviour) -->
<div id="calculatorBox" style="display:none; position:fixed; bottom:20px; right:20px; z-index:1050; background:#fff; padding:20px; border-radius:12px; box-shadow:0 0 15px rgba(0,0,0,0.2); width:300px;">
  <div class="d-flex justify-content-between align-items-center mb-2">
    <strong>Scientific Calculator</strong>
    <button class="btn btn-sm btn-danger" onclick="toggleCalculator()">Close</button>
  </div>
  <input type="text" id="calc-display" class="form-control mb-3 text-end" readonly style="font-size:18px; height:40px;">
  <div class="row g-1">
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('Math.PI')">PI</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('Math.E')">e</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('Math.log(')">log</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('/')">/</button></div>

    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('7')">7</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('8')">8</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('9')">9</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('*')">*</button></div>

    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('4')">4</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('5')">5</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('6')">6</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('-')">-</button></div>

    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('1')">1</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('2')">2</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('3')">3</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('+')">+</button></div>

    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('0')">0</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="pressCalc('.')">.</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="calculateResult()">=</button></div>
    <div class="col-3"><button class="btn btn-secondary w-100" onclick="clearCalc()">C</button></div>

    <div class="col-4 mt-2"><button class="btn btn-outline-primary w-100" onclick="pressCalc('Math.sin(')">sin</button></div>
    <div class="col-4 mt-2"><button class="btn btn-outline-primary w-100" onclick="pressCalc('Math.cos(')">cos</button></div>
    <div class="col-4 mt-2"><button class="btn btn-outline-primary w-100" onclick="pressCalc('Math.tan(')">tan</button></div>
    <div class="col-6 mt-2"><button class="btn btn-outline-primary w-100" onclick="pressCalc('Math.sqrt(')">Square</button></div>
    <div class="col-6 mt-2"><button class="btn btn-outline-warning w-100" onclick="pressCalc(')')">)</button></div>
  </div>
</div>

<!-- MathJax -->
<script>
window.MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] }, svg: { fontCache: 'global' } };
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

<script>
document.addEventListener("DOMContentLoaded", () => {
    if (window.MathJax && window.MathJax.typesetPromise) MathJax.typesetPromise();
});
function renderMathJax() {
    if (window.MathJax && window.MathJax.typesetPromise) MathJax.typesetPromise();
}
if (document.getElementById('nextBtn')) document.getElementById('nextBtn').addEventListener('click', renderMathJax);
if (document.getElementById('prevBtn')) document.getElementById('prevBtn').addEventListener('click', renderMathJax);
</script>

<script>
    history.pushState(null, null, location.href);
    window.onpopstate = function () { history.go(1); };
</script>

<script>
function pressCalc(value) {
    document.getElementById('calc-display').value += value;
}
function clearCalc() { document.getElementById('calc-display').value = ''; }
function calculateResult() {
    const display = document.getElementById('calc-display');
    try { display.value = eval(display.value); } catch { display.value = "Error"; }
}
function toggleCalculator() {
    const calc = document.getElementById('calculatorBox');
    calc.style.display = calc.style.display === "none" ? "block" : "none";
}
</script>

<script>
    // Auto-save theory answers
function autoSaveTheory() {
    const form = document.getElementById('examForm');
    const data = new FormData(form);
    // Only send theory questions
    const theoryData = new FormData();
    theoryData.append('exam_id', "<?= $exam_id ?>");
    for (const [key, value] of data.entries()) {
        if (key.startsWith('answers[')) {
            const qid = key.match(/answers\[(\d+)\]/)[1];
            theoryData.append(`answers[${qid}]`, value);
        }
    }
    fetch('autosave_exam.php', { method: 'POST', body: theoryData })
        .then(res => res.text())
        .then(txt => console.log('Auto-saved:', txt))
        .catch(err => console.error('Auto-save error:', err));
}

// Save on input change
document.querySelectorAll('textarea[name^="answers"]').forEach(ta => {
    ta.addEventListener('input', () => autoSaveTheory());
});

// Also save every 30 seconds
setInterval(autoSaveTheory, 30000);

</script>

<script>
    // exam_end_timestamp supplied by PHP
    let endTime = <?= (int)$exam_end_timestamp ?>;
    let timerEl = document.getElementById('timer');
    const warningBox = document.getElementById('malpracticeAlert');
    const warningCount = document.getElementById('warningCount');
    const malpracticeKey = 'malpracticeCount_<?= (int)$student_id ?>_<?= (int)$exam_id ?>';

    // initialize malpractice count from localStorage if present
    let malpracticeCount = parseInt(localStorage.getItem(malpracticeKey) || '0', 10) || 0;
    localStorage.setItem(malpracticeKey, malpracticeCount);
    warningBox.style.display = malpracticeCount > 0 ? 'inline-block' : 'none';
    warningCount.textContent = malpracticeCount;

    function updateTimer() {
        let now = new Date().getTime();
        let distance = endTime - now;
        if (distance <= 0) {
            clearInterval(timerInterval);
            Swal.fire("Time's up!", "Your exam will be submitted.", "info").then(() => {
                document.getElementById('examForm').submit();
            });
            return;
        }

        let hours = Math.floor((distance / (1000 * 60 * 60)));
        let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = Math.floor((distance % (1000 * 60)) / 1000);

        let timeStr = (hours > 0 ? hours + 'h ' : '') + minutes + 'm ' + seconds + 's';
        timerEl.innerHTML = timeStr;

        if (distance <= 120000) {
            timerEl.classList.remove('bg-danger');
            timerEl.classList.add('bg-warning');
        }
    }

    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            malpracticeCount++;
            localStorage.setItem(malpracticeKey, malpracticeCount);
            warningBox.style.display = 'inline-block';
            warningCount.textContent = malpracticeCount;

            // notify server of malpractice
            fetch('malpractice_flag.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    student_id: "<?= (int)$student_id ?>",
                    exam_id: "<?= (int)$exam_id ?>",
                    count: malpracticeCount
                })
            });

            if (malpracticeCount === 1) {
                Swal.fire({ icon: 'warning', title: 'Tab Switch Detected', text: 'Warning: Do not leave the exam tab.', timer: 3000, showConfirmButton: false, timerProgressBar: true });
            } else if (malpracticeCount === 2) {
                Swal.fire({ icon: 'warning', title: 'Final Warning!', text: 'One more tab switch will disqualify you!', timer: 4000, showConfirmButton: false, timerProgressBar: true });
            } else if (malpracticeCount >= 3) {
                Swal.fire({ icon: 'error', title: 'Disqualified', text: 'You have been disqualified for malpractice.', confirmButtonText: 'Exit' }).then(() => {
                    window.location.href = "../index.php";
                });
            }
        }
    });

    const timerInterval = setInterval(updateTimer, 1000);

    // navigation
    let current = 0;
    const cards = document.querySelectorAll('.question-card');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const submitBtn = document.getElementById('submitBtn');
    const reviewBtns = document.querySelectorAll('.review-btn');

    function showCard(index) {
        cards.forEach((card, i) => {
            card.style.display = i === index ? 'block' : 'none';
            reviewBtns[i].classList.toggle('btn-primary', i === index);
            reviewBtns[i].classList.toggle('btn-outline-primary', i !== index);
        });
        prevBtn.disabled = index === 0;
        nextBtn.classList.toggle('d-none', index === cards.length - 1);
        submitBtn.classList.toggle('d-none', index !== cards.length - 1);
        current = index;
    }

    if (cards.length) {
        prevBtn.onclick = () => { if (current > 0) showCard(--current); };
        nextBtn.onclick = () => { if (current < cards.length - 1) showCard(++current); };
        reviewBtns.forEach(btn => btn.addEventListener('click', () => showCard(parseInt(btn.dataset.index))));
        showCard(current);
    }

    // disable right-click
    document.addEventListener('contextmenu', e => e.preventDefault());

    // autosave every 30 seconds
    setInterval(() => {
        const form = document.getElementById('examForm');
        const data = new FormData(form);
        fetch('autosave_exam.php', { method: 'POST', body: data });
    }, 30000);

    /**
     * MCQ Confirmation flow:
     * - On form submit, if Qtype is 'mcq', gather answered count and total mcq questions
     * - Show confirmation modal with counts
     * - On confirm -> submit form
     * - On cancel -> close modal and return to exam
     */
    (function () {
        const form = document.getElementById('examForm');
        const qtype = "<?= addslashes($Qtype) ?>";
        const confirmBackdrop = document.getElementById('confirmModalBackdrop');
        const confirmCountEl = document.getElementById('confirmCount');
        const confirmCancel = document.getElementById('confirmCancel');
        const confirmSubmit = document.getElementById('confirmSubmit');

        function countMCQAnswered() {
            // Count number of question-cards that are MCQ and how many have a checked radio
            const cards = document.querySelectorAll('.question-card');
            let total = 0;
            let answered = 0;
            cards.forEach(card => {
                // If card contains radio inputs (MCQ), count it
                const radios = card.querySelectorAll('input[type="radio"]');
                if (radios && radios.length > 0) {
                    total++;
                    const checked = card.querySelector('input[type="radio"]:checked');
                    if (checked) answered++;
                }
            });
            return { answered, total };
        }

        function showConfirm(answered, total) {
            confirmCountEl.textContent = `You have answered ${answered} out of ${total} questions.`;
            confirmBackdrop.style.display = 'flex';
            // focus confirm for accessibility
            confirmSubmit.focus();
        }

        function hideConfirm() {
            confirmBackdrop.style.display = 'none';
        }

        // Cancel button
        confirmCancel.addEventListener('click', function (e) {
            e.preventDefault();
            hideConfirm();
        });

        // On confirm, disable the confirm button (prevent double-click) and submit the form
        confirmSubmit.addEventListener('click', function (e) {
            e.preventDefault();
            confirmSubmit.disabled = true;
            // optionally show a tiny spinner or change text
            confirmSubmit.textContent = 'Submitting...';
            // Submit the real form
            form.submit();
        });

        // Intercept form submit
        form.addEventListener('submit', function (ev) {
            // If qtype is mcq => show confirmation modal
            if (qtype === 'mcq') {
                ev.preventDefault();
                const counts = countMCQAnswered();
                // Show confirm with counts
                showConfirm(counts.answered, counts.total);
                return;
            }
            // otherwise allow submit to proceed
        });
    })();
</script>

<!-- jQuery & Bootstrap (for modal) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>

<?php include('partials/footer.php'); ?>
