<?php
ob_start();
require_once('operations.php');
session_start();

$db = new Operations();
$db2 = new Operations();

if (isset($_GET['examcode'], $_GET['admissionno'], $_GET['class'], $_GET['lname'], $_GET['fname'])) {
    $examcode = $_GET['examcode'];
    $admissionno = $_GET['admissionno'];
    $class2 = $_GET['class'];
    $lname = $_GET['lname'];
    $fname = $_GET['fname'];

    $_SESSION['exam_info'] = compact('examcode', 'admissionno', 'class2', 'lname', 'fname');
}

if (!isset($_SESSION['exam_info'])) {
    die("Exam session not set.");
}

extract($_SESSION['exam_info']);

$db->findExamsById($examcode);
if ($db->status == "closed") {
    echo "<script>alert('Exam is still closed. Contact admin.'); window.location.href='studDashboard.php';</script>";
    exit;
}

if ($db->checkCountScores($examcode, $admissionno) >= 1) {
    echo "<script>alert('You have already written this exam'); window.location.href='studDashboard.php';</script>";
    exit;
}

$statement2 = $db2->getQuestionsByExamIDRandom($examcode);
$questions = $statement2->fetchAll(PDO::FETCH_ASSOC);

$totalQuestions = count($questions);
$perPage = 2;
$totalPages = ceil($totalQuestions / $perPage);

$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, min($totalPages, $currentPage));

$startIndex = ($currentPage - 1) * $perPage;
$currentQuestions = array_slice($questions, $startIndex, $perPage);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($_POST['choices'] ?? [] as $qnum => $ans) {
        $_SESSION['answers'][$qnum] = $ans;
    }
    if (isset($_POST['final_submit'])) {
        header("Location: compute.php");
        exit;
    } else {
        $nextPage = $currentPage + (isset($_POST['next']) ? 1 : -1);
        header("Location: examsPage.php?page=$nextPage");
        exit;
    }
}

$db->findSubjectById($db->subject_id);
?>

<!DOCTYPE html>
<html>
<head>
    <title>CBT Exam</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <style>
        body {
            background-color: #e9ebee;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .exam-header {
            background-color: #4267B2;
            color: white;
            padding: 20px;
            border-radius: 10px 10px 0 0;
        }
        .question-card {
            border: 1px solid #ddd;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .form-check-label {
            font-weight: 500;
        }
        .sticky-header {
            position: sticky;
            top: 0;
            z-index: 1000;
            background-color: #4267B2;
            color: white;
            padding: 10px;
            text-align: center;
            border-radius: 0 0 10px 10px;
        }
        .btn-facebook {
            background-color: #4267B2;
            color: white;
        }
        .btn-facebook:hover {
            background-color: #365899;
        }
    </style>
</head>
<body>

<div class="container mt-4">
    <div class="sticky-header">
        <strong>⏳ Time Left:</strong> <span id="quiz-time-left"></span>
    </div>

    <div class="exam-header mb-4 text-center">
        <h2><?= htmlspecialchars($db->title) ?></h2>
        <p><strong>Page <?= $currentPage ?> of <?= $totalPages ?></strong></p>
    </div>

    <form method="post" id="exam-form" action="">
        <?php foreach ($currentQuestions as $index => $q): ?>
            <?php $qnum = $startIndex + $index + 1; ?>
            <div class="question-card p-3">
                <h5><strong>(<?= $qnum ?>)</strong> <?= htmlspecialchars($q['question']) ?></h5>
                <hr>
                <?php foreach (['A', 'B', 'C', 'D'] as $opt): ?>
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="choices[<?= $qnum ?>]" value="<?= $opt ?>" id="q<?= $qnum . $opt ?>" <?= (isset($_SESSION['answers'][$qnum]) && $_SESSION['answers'][$qnum] === $opt) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="q<?= $qnum . $opt ?>">
                            <?= htmlspecialchars($q['option' . $opt]) ?>
                        </label>
                    </div>
                <?php endforeach; ?>
                <input type="hidden" name="id[<?= $qnum ?>]" value="<?= $q['id'] ?>">
            </div>
        <?php endforeach; ?>

        <div class="d-flex justify-content-between mt-4">
            <?php if ($currentPage > 1): ?>
                <button type="submit" name="prev" class="btn btn-secondary">← Previous</button>
            <?php endif; ?>
            <?php if ($currentPage < $totalPages): ?>
                <button type="submit" name="next" class="btn btn-facebook">Next →</button>
            <?php else: ?>
                <button type="submit" name="final_submit" class="btn btn-success" onclick="return confirm('Are you sure you want to submit?')">Submit Exam</button>
            <?php endif; ?>
        </div>
    </form>
</div>

<script>
    let blurCount = 0;

    function autoSubmitExam() {
        alert("Submitting your exam.");
        // Dynamically add hidden input to indicate final submit
        let form = document.getElementById("exam-form");
        if (!form.querySelector('input[name="final_submit"]')) {
            let input = document.createElement("input");
            input.type = "hidden";
            input.name = "final_submit";
            input.value = "1";
            form.appendChild(input);
        }
        form.submit();
    }

    window.addEventListener("blur", function () {
        blurCount++;
        if (blurCount === 1) {
            alert("You have left the exam window. Please return immediately.");
        } else if (blurCount >= 2) {
            autoSubmitExam();
        }
    });

    var total_seconds = <?= $db->duration * 60 ?>;
    var quiz_timer = setInterval(function () {
        let mins = Math.floor(total_seconds / 60);
        let secs = total_seconds % 60;
        document.getElementById('quiz-time-left').textContent = `${mins}m ${secs}s`;
        total_seconds--;
        if (total_seconds < 0) {
            clearInterval(quiz_timer);
            alert("Time is up! Submitting exam.");
            autoSubmitExam();
        }
    }, 1000);
</script>

</body>
</html>
