<?php
session_start();
require_once 'db.php';

if (!isset($_SESSION['started']) || $_SESSION['started'] !== true) {
    header("Location: login.php");
    exit();
}

if (time() > $_SESSION['end_time']) {
    header("Location: submit.php?timeout=1");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>OSCOTECH CBT Examination</title>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f6f9; margin: 0; padding: 20px; }
        .workspace { display: grid; grid-template-columns: 280px 1fr; gap: 20px; max-width: 1200px; margin: 20px auto; }
        .profile-card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); text-align: center; height: fit-content; }
        .profile-img { width: 130px; height: 130px; border-radius: 50%; object-fit: cover; border: 4px solid #eef2f7; margin-bottom: 15px; background: #ddd; }
        .exam-card { background: white; padding: 35px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); position: relative; }
        .meta-line { text-align: left; font-size: 13px; margin: 8px 0; border-bottom: 1px dashed #eee; padding-bottom: 5px; color: #555; }
        .timer-box { font-size: 22px; font-weight: bold; color: #d9534f; background: #fff5f5; border: 1px solid #d9534f; padding: 10px; border-radius: 4px; margin-bottom: 20px; display: block; text-align: center; }
        .q-card { display: none; }
        .q-card.active { display: block; }
        .options-list { list-style-type: none; padding: 0; }
        .options-list li { margin: 12px 0; background: #f9f9f9; padding: 12px; border-radius: 4px; border: 1px solid #ddd; }
        .nav-btns { margin-top: 20px; display: flex; gap: 10px; }
        .btn { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 15px; font-weight: bold; }
        .btn:disabled { background: #ccc; cursor: not-allowed; }
        .btn-danger { background: #d9534f; }
    </style>
</head>
<body>

<div class="workspace">
    <!-- LEFT PANEL: Dynamic Multi-Field Metadata Display Dashboard Card -->
    <div class="profile-card">
        <?php if ($_SESSION['photography'] !== 'placeholder'): ?>
            <img class="profile-img" src="<?php echo $_SESSION['photography']; ?>" alt="Student Photo">
        <?php else: ?>
            <div class="profile-img" style="display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: bold; color: #777; margin-left: auto; margin-right: auto;">👤</div>
        <?php endif; ?>
        
        <h4 style="margin: 5px 0 15px 0; color:#333;"><?php echo htmlspecialchars($_SESSION['student_name']); ?></h4>
        
        <div class="meta-line"><strong>Matric:</strong> <?php echo htmlspecialchars($_SESSION['matric_number']); ?></div>
        <div class="meta-line"><strong>Gender/Sex:</strong> <?php echo htmlspecialchars($_SESSION['sex']); ?></div>
        <div class="meta-line"><strong>Department:</strong> <?php echo htmlspecialchars($_SESSION['department']); ?></div>
        <div class="meta-line"><strong>Level Track:</strong> <?php echo htmlspecialchars($_SESSION['student_level']); ?></div>
        <div class="meta-line" style="border:none; background:#eef2f7; padding: 8px; font-weight: bold; border-radius: 4px; color:#0056b3; margin-top:15px; text-align: center;">
            Course: <?php echo htmlspecialchars($_SESSION['course_code']); ?>
        </div>
    </div>

    <!-- RIGHT PANEL: Question Paper Execution Platform -->
    <div class="exam-card">
        <div class="timer-box" id="countdownTimer">--:--</div>

        <form id="cbtExamForm" action="submit.php" method="POST">
            <?php foreach ($_SESSION['questions'] as $idx => $question): ?>
                <div class="q-card <?php echo $idx === 0 ? 'active' : ''; ?>" id="tab-<?php echo $idx; ?>">
                    <h3 style="color:#555; margin-top:0;">Question <?php echo ($idx + 1); ?> of <?php echo $_SESSION['total_questions']; ?></h3>
                    <p style="font-size: 16px; font-weight: bold; line-height: 1.5; color:#222;">
                        <?php echo htmlspecialchars($question['question_text']); ?>
                    </p>
                    
                    <ul class="options-list">
                        <?php foreach (['A', 'B', 'C', 'D'] as $letter): ?>
                            <li>
                                <label style="display: block; cursor: pointer;">
                                    <input type="radio" name="answers[<?php echo $question['id']; ?>]" value="<?php echo $letter; ?>">
                                    <strong><?php echo $letter; ?>.</strong> <?php echo htmlspecialchars($question['option_'.strtolower($letter)]); ?>
                                </label>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endforeach; ?>

            <div class="nav-btns">
                <button type="button" class="btn" id="prevTabBtn" onclick="changeQuestion(-1)" disabled>Previous</button>
                <button type="button" class="btn" id="nextTabBtn" onclick="changeQuestion(1)">Next Question</button>
                <button type="submit" class="btn btn-danger" id="submitExamFormBtn" style="display: none;">Submit Exam</button>
            </div>
        </form>
    </div>
</div>

<script>
    let activeIndex = 0;
    const totalItems = <?php echo $_SESSION['total_questions']; ?>;
    
    function showActiveQuestion(n) {
        const cards = document.getElementsByClassName("q-card");
        cards[n].classList.add("active");
        
        document.getElementById("prevTabBtn").disabled = (n === 0);
        if (n === (totalItems - 1)) {
            document.getElementById("nextTabBtn").style.display = "none";
            document.getElementById("submitExamFormBtn").style.display = "inline-block";
        } else {
            document.getElementById("nextTabBtn").style.display = "inline-block";
            document.getElementById("submitExamFormBtn").style.display = "none";
        }
    }

    function changeQuestion(step) {
        const cards = document.getElementsByClassName("q-card");
        cards[activeIndex].classList.remove("active");
        activeIndex += step;
        showActiveQuestion(activeIndex);
    }

    // High precision localized browser clock execution tracker
    const targetTimeMillis = <?php echo $_SESSION['end_time']; ?> * 1000;
    const trackingLoop = setInterval(function() {
        const now = new Date().getTime();
        const delta = targetTimeMillis - now;
        
        if (delta <= 0) {
            clearInterval(trackingLoop);
            // Remove the refresh lock immediately before auto-submitting
            window.removeEventListener('beforeunload', preventReloadAlert);
            document.getElementById("countdownTimer").innerHTML = "TIMEOUT EXPIRED";
            document.getElementById("cbtExamForm").submit();
            return;
        }
        
        const min = Math.floor((delta % (1000 * 60 * 60)) / (1000 * 60));
        const sec = Math.floor((delta % (1000 * 60)) / 1000);
        document.getElementById("countdownTimer").innerHTML = "Remaining Duration Time: " + min + "m " + sec + "s ";
    }, 1000);

    // ==========================================
    // REFRESH LOCKING & SECURITY RULES BLOCK
    // ==========================================
    
    // Warn the user before they leave, refresh, close the tab, or go back
    window.addEventListener('beforeunload', preventReloadAlert);
    
    function preventReloadAlert(e) {
        e.preventDefault();
        e.returnValue = 'Warning: An active exam session is running! Reloading will disrupt your testing window.';
    }

    // Disable right-clicks to block context-menu refreshes
    document.addEventListener('contextmenu', event => event.preventDefault());

    // Catch and block keyboard shortcuts (F5, Ctrl+R, Cmd+R)
    document.addEventListener('keydown', function (e) {
        if (
            e.key === 'F5' || 
            (e.ctrlKey && e.key === 'r') || 
            (e.metaKey && e.key === 'r')
        ) {
            e.preventDefault();
            alert("Action Prohibited: Page refresh options are locked down during the exam.");
        }
    });

    // Remove security lock rules cleanly when the student submits the exam manually
    document.getElementById('cbtExamForm').addEventListener('submit', function(e) {
        if (!confirm('Do you completely certify validation to submit score sheets?')) {
            e.preventDefault();
            return false;
        }
        window.removeEventListener('beforeunload', preventReloadAlert);
    });
</script>
</body>
</html>
