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

/* Read exam id (prefer exam_id; accept id as fallback; POST or GET) */
$exam_id = (int)($_POST['exam_id'] ?? $_GET['exam_id'] ?? $_GET['id'] ?? 0);
if ($exam_id <= 0) die("Missing exam id.");

$msg = '';
if ($_SERVER['REQUEST_METHOD']==='POST') {
  $title = trim($_POST['title'] ?? '');
  $course= trim($_POST['course_name'] ?? '');
  $unit  = trim($_POST['unit_exam'] ?? '');
  $total = (int)($_POST['total_questions'] ?? 0); if ($total <= 0) $total = 40;

  $st = $conn->prepare("UPDATE exams SET title=?, course_name=?, unit_exam=?, total_questions=? WHERE id=?");
  $st->bind_param("sssii", $title,$course,$unit,$total,$exam_id);
  $msg = $st->execute() ? "Exam updated." : ("Error: ".$conn->error);
}

/* fetch */
$st = $conn->prepare("SELECT * FROM exams WHERE id=? LIMIT 1");
$st->bind_param("i", $exam_id);
$st->execute();
$ex = $st->get_result()->fetch_assoc();
if (!$ex) die("Exam not found.");
?>
<!DOCTYPE html>
<html>
<head>
  <title>Edit Exam</title>
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
<div class="container">
  <h3>Edit Exam</h3>
  <?php if($msg) echo '<div class="alert alert-info">'.htmlspecialchars($msg).'</div>'; ?>
  <form method="post" action="edit_exam.php?exam_id=<?= (int)$exam_id ?>">
    <input type="hidden" name="exam_id" value="<?= (int)$exam_id ?>">
    <div class="mb-2">
      <label class="form-label">Title</label>
      <input class="form-control" name="title" value="<?= htmlspecialchars($ex['title']) ?>" required>
    </div>
    <div class="mb-2">
      <label class="form-label">Course</label>
      <input class="form-control" name="course_name" value="<?= htmlspecialchars($ex['course_name']) ?>" required>
    </div>
    <div class="mb-2">
      <label class="form-label">Unit Exam</label>
      <input class="form-control" name="unit_exam" value="<?= htmlspecialchars($ex['unit_exam']) ?>" required>
    </div>
    <div class="mb-2">
      <label class="form-label">Total Questions</label>
      <input type="number" class="form-control" name="total_questions" value="<?= (int)$ex['total_questions'] ?>">
    </div>
    <button class="btn btn-primary">Save Changes</button>
    <a class="btn btn-secondary" href="dashboard.php">Back</a>
  </form>
</div>
</body>
</html>
