<?php
session_start();
if (!isset($_SESSION['student_id'])) {
    header('Location: student_login.php');
    exit;
}

// Handle language selection
if (isset($_GET['lang'])) {
    $lang = $_GET['lang'];
    if (in_array($lang, ['en', 'hi'])) {
        $_SESSION['lang'] = $lang;
    }
}
$lang = $_SESSION['lang'] ?? 'en';

// Load language strings
$lang_strings = include 'lang.php';

require_once 'connectiondb.php';



// Fetch student name
$stmt = $pdo->prepare("SELECT name FROM students WHERE id = ?");
$stmt->execute([$_SESSION['student_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
$student_name = $student ? $student['name'] : 'Student';

/**
 * Fetch exams assigned to the student with attempts and allowed_attempts,
 * including exams with attempts left and excluding exams completed more than 1 week ago.
 * Also fetch archived exams separately if needed.
 */
$stmt = $pdo->prepare("
    SELECT e.id, e.exam_name, e.duration, se.status, se.attempts, e.allowed_attempts, se.completed_at
    FROM exams e
    JOIN student_exams se ON e.id = se.exam_id
    WHERE se.student_id = ?
    AND (se.status != 'completed' OR se.completed_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK))
    ORDER BY e.exam_name
");
$stmt->execute([$_SESSION['student_id']]);
$exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Optionally, fetch archived exams completed more than 1 week ago
$stmtArchived = $pdo->prepare("
    SELECT e.id, e.exam_name, e.duration, se.status, se.attempts, e.allowed_attempts, se.completed_at
    FROM exams e
    JOIN student_exams se ON e.id = se.exam_id
    WHERE se.student_id = ?
    AND se.status = 'completed'
    AND se.completed_at < DATE_SUB(NOW(), INTERVAL 1 WEEK)
    ORDER BY se.completed_at DESC
");
$stmtArchived->execute([$_SESSION['student_id']]);
$archivedExams = $stmtArchived->fetchAll(PDO::FETCH_ASSOC);

// Fetch questions count for each exam
$exam_ids = array_column($exams, 'id');
$questions_count = [];
if (!empty($exam_ids)) {
    $placeholders = implode(',', array_fill(0, count($exam_ids), '?'));
    $stmt = $pdo->prepare("SELECT exam_id, COUNT(*) as qcount FROM questions WHERE exam_id IN ($placeholders) GROUP BY exam_id");
    $stmt->execute($exam_ids);
    $counts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($counts as $count) {
        $questions_count[$count['exam_id']] = $count['qcount'];
    }
}
?>
<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($lang); ?>">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Student Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        .exam-card:hover {
            box-shadow: 0 0 11px rgba(33,33,33,.2);
            cursor: pointer;
            transform: translateY(-3px);
            transition: all 0.3s ease;
        }
        .badge-assigned {
            background-color: #0d6efd;
        }
        .badge-completed {
            background-color: #198754;
        }
        .no-exams-illustration {
            max-width: 300px;
            margin: 20px auto;
            display: block;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">MCQ Exam Portal</a>
    <div class="d-flex align-items-center">

      <span class="navbar-text text-white me-3"><?php echo htmlspecialchars($lang_strings[$lang]['welcome']); ?>, <?php echo htmlspecialchars($student_name); ?></span>
      <form method="get" class="me-3">
        <select name="lang" onchange="this.form.submit()" class="form-select form-select-sm" aria-label="Select language">
          <option value="en" <?php if($lang === 'en') echo 'selected'; ?>>English</option>
          <option value="hi" <?php if($lang === 'hi') echo 'selected'; ?>>हिन्दी</option>
        </select>
      </form>
      <a href="student_logout.php" class="btn btn-outline-light btn-sm"><?php echo htmlspecialchars($lang_strings[$lang]['logout']); ?></a>
    </div>
  </div>
</nav>
<div class="container my-4">
<?php
// Check if student has any approved results to show the result button
$show_result_button = false;
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM student_exams WHERE student_id = ? AND status = 'completed' AND result_approved = 1");
    $stmt->execute([$_SESSION['student_id']]);
    $count = (int)$stmt->fetchColumn();
    if ($count > 0) {
        $show_result_button = true;
    }
} catch (PDOException $e) {
    // Fail silently, do not show button
    $show_result_button = false;
}

// Fetch notifications for student's exams
try {
    $stmtNotifs = $pdo->prepare("
        SELECT en.notification_text, en.created_at, e.exam_name
        FROM exam_notifications en
        JOIN exams e ON en.exam_id = e.id
        JOIN student_exams se ON se.exam_id = e.id
        WHERE se.student_id = ?
        ORDER BY en.created_at DESC
    ");
    $stmtNotifs->execute([$_SESSION['student_id']]);
    $notifications = $stmtNotifs->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $notifications = [];
}
?>
    <?php if ($show_result_button): ?>
    <div class="mb-3">
        <a href="student_result.php" class="btn btn-success">View Your Results</a>
    </div>
    <?php endif; ?>

    <?php
    // Fetch notifications for the logged-in student
    $stmtNotifications = $pdo->prepare("
        SELECT en.notification_text, en.created_at
        FROM exam_notifications en
        JOIN student_exams se ON en.exam_id = se.exam_id
        WHERE se.student_id = ?
        ORDER BY en.created_at DESC
        LIMIT 5
    ");
    $stmtNotifications->execute([$_SESSION['student_id']]);
    $notifications = $stmtNotifications->fetchAll(PDO::FETCH_ASSOC);
    $notificationCount = count($notifications);
    ?>
    <div class="d-flex justify-content-between align-items-center mb-2 position-relative">
        <h2><?php echo htmlspecialchars($lang_strings[$lang]['your_exams']); ?></h2>
        <div class="dropdown">
            <button class="btn btn-primary position-relative" type="button" id="notificationDropdown" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Notifications">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-bell" viewBox="0 0 16 16">
                    <path d="M8 16a2 2 0 0 0 1.985-1.75H6.015A2 2 0 0 0 8 16zm.104-14.995a1 1 0 0 0-2.208 0A5.002 5.002 0 0 0 3 6c0 1.098-.405 2.08-1.05 2.777-.6.63-.95 1.42-.95 2.223v.5a.5.5 0 0 0 .5.5h12a.5.5 0 0 0 .5-.5v-.5c0-.803-.35-1.593-.95-2.223C13.405 8.08 13 7.098 13 6a5.002 5.002 0 0 0-4.896-4.995z"/>
                </svg>
                <?php if ($notificationCount > 0): ?>
                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                        <?php echo $notificationCount; ?>
                        <span class="visually-hidden">unread notifications</span>
                    </span>
                <?php endif; ?>
            </button>
            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="notificationDropdown" style="min-width: 300px; max-height: 300px; overflow-y: auto; word-wrap: break-word; white-space: normal; word-break: break-word;">
                <?php if ($notificationCount === 0): ?>
                    <li class="dropdown-item text-center text-muted">No notifications</li>
                <?php else: ?>
                    <?php foreach ($notifications as $notification): ?>
                        <li class="dropdown-item text-wrap">
                            <div><?php echo htmlspecialchars($notification['notification_text']); ?></div>
                            <small class="text-muted"><?php echo date('M d, Y H:i', strtotime($notification['created_at'])); ?></small>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                    <?php endforeach; ?>
                <?php endif; ?>
            </ul>
        </div>
    </div>
    <input type="text" id="searchInput" class="form-control mb-4" placeholder="<?php echo htmlspecialchars($lang_strings[$lang]['search_exams']); ?>" aria-label="Search exams" />

    <div class="mb-3">
        <a href="student_previous_exams.php" class="btn btn-info">View Previous Completed Exams</a>
    </div>
    <div class="mb-3">
        <a href="student_attendance.php" class="btn btn-secondary">View Your Attendance</a>
    </div>

    <?php if (empty($exams)): ?>
        <div class="text-center">
            <img src="https://cdn-icons-png.flaticon.com/512/4076/4076549.png" alt="No exams" class="no-exams-illustration" style="max-width: 100px; margin: 20px auto; display: block;" />
            <p class="lead"><?php echo htmlspecialchars($lang_strings[$lang]['no_exams']); ?></p>
        </div>
    <?php else: ?>
        <div class="row" id="examsContainer">
            <?php foreach ($exams as $exam): ?>
            <?php
                // Determine if the exam should be shown as continue or re-exam based on attempts left
                $can_continue = ($exam['attempts'] < $exam['allowed_attempts']);
            ?>
            <div class="col-md-6 col-lg-4 mb-4 exam-card">
                <div class="card h-100 shadow-sm d-flex flex-column">
                    <div class="card-body d-flex flex-column">
                        <h5 class="card-title"><?php echo htmlspecialchars($exam['exam_name']); ?></h5>
                        <p class="card-text mb-2"><?php echo htmlspecialchars($lang_strings[$lang]['questions']); ?>: <?php echo isset($questions_count[$exam['id']]) ? $questions_count[$exam['id']] : 0; ?></p>
                        <p class="card-text mb-2">Duration: <?php echo htmlspecialchars($exam['duration']); ?> minutes</p>
                        <p class="card-text mb-2">Attempts Used: <?php echo htmlspecialchars($exam['attempts']); ?> / <?php echo htmlspecialchars($exam['allowed_attempts']); ?></p>
                        <?php if ($exam['status'] === 'assigned'): ?>
                            <?php if (!$can_continue): ?>
                                <span class="badge bg-danger text-white mb-3">Max Attempts Reached</span>
                                <button type="button" class="btn btn-secondary mt-auto" disabled title="You have reached the maximum number of attempts. Please contact admin for approval.">Start Exam</button>
                            <?php else: ?>
                                <span class="badge badge-assigned text-white mb-3"><?php echo htmlspecialchars($lang_strings[$lang]['assigned']); ?></span>
                                <button type="button" class="btn btn-primary mt-auto start-exam-btn" data-exam-id="<?php echo $exam['id']; ?>" data-bs-toggle="tooltip" data-bs-placement="top" title="Continue Exam">Continue Exam</button>
                            <?php endif; ?>
                        <?php elseif ($exam['status'] === 'completed'): ?>
                            <span class="badge badge-completed text-white mb-3"><?php echo htmlspecialchars($lang_strings[$lang]['completed']); ?></span>
                            <?php if ($can_continue): ?>
                                <button type="button" class="btn btn-warning mt-auto start-exam-btn" data-exam-id="<?php echo $exam['id']; ?>" data-bs-toggle="tooltip" data-bs-placement="top" title="Continue Exam">Continue Exam</button>
                            <?php else: ?>
                                <button type="button" class="btn btn-secondary mt-auto" disabled title="No attempts left for re-exam">Re-exam</button>
                            <?php endif; ?>
                        <?php else: ?>
                            <span class="badge bg-secondary mb-3"><?php echo htmlspecialchars($lang_strings[$lang]['unknown_status']); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php include 'student_dashboard_modal_terms.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Enable Bootstrap tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })

    // Search filter for exams
    const searchInput = document.getElementById('searchInput');
    const examsContainer = document.getElementById('examsContainer');
    const examCards = examsContainer ? examsContainer.getElementsByClassName('exam-card') : [];

    searchInput && searchInput.addEventListener('input', function() {
        const filter = this.value.toLowerCase();
        Array.from(examCards).forEach(card => {
            const title = card.querySelector('.card-title').textContent.toLowerCase();
            if (title.includes(filter)) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });
    });

    // Removed direct start exam button click handler to allow modal event delegation to handle it
</script>
</body>
</html>
