<?php 
// Debugging (Remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

// 1. Database Connection
if (!file_exists('db_connect.php')) {
    die("Error: db_connect.php file is missing.");
}
require_once 'db_connect.php';

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

// Get Exam ID from URL
if(!isset($_GET['id'])) { 
    header("Location: exams.php"); 
    exit; 
}

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

try {
    // 🚨 Double Exam Check (Check if the student has already taken this exam)
    $check_taken = $pdo->prepare("SELECT id FROM exam_result WHERE student_id = ? AND exam_id = ?");
    $check_taken->execute([$student_id, $exam_id]);
    if ($check_taken->rowCount() > 0) {
        die("<div style='text-align:center; padding:100px 20px; font-family: \"Outfit\", sans-serif; background: #f8fafc; min-height: 100vh;'>
                <i class='fas fa-exclamation-triangle' style='font-size: 60px; color: #d4af37; margin-bottom: 20px;'></i>
                <h2 style='color:#022c22; font-weight: 800; margin-bottom: 30px;'>You have already participated in this exam!</h2>
                <a href='all_results.php' style='padding:12px 30px; background:#064e3b; color:#fff; text-decoration:none; border-radius:50px; font-weight: 700; box-shadow: 0 5px 15px rgba(6,78,59,0.3); transition: 0.3s;'>View Your Result</a>
             </div>");
    }

    // 3. Fetch Exam Information
    $exam_stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ? AND status = 'active'");
    $exam_stmt->execute([$exam_id]);
    $exam = $exam_stmt->fetch(PDO::FETCH_ASSOC);

    if(!$exam) { 
        die("<div style='text-align:center; padding:100px 20px; font-family: \"Outfit\", sans-serif; background: #f8fafc; min-height: 100vh;'>
                <h2 style='color:#022c22; font-weight: 800;'>The exam could not be found or is currently closed.</h2>
             </div>"); 
    }

    // 4. Fetch all questions for this exam (RANDOM order so each student gets a different sequence)
    $q_stmt = $pdo->prepare("SELECT * FROM questions WHERE exam_id = ? ORDER BY RAND()");
    $q_stmt->execute([$exam_id]);
    $questions = $q_stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

// Include Header
if(file_exists('includes/user_header.php')) { include 'includes/user_header.php'; } 
elseif(file_exists('header.php')) { include 'header.php'; }
?>

<style>
    :root {
        --primary: #064e3b;
        --primary-dark: #022c22;
        --accent: #d4af37; /* Golden */
    }

    body { background-color: #f8fafc; }
    
    /* Anti-cheat: Disable text selection */
    .unselectable {
        -webkit-user-select: none; /* Safari */
        -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* IE10+/Edge */
        user-select: none; /* Standard */
    }

    .sticky-timer { position: sticky; top: 15px; z-index: 1000; }
    
    .question-card { 
        border-left: 5px solid #cbd5e1; 
        transition: 0.3s; 
    }
    .question-card:hover { 
        border-left-color: var(--accent); /* Golden border on hover */
        box-shadow: 0 10px 25px rgba(0,0,0,0.05) !important; 
        transform: translateY(-3px); 
    }
    
    .option-label { 
        cursor: pointer; 
        display: flex; 
        align-items: center; 
        padding: 12px 18px; 
        border-radius: 12px; 
        border: 2px solid #e2e8f0; 
        transition: 0.2s; 
        background: #fff; 
        height: 100%; 
        font-size: 15px; 
    }
    .option-label:hover { 
        border-color: #94a3b8; 
        background: #f1f5f9; 
    }
    
    /* Selected Option Style (Deep Green Border + Light Golden Background) */
    .option-input:checked + .option-label { 
        background: rgba(212, 175, 55, 0.08); 
        border-color: var(--primary); 
        color: var(--primary-dark); 
        font-weight: 700; 
        box-shadow: 0 4px 10px rgba(6, 78, 59, 0.1); 
    }
    .option-input { display: none; }
    
    #timer-box { font-size: 22px; font-weight: 800; font-variant-numeric: tabular-nums; transition: 0.3s; }
    .timer-warning { background: #dc3545 !important; color: #fff !important; border-color: #dc3545 !important; animation: pulse 1s infinite; }
    
    @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.05); } 100% { transform: scale(1); } }
</style>

<div class="container py-4 unselectable">
    
    <div class="row sticky-timer mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-lg rounded-pill p-3 d-flex flex-row justify-content-between align-items-center" style="background: var(--primary-dark); color: #fff; border: 2px solid var(--accent);">
                <div class="ms-3 d-none d-md-block">
                    <h5 class="mb-0 fw-bold" style="color: var(--accent);"><?= htmlspecialchars($exam['exam_title']); ?></h5>
                    <small class="opacity-75"><i class="fas fa-list-ol me-1"></i> Total Questions: <?= count($questions); ?></small>
                </div>
                <div class="ms-3 d-block d-md-none">
                    <h6 class="mb-0 fw-bold" style="color: var(--accent);">Live Exam</h6>
                </div>
                <div id="timer-box" class="bg-white px-4 py-2 rounded-pill shadow-sm" style="color: var(--primary); border: 2px solid #e2e8f0;">
                    <i class="far fa-clock me-2 text-danger"></i> <span id="time-left">00:00</span>
                </div>
            </div>
        </div>
    </div>

    <form id="examForm" action="submit_exam.php" method="POST">
        <input type="hidden" name="exam_id" value="<?= $exam_id; ?>">
        
        <div class="row justify-content-center">
            <div class="col-lg-10">
                
                <?php if(!empty($questions)): $i = 1; foreach($questions as $q): ?>
                <div class="card border-0 shadow-sm rounded-4 p-4 mb-4 question-card bg-white">
                    <h5 class="fw-bold mb-4 text-dark" style="line-height: 1.5;">
                        <span style="color: var(--primary);" class="me-1"><?= $i++; ?>.</span> <?= htmlspecialchars($q['question_text']); ?>
                    </h5>
                    
                    <div class="row g-3">
                        <?php 
                        $options = ['a' => $q['option_a'], 'b' => $q['option_b'], 'c' => $q['option_c'], 'd' => $q['option_d']];
                        foreach($options as $key => $val): 
                            if(empty(trim($val))) continue;
                        ?>
                        <div class="col-md-6">
                            <input type="radio" name="answers[<?= $q['id']; ?>]" value="<?= $key; ?>" id="q<?= $q['id'].$key; ?>" class="option-input">
                            <label for="q<?= $q['id'].$key; ?>" class="option-label">
                                <span class="me-2 badge bg-dark bg-opacity-10 text-dark rounded-circle text-uppercase"><?= $key; ?></span> 
                                <?= htmlspecialchars($val); ?>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; else: ?>
                    <div class="text-center py-5 bg-white shadow-sm rounded-4 border">
                        <i class="fas fa-box-open fa-3x text-muted mb-3 opacity-50"></i>
                        <h5 class="text-muted fw-bold">No questions have been added to this exam yet.</h5>
                    </div>
                <?php endif; ?>

                <?php if(!empty($questions)): ?>
                <div class="text-center mt-5 mb-5">
                    <button type="button" class="btn btn-lg px-5 py-3 rounded-pill fw-bold shadow-lg" style="background: var(--primary); color: white; border: none; font-size: 18px; transition: 0.3s;" onmouseover="this.style.backgroundColor='var(--accent)'; this.style.color='var(--primary-dark)';" onmouseout="this.style.backgroundColor='var(--primary)'; this.style.color='white';" onclick="confirmSubmit()">
                        Submit Exam <i class="fas fa-paper-plane ms-2"></i>
                    </button>
                </div>
                <?php endif; ?>
                
            </div>
        </div>
    </form>
</div>

<script>
    // ==========================================
    // 🛡️ CHEAT PROTECTION SYSTEM
    // ==========================================

    // 1. Disable Right Click
    document.addEventListener('contextmenu', event => event.preventDefault());

    // 2. Disable Copy, Paste, and Cut
    document.addEventListener('copy', e => e.preventDefault());
    document.addEventListener('paste', e => e.preventDefault());
    document.addEventListener('cut', e => e.preventDefault());

    // 3. Disable Keyboard Shortcuts (F12, Ctrl+Shift+I, Ctrl+U)
    document.onkeydown = function(e) {
        if (e.keyCode == 123) return false; // F12
        if (e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) return false;
        if (e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) return false;
        if (e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) return false;
        if (e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) return false; // View Source
    };

    // 4. Tab Switching Detection (Warnings before Auto-Submit)
    let warningCount = 0;
    const maxWarnings = 3; // 3 warnings allowed
    const examForm = document.getElementById('examForm');
    let isSubmitting = false;

    document.addEventListener("visibilitychange", function() {
        if (document.hidden && !isSubmitting) {
            warningCount++;
            if (warningCount >= maxWarnings) {
                isSubmitting = true;
                window.onbeforeunload = null;
                alert("You have switched tabs multiple times! Due to suspicious activity, your exam is being auto-submitted.");
                examForm.submit();
            } else {
                alert("Warning " + warningCount + " (Max " + maxWarnings + "): Switching tabs or apps during the exam is prohibited! If you break this rule, your exam will be auto-submitted.");
            }
        }
    });

    // ==========================================
    // ⏱️ TIMER LOGIC
    // ==========================================
    let totalSeconds = <?= isset($exam['duration_minutes']) ? (int)$exam['duration_minutes'] * 60 : 0; ?>;
    const timerDisplay = document.getElementById('time-left');
    const timerBox = document.getElementById('timer-box');

    const countdown = setInterval(() => {
        if (totalSeconds <= 0) {
            clearInterval(countdown);
            if(!isSubmitting){
                isSubmitting = true;
                timerDisplay.innerHTML = "00:00";
                alert("Time's up! Your exam is being auto-submitted.");
                window.onbeforeunload = null;
                examForm.submit();
            }
            return;
        }

        let minutes = Math.floor(totalSeconds / 60);
        let seconds = totalSeconds % 60;

        minutes = minutes < 10 ? '0' + minutes : minutes;
        seconds = seconds < 10 ? '0' + seconds : seconds;

        timerDisplay.innerHTML = `${minutes}:${seconds}`;

        // Red pulse animation for the last 30 seconds
        if (totalSeconds <= 30 && !timerBox.classList.contains('timer-warning')) {
            timerBox.classList.add('timer-warning');
        }

        totalSeconds--;
    }, 1000);

    // Manual Submit Confirmation
    function confirmSubmit() {
        if(confirm('Are you sure you want to submit the exam?')) {
            isSubmitting = true;
            clearInterval(countdown);
            window.onbeforeunload = null;
            examForm.submit();
        }
    }

    // Prevent accidental page refresh or closing tab
    window.onbeforeunload = function() {
        if(!isSubmitting) {
            return "Are you sure you want to leave the exam? Your progress will be lost.";
        }
    };
</script>

<?php 
// Include Footer (if exists, hide regular footer elements that might distract from exam)
if(file_exists('includes/user_footer.php')) { include 'includes/user_footer.php'; } 
elseif(file_exists('footer.php')) { include 'footer.php'; }
?>