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

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

include('partials/exam_header.php');

$student_id = (int) $_SESSION['student_id'];
$exam_id    = (int) ($_GET['exam_id'] ?? 0);

// Fetch student info — prepared
$stmtStu = $conn->prepare("SELECT * FROM students WHERE id = ? LIMIT 1");
$stmtStu->bind_param("i", $student_id);
$stmtStu->execute();
$student = $stmtStu->get_result()->fetch_assoc();
if (!$student) {
    echo "<div class='alert alert-danger'>Student not found.</div>";
    exit;
}

// Fetch exam info — prepared
$stmtExam = $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 = ? LIMIT 1
");
$stmtExam->bind_param("i", $exam_id);
$stmtExam->execute();
$exam = $stmtExam->get_result()->fetch_assoc();

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

// 🧠 REPLACED SESSION TIMER WITH DB TIMER
$exam_end_timestamp = 0;
$checkSession = $conn->prepare("SELECT end_time FROM student_exam_sessions WHERE student_id = ? AND exam_id = ?");
$checkSession->bind_param("ii", $student_id, $exam_id);
$checkSession->execute();
$checkResult = $checkSession->get_result();
$checkSession->close();

if ($checkResult->num_rows > 0) {
    $end_time_db = $checkResult->fetch_assoc()['end_time'];
    $exam_end_timestamp = strtotime($end_time_db) * 1000; // JS needs ms
} else {
    // New session – calculate and insert
    $duration = (int)$exam['duration_minutes'];
    $start_time = date('Y-m-d H:i:s');
    $end_time = date('Y-m-d H:i:s', strtotime("+$duration minutes"));
    $exam_end_timestamp = strtotime($end_time) * 1000;

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

// Fetch and shuffle questions — prepared
$stmtQ = $conn->prepare("SELECT * FROM questions WHERE exam_id = ? ORDER BY RAND()");
$stmtQ->bind_param("i", $exam_id);
$stmtQ->execute();
$qResult      = $stmtQ->get_result();
$questionList = $qResult && $qResult->num_rows ? $qResult->fetch_all(MYSQLI_ASSOC) : [];

// Fetch instruction
$instruction = "";
if ($exam_id) {
    $stmt = $conn->prepare("SELECT instruction FROM exam_instructions WHERE exam_id = ?");
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $stmt->bind_result($instruction);
    $stmt->fetch();
    $stmt->close();
}
?>



<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    @media (min-width: 1080px) {
        .sidebar-sticky {
            position: sticky;
            top: 100px;
        }
    }
</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($exam['exam_type']) ?>
</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 Content -->
                <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 ?>">

                        <?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 ?>" 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">
                                                   <!-- Question Text -->
                                                    <p class="question-text"><?= nl2br($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>

                                            <!-- Question Option -->
                                            <?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[<?= $q['id'] ?>]" 
                                                                   value="<?= $opt ?>" 
                                                                   id="q<?= $q['id'] ?>_<?= $opt ?>">
                                                            <label class="form-check-label question-text" for="q<?= $q['id'] ?>_<?= $opt ?>">
                                                                <?= $q['option_' . $opt] ?>
                                                            </label>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            <?php elseif ($q['question_type'] === 'theory'): ?>
                                                <textarea class="form-control" name="answers[<?= $q['id'] ?>]" rows="4"></textarea>
                                            <?php elseif ($q['question_type'] === 'fill'): ?>
                                                <input type="text" class="form-control" name="answers[<?= $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>
<!-- SCIENTIFIC CALCULATOR -->
<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">
        <!-- Row 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>

        <!-- Row 2 -->
        <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>

        <!-- Row 3 -->
        <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>

        <!-- Row 4 -->
        <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>

        <!-- Row 5 -->
        <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>

        <!-- Row 6 -->
        <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>
<!-- math.js: safe expression evaluator (replaces eval()) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.11.0/math.min.js"></script>

<script>
// Ensure MathJax runs on initial load
document.addEventListener("DOMContentLoaded", () => {
    if (window.MathJax && window.MathJax.typesetPromise) {
        MathJax.typesetPromise();
    }
});

// Re-render when switching questions
function renderMathJax() {
    if (window.MathJax && window.MathJax.typesetPromise) {
        MathJax.typesetPromise();
    }
}

// Example: hook into your Next/Prev buttons
document.getElementById('nextBtn').addEventListener('click', renderMathJax);
document.getElementById('prevBtn').addEventListener('click', renderMathJax);
</script>

<script>
    history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1); // prevent back button
    };
</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 {
        // ✅ FIX: Use math.js instead of eval() — safe expression parser
        display.value = math.evaluate(display.value);
    } catch {
        display.value = 'Error';
    }
}

function toggleCalculator() {
    const calc = document.getElementById('calculatorBox');
    calc.style.display = calc.style.display === "none" ? "block" : "none";
}
</script>


<script>
    let endTime = <?= $exam_end_timestamp ?>;
    let timerEl = document.getElementById('timer');
    const warningBox = document.getElementById('malpracticeAlert');
    const warningCount = document.getElementById('warningCount');
    let malpracticeKey = 'malpracticeCount_<?= $student_id ?>_<?= $exam_id ?>';
    let malpracticeCount = 0;

    localStorage.setItem(malpracticeKey, '0');
    warningBox.style.display = 'none';
    warningCount.textContent = '0';

    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 minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = Math.floor((distance % (1000 * 60)) / 1000);
        timerEl.innerHTML = `${minutes}m ${seconds}s`;

        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;

            fetch('malpractice_flag.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    student_id: "<?= $student_id ?>",
                    exam_id: "<?= $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);

    // Question 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());

    // Auto-save every 30 seconds
    setInterval(() => {
        const form = document.getElementById('examForm');
        const data = new FormData(form);
        fetch('autosave_exam.php', { method: 'POST', body: data });
    }, 30000);
</script>
<!-- MathJax for equation rendering -->
<script>
window.MathJax = {
  tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] },
  svg: { fontCache: 'global' }
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

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