<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

if (!isset($_GET['exam_id']) || !is_numeric($_GET['exam_id'])) {
    header('Location: admin_dashboard.php');
    exit;
}

$exam_id = (int)$_GET['exam_id'];

require_once 'connectiondb.php';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Delete related student answers
    $stmt = $pdo->prepare("DELETE sa FROM student_answers sa JOIN questions q ON sa.question_id = q.id WHERE q.exam_id = ?");
    $stmt->execute([$exam_id]);

    // Delete related questions
    $stmt = $pdo->prepare("DELETE FROM questions WHERE exam_id = ?");
    $stmt->execute([$exam_id]);

    // Delete the exam
    $stmt = $pdo->prepare("DELETE FROM exams WHERE id = ?");
    $stmt->execute([$exam_id]);

    header('Location: admin_dashboard.php?msg=Exam+deleted+successfully');
    exit;
} catch (PDOException $e) {
    die("Error deleting exam: " . $e->getMessage());
}
?>
