<?php
chdir('../');
session_start();
require_once('public/connection.php');

// Show PHP errors for development (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Ensure student is logged in
if (!isset($_SESSION['student_id'])) {
    header("Location: ../index.php");
    exit;
}

$student_id = $_SESSION['student_id'];

// Fetch student exam group results
$query = $conn->query("
    SELECT r.*, s.subjects AS subject_name
    FROM exam_group_results r
    JOIN school_subjects s ON r.subject = s.subjects
    WHERE r.student_id = $student_id
    ORDER BY r.session DESC
");
?>

<?php include('partials/header.php'); ?>
<?php include('partials/navbar.php'); ?>
<?php include('partials/sidebar.php'); ?>
<?php include('partials/alert.php'); ?>

<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h4 class="mb-0">My Exam Results</h4>
    </div>
  </div>
    <a href="print_results.php" target="_blank" class="btn btn-danger mb-3">
  <i class="fas fa-file-pdf"></i> Download PDF
</a>

  <div class="content">
    <div class="container-fluid">

      <?php if ($query && $query->num_rows > 0): ?>
        <div class="card">
          <div class="card-body table-responsive">
            <table class="table table-bordered table-striped">
              <thead class="table-dark">
                <tr>
                  <th>#</th>
                  <th>Subject</th>
                  <th>Term</th>
                  <th>Session</th>
                  <th>Objectives</th>
                  <th>Theory</th>
                  <th>Total Score</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php 
                $sn = 1;
                while ($row = $query->fetch_assoc()):
                ?>
                <tr>
                  <td><?= $student_id ?></td>
                  <td><?= htmlspecialchars($row['subject_name']) ?></td>
                  <td><?= htmlspecialchars($row['term']) ?></td>
                  <td><?= htmlspecialchars($row['session']) ?></td>
                  <td><?= htmlspecialchars($row['mcq_score'] ?? 0) ?></td>
                  <td><?= htmlspecialchars($row['theory_score'] ?? 0) ?></td>
                  <td><strong><?= htmlspecialchars($row['total'] ?? 0) ?></strong></td>
                  <td><?= htmlspecialchars($row['status'] ?? '-') ?></td>
                </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        </div>
      <?php else: ?>
        <div class="alert alert-info">You have no results yet.</div>
      <?php endif; ?>

    </div>
  </div>
</div>

<?php include('partials/footer.php'); ?>
