<?php
require_once __DIR__ . "/auth.php";
require_role(['super','admin']);
require_once __DIR__ . "/../includes/db.php";

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

$message = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title'] ?? "");
    $course_name = trim($_POST['course_name'] ?? "");
    $unit_name   = trim($_POST['unit_exam'] ?? "");

    if ($title && $course_name && $unit_name) {
        // find or create course (column is course_name, not name)
        $st = $conn->prepare("SELECT id FROM courses WHERE course_name=? LIMIT 1");
        $st->bind_param("s", $course_name);
        $st->execute();
        $c = $st->get_result()->fetch_assoc();
        $st->close();

        if (!$c) {
            $ins = $conn->prepare("INSERT INTO courses(course_name) VALUES (?)");
            $ins->bind_param("s", $course_name);
            $ins->execute();
            $course_id = (int)$ins->insert_id;
            $ins->close();
        } else {
            $course_id = (int)$c['id'];
        }

        // find or create unit (units.name holds the label)
        $st = $conn->prepare("SELECT id FROM units WHERE course_id=? AND name=? LIMIT 1");
        $st->bind_param("is", $course_id, $unit_name);
        $st->execute();
        $u = $st->get_result()->fetch_assoc();
        $st->close();

        if (!$u) {
            $ins2 = $conn->prepare("INSERT INTO units(course_id, course_name, name) VALUES (?, ?, ?)");
            $ins2->bind_param("iss", $course_id, $course_name, $unit_name);
            $ins2->execute();
            $unit_id = (int)$ins2->insert_id;
            $ins2->close();
        } else {
            $unit_id = (int)$u['id'];
        }

        // insert exam (keeps legacy text fields for compatibility)
        $stmt = $conn->prepare(
          "INSERT INTO exams (title, course_id, unit_id, course_name, unit_exam)
           VALUES (?, ?, ?, ?, ?)"
        );
        $stmt->bind_param("siiss", $title, $course_id, $unit_id, $course_name, $unit_name);
        if ($stmt->execute()) {
            $message = "<div class='alert alert-success'>Exam created successfully!</div>";
        } else {
            $message = "<div class='alert alert-danger'>Error creating exam: " . htmlspecialchars($conn->error) . "</div>";
        }
        $stmt->close();
    } else {
        $message = "<div class='alert alert-warning'>Please fill in all fields.</div>";
    }
}

// dropdown: DISTINCT avoids duplicates
$courses = $conn->query("SELECT DISTINCT course_name FROM courses ORDER BY course_name ASC");
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Create Exam</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">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="bg-light">
<?php include __DIR__ . '/../includes/topbar.php'; ?>
<div class="container py-4">
    <h3>Create New Exam</h3>
    <?php echo $message; ?>
    <form method="post">
        <div class="mb-3">
            <label>Exam Title</label>
            <input type="text" name="title" class="form-control" placeholder="Enter exam title" required>
        </div>

        <div class="mb-3">
            <label>Course Name</label>
            <div class="input-group">
              <select name="course_name" id="course_name" class="form-select" required>
                <option value="">-- Select Course --</option>
                <?php if ($courses) while($r=$courses->fetch_assoc()): ?>
                  <option value="<?= htmlspecialchars($r['course_name']) ?>">
                    <?= htmlspecialchars($r['course_name']) ?>
                  </option>
                <?php endwhile; ?>
              </select>
              <a class="btn btn-outline-primary" href="courses.php" target="_blank">Manage</a>
            </div>
        </div>

        <div class="mb-3">
            <label>Unit Exam</label>
            <div class="input-group">
              <select name="unit_exam" id="unit_exam" class="form-select" required>
                <option value="">-- Select Unit --</option>
              </select>
              <button class="btn btn-outline-secondary" type="button" id="refreshUnits">↻</button>
            </div>
        </div>

        <button type="submit" class="btn btn-primary">Create Exam</button>
        <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
    </form>
</div>

<script>
function loadUnits(){
  const c = $('#course_name').val();
  if(!c){
    $('#unit_exam').html('<option value="">-- Select Unit --</option>');
    return;
  }
  $.get('get_units.php', { course_name: c }, function(html){
    $('#unit_exam').html(html || '<option value="">-- No units found --</option>');
  });
}
$('#course_name').on('change', loadUnits);
$('#refreshUnits').on('click', loadUnits);
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>