<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || $user->isAdmin()) {
    header("Location: ../index.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// Fetch Assigned Active Exams
// Logic: Exam must be active AND assigned to this student in exam_assignments table
$stmt = $pdo->prepare("
    SELECT e.*, s.name as subject_name 
    FROM exams e
    JOIN exam_assignments ea ON e.exam_id = ea.exam_id
    JOIN subjects s ON e.subject_id = s.subject_id
    WHERE ea.user_id = ? AND e.status = 'active'
");
$stmt->execute([$user_id]);
$exams = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Dashboard</title>
    <link rel="stylesheet" href="../assets/css/student.css">
</head>
<body>
    <?php include '../includes/loader.php'; ?>
    <div class="container">
        <?php include '../includes/page_header.php'; ?>
        <div class="header">
            <?php
            $stmtName = $pdo->prepare("SELECT full_name, username FROM users WHERE user_id = ?");
            $stmtName->execute([$user_id]);
            $me = $stmtName->fetch();
            $displayName = $me && !empty($me['full_name']) ? $me['full_name'] : $me['username'];
            ?>
            <h2>Hello, <?php echo htmlspecialchars($displayName); ?></h2>
            <a href="../logout.php" style="color: red;">Logout</a>
        </div>
        
        <?php if (isset($_GET['completed'])): ?>
            <div style="padding:10px; background:#e9ecef; border:1px solid #ced4da; border-radius:4px; margin-bottom:15px;">
                You have completed the exam. Thank you.
            </div>
        <?php endif; ?>

        <h3>Available Exams</h3>
        
        <?php if (count($exams) > 0): ?>
            <?php foreach ($exams as $exam): ?>
                <?php
                // Check status
                $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM results WHERE user_id = ? AND exam_id = ?");
                $stmtCheck->execute([$user_id, $exam['exam_id']]);
                $taken = $stmtCheck->fetchColumn();
                $allowed = $exam['allowed_attempts'] ?? 1;
                ?>
                <div class="exam-card">
                    <div>
                        <strong><?php echo htmlspecialchars($exam['title']); ?></strong><br>
                        Subject: <?php echo htmlspecialchars($exam['subject_name']); ?><br>
                        Duration: <?php echo $exam['duration']; ?> mins<br>
                        <small>Attempts: <?php echo $taken; ?> / <?php echo $allowed; ?></small>
                    </div>
                    <?php if ($taken >= $allowed): ?>
                        <a href="result_slip.php?exam_id=<?php echo $exam['exam_id']; ?>" class="btn" style="background:#6c757d;">View Result</a>
                    <?php else: ?>
                        <a href="take_exam.php?exam_id=<?php echo $exam['exam_id']; ?>" class="btn">Start Exam</a>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p>No active exams assigned to you at the moment.</p>
        <?php endif; ?>

        <div class="footer">Designed by ferakeys</div>
    </div>
    <script>
        (function(){
            const goFullscreen = async () => {
                try {
                    if (!document.fullscreenElement && document.documentElement.requestFullscreen) {
                        await document.documentElement.requestFullscreen();
                    }
                } catch(e) { /* ignore */ }
            };
            // Attempt immediately (may silently fail)
            goFullscreen();
            // Guarantee on first interaction
            const once = (fn) => {
                let done = false;
                return () => { if (!done) { done = true; fn(); } };
            };
            const ensureFS = once(goFullscreen);
            window.addEventListener('click', ensureFS, { once: true });
            window.addEventListener('keydown', ensureFS, { once: true });

            const logoutLink = document.querySelector('a[href="../logout.php"]');
            if (logoutLink) {
                logoutLink.addEventListener('click', function(e){
                    const loader = document.getElementById('global-loader');
                    if (loader) {
                        loader.classList.remove('hidden');
                        loader.style.display = 'flex';
                    }
                });
            }
        })();
    </script>
</body>
</html>
