<?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 = $_SESSION['student_id'];
$student = $conn->query("SELECT * FROM students WHERE id = $student_id")->fetch_assoc();
$student_class = $student['class'];

$search = $_GET['search'] ?? '';
$search_sql = $search ? "AND (
  e.exam_type LIKE '%$search%' OR 
  s.subjects LIKE '%$search%' OR 
  e.term LIKE '%$search%' OR 
  e.session LIKE '%$search%'
)" : '';

// JOIN subjects to fetch subject name and build exam title from pieces
$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
";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $student_class);
$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->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()):
              $examids = htmlspecialchars($exam['id'] ?? '');
              $hasmcq = htmlspecialchars($exam['hasmcq'] ?? '');
              $hastheory = htmlspecialchars($exam['hastheory'] ?? '');
             
             // Query to count theory questions
$query3 = "
    SELECT COUNT(*) AS total_theory 
    FROM questions 
    WHERE exam_id = '$examids' 
      AND question_type = 'theory'
";

$result = mysqli_query($conn, $query3);
if ($result && $row = mysqli_fetch_assoc($result)) {
    $theorycount = $row['total_theory'];
} else {
    $theorycount = 0;
}

$query2 = "
    SELECT COUNT(*) AS mcq 
    FROM questions 
    WHERE exam_id = '$examids' 
      AND question_type = 'mcq'
";
$result2 = mysqli_query($conn, $query2);
if ($result2 && $row2 = mysqli_fetch_assoc($result2)) {
    $mcq = $row2['mcq'];
} else {
    $mcq = 0;
}

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

$totalquest = $mcq + $theorycount;
?>

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

<?php if ($hastheory === 'YES'): 
$attempted_exams = [];
$res = $conn->query("SELECT exam_id FROM student_exam_attempts WHERE student_id = $student_id AND qtype = 'theory'");
while ($r = $res->fetch_assoc()) {
  $attempted_exams[] = $r['exam_id'];
}
?> 
<tr>
  <td>
    <?= htmlspecialchars($exam['exam_type'] ?? '') ?> |
    <?= htmlspecialchars($exam['class'] ?? '') ?> |
    <?= htmlspecialchars($exam['subjects'] ?? 'Not Available') ?> |
    <?= htmlspecialchars($exam['term'] ?? '') ?> |
    <?= htmlspecialchars($exam['session'] ?? '') ?> |
    Theory
  </td>
  <td><?= date('F j, Y', strtotime($exam['exam_date'] ?? '')) ?></td>
  <td><?= htmlspecialchars($exam['duration_minutes'] ?? '0') ?> mins</td>
  <td>
    <?php if (in_array($exam['id'], $attempted_exams)): ?>
      <button class="btn btn-secondary" disabled>Attempted</button>
    <?php else: ?>
      <a href="start_exam.php?exam_id=<?= htmlspecialchars($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'); ?>
