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

$stmt = $dbh->prepare("SELECT a.*, e.title, s.session_year, t.term_name, sub.name as subject FROM exam_attempts a
    JOIN exams e ON e.id = a.exam_id
    JOIN sessions s ON s.id = e.session_id
    JOIN terms t ON t.id = e.term_id
    JOIN Subjects sub ON sub.id = e.subject_id
    WHERE a.student_id = :sid ORDER BY a.started_at DESC");
$stmt->execute([':sid'=>$student_id]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html><head><meta charset="utf-8"><title>My Results</title>
<script src="https://cdn.tailwindcss.com"></script>
</head><body class="bg-gray-100 p-6">
  <div class="max-w-5xl mx-auto">
    <h1 class="text-2xl font-semibold mb-4">My Exam Attempts</h1>
    <?php if(!$rows): ?>
      <div class="bg-white p-4 rounded">No attempts yet.</div>
    <?php else: ?>
      <table class="min-w-full bg-white rounded overflow-hidden">
        <thead class="bg-gray-100"><tr>
          <th class="p-2">Exam</th><th class="p-2">Subject</th><th class="p-2">Started</th><th class="p-2">Submitted</th><th class="p-2">Score</th><th class="p-2">Action</th>
        </tr></thead>
        <tbody>
          <?php foreach($rows as $r): ?>
            <tr class="border-t">
              <td class="p-2"><?=htmlspecialchars($r['title'])?></td>
              <td class="p-2"><?=htmlspecialchars($r['subject'])?></td>
              <td class="p-2"><?=htmlspecialchars($r['started_at'])?></td>
              <td class="p-2"><?=htmlspecialchars($r['submitted_at'] ?? '-')?></td>
              <td class="p-2"><?=htmlspecialchars($r['score'] ?? '-')?></td>
              <td class="p-2">
                <a href="student_view_attempt.php?attempt_id=<?=$r['id']?>" class="text-sm bg-blue-600 text-white px-3 py-1 rounded">View</a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>
</body></html>
