<?php
session_start();
require_once "../includes/db.php";
if (!isset($_SESSION['admin'])) { header("Location: index.php"); exit; }

$mode = $_GET['mode'] ?? $_POST['mode'] ?? 'single';
$mode = ($mode === 'bulk') ? 'bulk' : 'single';

$exams = $conn->query("SELECT id, title, course_name, unit_exam FROM exams ORDER BY course_name, unit_exam, id DESC");
$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $exam_id = (int)($_POST['exam_id'] ?? 0);

  if ($exam_id > 0) {
    if ($mode === 'bulk') {
      header("Location: bulk_upload_questions.php?exam_id=" . $exam_id);
      exit;
    } else {
      header("Location: add_question.php?exam_id=" . $exam_id);
      exit;
    }
  } else {
    $message = "<div class='alert alert-warning'>Please select an exam.</div>";
  }
}

$pageTitle = ($mode === 'bulk') ? 'Select Exam for Bulk Upload Questions' : 'Select Exam for Single Questions';
$btnText   = ($mode === 'bulk') ? 'Continue to Bulk Upload' : 'Continue to Single Questions';
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title><?= htmlspecialchars($pageTitle) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body{
      background:#f4f7fb;
    }
    .select-card{
      border:0;
      border-radius:18px;
      box-shadow:0 16px 36px rgba(10,27,66,.10);
    }
  </style>
</head>
<body>
<?php include __DIR__ . '/../includes/topbar.php'; ?>

<div class="container py-4" style="max-width:760px;">
  <div class="card select-card">
    <div class="card-body p-4">
      <h3 class="mb-3"><?= htmlspecialchars($pageTitle) ?></h3>

      <?= $message ?>

      <form method="post">
        <input type="hidden" name="mode" value="<?= htmlspecialchars($mode) ?>">

        <div class="mb-3">
          <label class="form-label fw-semibold">Exam</label>
          <select class="form-select" name="exam_id" required>
            <option value="">-- Select Exam --</option>
            <?php if ($exams) while($e = $exams->fetch_assoc()): ?>
              <option value="<?= (int)$e['id'] ?>">
                <?= htmlspecialchars($e['title'] . " — " . $e['course_name'] . " / " . $e['unit_exam']) ?>
              </option>
            <?php endwhile; ?>
          </select>
        </div>

        <div class="d-flex gap-2">
          <button class="btn btn-primary"><?= htmlspecialchars($btnText) ?></button>
          <a class="btn btn-secondary" href="dashboard.php">Cancel</a>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('.dropdown-toggle').forEach(function (el) {
    new bootstrap.Dropdown(el);
  });
});
</script>
</body>
</html>