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

$lang = $_SESSION['lang'] ?? 'en';
$lang_strings = include 'lang.php';

require_once 'connectiondb.php';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// 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 completed more than 1 week ago
$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'
    AND se.completed_at < DATE_SUB(NOW(), INTERVAL 1 WEEK)
    ORDER BY se.completed_at DESC
");
$stmt->execute([$_SESSION['student_id']]);
$previous_exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch questions count for each exam
$exam_ids = array_column($previous_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>Previous Completed Exams - 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-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="student_dashboard.php">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>
      <a href="student_dashboard.php" class="btn btn-light btn-sm me-2">Back to Dashboard</a>
      <a href="student_logout.php" class="btn btn-outline-light btn-sm">Logout</a>
    </div>
  </div>
</nav>
<div class="container my-4">
    <h2 class="mb-4">Previous Completed Exams</h2>
    <?php if (empty($previous_exams)): ?>
        <div class="text-center">
            <img src="templates/no_exams.svg" alt="No previous exams" class="no-exams-illustration" />
            <p class="lead">No previous completed exams found.</p>
        </div>
    <?php else: ?>
        <div class="row" id="previousExamsContainer">
            <?php foreach ($previous_exams as $exam): ?>
            <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">Completed on: <?php echo htmlspecialchars(date('Y-m-d', strtotime($exam['completed_at']))); ?></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>
                        <span class="badge badge-completed text-white mb-3">Completed</span>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
