<?php
include '../../includes/conn.php';
include '../../includes/functions.php';
requireRole('student');

$student_id = $_SESSION['user_id'];

// Ensure exam ID is provided
if (!isset($_GET['exam_id'])) {
    die("Exam ID not provided.");
}
$exam_id = intval($_GET['exam_id']);

// Fetch student info
$student_stmt = $pdo->prepare("
    SELECT u.username, u.email, u.first_name, u.last_name, u.photo, c.name AS current_class
    FROM users u
    LEFT JOIN classroom_students cs ON u.id = cs.student_id
    LEFT JOIN classrooms c ON cs.classroom_id = c.id
    WHERE u.id = ?
    LIMIT 1
");
$student_stmt->execute([$student_id]);
$student = $student_stmt->fetch(PDO::FETCH_ASSOC);
if (!$student) die("Student info not found.");

// Check if student already started the exam
$check_start = $pdo->prepare("SELECT id, started_at, submitted_at FROM cbt_exam_results WHERE exam_id = ? AND student_id = ?");
$check_start->execute([$exam_id, $student_id]);
$result = $check_start->fetch(PDO::FETCH_ASSOC);

if ($result && !empty($result['submitted_at'])) {
    // Redirect to the result page instead of dying
    header("Location: exam_result.php?exam_id=$exam_id&already_submitted=1");
    exit;
}

// Fetch exam info
$exam_stmt = $pdo->prepare("
    SELECT e.*, s.name AS session_name, t.name AS term_name
    FROM cbt_exams e
    LEFT JOIN sessions s ON e.session_id = s.id
    LEFT JOIN terms t ON e.term_id = t.id
    WHERE e.id = ?
");
$exam_stmt->execute([$exam_id]);
$exam = $exam_stmt->fetch(PDO::FETCH_ASSOC);
if (!$exam) die("Exam not found.");

// Fetch questions
$questions_stmt = $pdo->prepare("SELECT * FROM cbt_questions WHERE exam_id = ?");
$questions_stmt->execute([$exam_id]);
$questions = $questions_stmt->fetchAll(PDO::FETCH_ASSOC);
$total_questions = count($questions);

// Timer handling (persistent)
$exam_duration_seconds = intval($exam['duration'] ?? 30) * 60;

if (!$result) {
    // First time starting: insert row with started_at
    $insert_start = $pdo->prepare("
    INSERT INTO cbt_exam_results (exam_id, student_id, started_at)
    VALUES (?, ?, NOW())
    ON DUPLICATE KEY UPDATE started_at = started_at
    ");
    $insert_start->execute([$exam_id, $student_id]);
    $started_at = new DateTime();
} else {
    $started_at = new DateTime($result['started_at']);
}

// Calculate remaining seconds
$end_time = clone $started_at;
$end_time->modify("+{$exam_duration_seconds} seconds");
$remaining_seconds = max(0, $end_time->getTimestamp() - time());

// Prepare student photo as base64 if exists
if (!empty($student['photo'])) {
    $photo_base64 = 'data:image/jpeg;base64,' . base64_encode($student['photo']);
} else {
    $photo_base64 = '../user.png';
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Take Exam - <?= htmlspecialchars($exam['title']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        #timer { font-size: 1.2rem; font-weight: bold; }
        body { background: color: #fff; }
        .exam-container { max-width: 900px; margin: 40px auto; padding: 20px; background: #1e1e1e; border-radius: 12px; }
        .video-preview { width: 240px; border-radius: 8px; border: 2px solid #444; margin-top: 15px; }
        /* Consent modal (overlay) */
        #consentModal {
          position: fixed;
          inset: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(0,0,0,0.7);
          z-index: 1050;
        }
        .consent-card {
          background: #ffffff;
          color: #000;
          padding: 22px;
          border-radius: 10px;
          width: 100%;
          max-width: 720px;
          box-shadow: 0 8px 24px rgba(0,0,0,0.4);
        }
        .consent-card h4 { margin-bottom: 8px; }
        .consent-card p, .consent-card li { color: #222; }
        .text-muted-dark { color: rgba(255,255,255,0.6); }
        .small-muted { color: rgba(255,255,255,0.65); }
    </style>
</head>
<body>
<div class="container mt-3">
    <div class="row">
        <!-- Exam Questions -->
        <div class="col-md-8">
            <div class="card shadow-sm mb-3 exam-container">
                <div class="card-body">
                    <div class="row shadow-sm mb-3"> 
                       <h4><?= htmlspecialchars($exam['title']) ?></h4>
                        <small class="text-muted small-muted">
                            (Session: <?= htmlspecialchars($exam['session_name'] ?? 'N/A') ?>, 
                            Term: <?= htmlspecialchars($exam['term_name'] ?? 'N/A') ?>)
                        </small>
                        <div class="d-flex justify-content-between mb-3 mt-2">
                            <div>Total Questions: <?= $total_questions ?></div>
                            <div id="timer"></div>
                        </div>
                    </div>
                    <form action="submit_exam.php" method="POST" id="examForm">
                        <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
                        <?php foreach($questions as $index => $q): ?>
                            <div class="mb-3 border p-3 rounded bg-white text-dark">
                                <p><strong>Q<?= $index+1 ?>:</strong> <?= htmlspecialchars($q['question_text']) ?></p>
                                <?php foreach(['a','b','c','d'] as $opt): ?>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" 
                                               name="q_<?= $q['id'] ?>" 
                                               id="q<?= $q['id'] ?><?= $opt ?>" value="<?= $opt ?>">
                                        <label class="form-check-label" for="q<?= $q['id'] ?><?= $opt ?>">
                                            <?= htmlspecialchars($q['option_'.$opt]) ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endforeach; ?>
                        <button type="submit" class="btn btn-primary">Submit Exam</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Student Info Card -->
        <div class="col-md-4">
            <div class="card shadow-sm">
                <div class="card-body text-left">
                    <?php if (!empty($user['photo'])): ?>
                         <img src="data:image/jpeg;base64,<?php echo base64_encode($user['photo']);?>" 
                        alt="User Photo" 
                        style="width:120; height:120; border-radius:50%; object-fit:cover;">
                        <?php else: ?>
                        <img src="user.png" 
                        alt="Default Photo" 
                        style="width:120; height:120; border-radius:50%; object-fit:cover;">
                    <?php endif; ?>
                    <h5 class="card-title"><?= htmlspecialchars($student['first_name'].' '.$student['last_name']) ?></h5>
                    <p class="card-text mb-1"><strong>Username:</strong> <?= htmlspecialchars($student['username']) ?></p>
                    <p class="card-text mb-1"><strong>Email:</strong> <?= htmlspecialchars($student['email']) ?></p>
                    <p class="card-text mb-0"><strong>Class:</strong> <?= htmlspecialchars($student['current_class'] ?? 'N/A') ?></p>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- Timer Script -->
<script>
let timeLeft = <?= $remaining_seconds ?>; // persistent seconds
const timerEl = document.getElementById('timer');

function updateTimer() {
    let minutes = Math.floor(timeLeft / 60);
    let seconds = timeLeft % 60;
    timerEl.textContent = `Time Left: ${minutes}:${seconds < 10 ? '0'+seconds : seconds}`;
    if (timeLeft <= 0) {
        clearInterval(timerInterval);
        alert('Time is up! Submitting your exam...');
        
        // Automatically submit via AJAX (so no reload delay)
        const form = document.getElementById('examForm');
        const formData = new FormData(form);

        fetch('submit_exam.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.text())
        .then(response => {
            // Redirect to result page after success
            window.location.href = `exam_result.php?exam_id=<?= $exam_id ?>`;
        })
        .catch(err => {
            alert('Error submitting exam automatically. Please contact admin.');
            console.error(err);
        });
    }

    timeLeft--;
}

updateTimer(); // initial display
const timerInterval = setInterval(updateTimer, 1000);
</script>
</body>
</html>
