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

$exam_id = (int)($_POST['exam_id'] ?? $_GET['exam_id'] ?? $_GET['id'] ?? 0);
if ($exam_id <= 0) { $_SESSION['flash']=['type'=>'danger','text'=>'Missing exam id.']; header("Location: dashboard.php"); exit; }

$st = $conn->prepare("SELECT id FROM exams WHERE id=? LIMIT 1");
$st->bind_param("i", $exam_id);
$st->execute(); $st->store_result();
if ($st->num_rows === 0) { $_SESSION['flash']=['type'=>'warning','text'=>'Exam not found.']; header("Location: dashboard.php"); exit; }

$conn->begin_transaction();
try {
  $stmt = $conn->prepare("DELETE FROM results WHERE exam_id=?");   $stmt->bind_param("i",$exam_id); $stmt->execute();
  $stmt = $conn->prepare("DELETE FROM questions WHERE exam_id=?"); $stmt->bind_param("i",$exam_id); $stmt->execute();
  $stmt = $conn->prepare("DELETE FROM exams WHERE id=?");          $stmt->bind_param("i",$exam_id); $stmt->execute();

  $conn->commit();
  $_SESSION['flash']=['type'=>'warning','text'=>'Exam deleted.'];
} catch (Throwable $e) {
  $conn->rollback();
  $_SESSION['flash']=['type'=>'danger','text'=>'Delete failed: '.$conn->error];
}
header("Location: dashboard.php"); exit;
