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

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

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

$student_id = (int) $_SESSION['student_id'];

// fetch student
$stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$student) {
    echo "<div class='alert alert-danger'>Student not found.</div>";
    include('partials/footer.php');
    exit;
}
$student_class = $student['class'] ?? '';

// sanitize search param
$search = trim($_GET['search'] ?? '');
$search_sql = '';
$params = [];
$types = '';

if ($search !== '') {
    $search_like = '%' . $search . '%';
    $search_sql = " AND (
        e.exam_type LIKE ? OR 
        s.subjects LIKE ? OR 
        e.term LIKE ? OR 
        e.session LIKE ?
    ) ";
    $params = [$search_like, $search_like, $search_like, $search_like];
    $types = 'ssss';
}

// Query exams with prepared statement
$query = "
  SELECT 
    e.id, e.questtype, e.exam_date, e.hasmcq, e.hastheory, e.duration_minutes, e.duration_minutes2, e.exam_type, e.class, e.term, e.session, s.subjects 
  FROM exams e
  LEFT JOIN school_subjects s ON e.subject_id = s.id
  WHERE e.class = ? AND e.status = 'active' {$search_sql}
  ORDER BY e.exam_date ASC
";
$types = 's' . $types;
$params = array_merge([$student_class], $params);

$stmt = $conn->prepare($query);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$available_exams = $stmt->get_result();
?>

<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1 class="m-0">Available Exams</h1>
        </div>
      </div>
    </div>
  </div>

  <div class="content">
    <div class="container-fluid">
      <form method="get" class="mb-3">
        <div class="input-group" style="max-width: 400px;">
          <input type="text" name="search" class="form-control" placeholder="Search exams..." value="<?= htmlspecialchars($search) ?>">
          <button type="submit" class="btn btn-primary">Search</button>
        </div>
      </form>

      <?php if ($available_exams && $available_exams->num_rows): ?>
        <div class="table-responsive">
          <table class="table table-striped table-hover">
            <thead class="thead-dark">
              <tr>
                <th>Exam Title</th>
                <th>Exam Date</th>
                <th>Duration</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php while ($exam = $available_exams->fetch_assoc()):
                $exam_id = (int)$exam['id'];
                $hasmcq = $exam['hasmcq'] ?? 'NO';
                $hastheory = $exam['hastheory'] ?? 'NO';

                // count theory and mcq questions (safe prepared)
                $qstmt = $conn->prepare("SELECT COUNT(*) AS total_theory FROM questions WHERE exam_id = ? AND question_type = 'theory'");
                $qstmt->bind_param("i", $exam_id);
                $qstmt->execute();
                $theorycount = $qstmt->get_result()->fetch_assoc()['total_theory'] ?? 0;
                $qstmt->close();

                $qstmt2 = $conn->prepare("SELECT COUNT(*) AS mcq FROM questions WHERE exam_id = ? AND question_type = 'mcq'");
                $qstmt2->bind_param("i", $exam_id);
                $qstmt2->execute();
                $mcq = $qstmt2->get_result()->fetch_assoc()['mcq'] ?? 0;
                $qstmt2->close();

                $qtype = $exam['questtype'] ?? '';
                if ($qtype === 'mcq') { $guesttype = 'Multiple Choice Question'; }
                elseif ($qtype === 'theory') { $guesttype = 'Theory'; }
                else { $guesttype = ucfirst($qtype); }

                // attempted exams for this student and qtype: do one query per type (efficient enough)
                $attempted_mcq = [];
                $attempted_theory = [];

                $rstmt = $conn->prepare("SELECT exam_id, qtype FROM student_exam_attempts WHERE student_id = ?");
                $rstmt->bind_param("i", $student_id);
                $rstmt->execute();
                $res = $rstmt->get_result();
                while ($r = $res->fetch_assoc()) {
                    if ($r['qtype'] === 'mcq') $attempted_mcq[] = (int)$r['exam_id'];
                    if ($r['qtype'] === 'theory') $attempted_theory[] = (int)$r['exam_id'];
                }
                $rstmt->close();
              ?>
                <?php if (strtoupper($hasmcq) === 'YES'): ?>
                <tr>
                  <td>
                    <?= htmlspecialchars($exam['exam_type'] ?? '') ?> |
                    <?= htmlspecialchars($exam['class'] ?? '') ?> |
                    <?= htmlspecialchars($exam['subjects'] ?? 'Not Available') ?> |
                    <?= htmlspecialchars($exam['term'] ?? '') ?> |
                    <?= htmlspecialchars($exam['session'] ?? '') ?> |
                    Multi Choice
                  </td>
                  <td><?= htmlspecialchars(date('F j, Y', strtotime($exam['exam_date'] ?? '')) ) ?></td>
                  <td><?= htmlspecialchars((int)$exam['duration_minutes2']) ?> mins</td>
                  <td>
                    <?php if (in_array($exam_id, $attempted_mcq)): ?>
                      <button class="btn btn-secondary" disabled>Attempted</button>
                    <?php else: ?>
                      <a href="start_exam.php?exam_id=<?= $exam_id ?>&type=mcq" class="btn btn-success">Start Exam</a>
                    <?php endif; ?>
                  </td>
                </tr>
                <?php endif; ?>

                <?php if (strtoupper($hastheory) === 'YES'): ?>
                <tr>
                  <td>
                    <?= htmlspecialchars($exam['exam_type'] ?? '') ?> |
                    <?= htmlspecialchars($exam['class'] ?? '') ?> |
                    <?= htmlspecialchars($exam['subjects'] ?? 'Not Available') ?> |
                    <?= htmlspecialchars($exam['term'] ?? '') ?> |
                    <?= htmlspecialchars($exam['session'] ?? '') ?> |
                    Theory
                  </td>
                  <td><?= htmlspecialchars(date('F j, Y', strtotime($exam['exam_date'] ?? '')) ) ?></td>
                  <td><?= htmlspecialchars((int)$exam['duration_minutes']) ?> mins</td>
                  <td>
                    <?php if (in_array($exam_id, $attempted_theory)): ?>
                      <button class="btn btn-secondary" disabled>Attempted</button>
                    <?php else: ?>
                      <a href="start_exam.php?exam_id=<?= $exam_id ?>&type=theory" class="btn btn-success">Start Exam</a>
                    <?php endif; ?>
                  </td>
                </tr>
                <?php endif; ?>

              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      <?php else: ?>
        <div class="alert alert-warning text-center">No active exams found for your class at this time.</div>
      <?php endif; ?>
    </div>
  </div>
</div>

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