<?php
// Debugging (Remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

// Security Check: Redirect to login page if not logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

require_once '../db_connect.php';

// Check if the exam ID is provided in the URL
if (isset($_GET['id']) && !empty($_GET['id'])) {
    $exam_id = (int)$_GET['id'];

    try {
        // Start Transaction to ensure data integrity
        $pdo->beginTransaction();

        // 1. Delete student responses linked to the results of this exam
        $stmt_resp = $pdo->prepare("DELETE FROM student_responses WHERE result_id IN (SELECT id FROM exam_result WHERE exam_id = ?)");
        $stmt_resp->execute([$exam_id]);

        // 2. Delete all results associated with this exam
        $stmt_res = $pdo->prepare("DELETE FROM exam_result WHERE exam_id = ?");
        $stmt_res->execute([$exam_id]);

        // 3. Delete all questions associated with this exam
        $stmt_q = $pdo->prepare("DELETE FROM questions WHERE exam_id = ?");
        $stmt_q->execute([$exam_id]);

        // 4. Finally, delete the exam itself from the exams table
        $stmt_exam = $pdo->prepare("DELETE FROM exams WHERE id = ?");
        $stmt_exam->execute([$exam_id]);

        // Commit the transaction (Permanently apply the deletions)
        $pdo->commit();

        // Redirect back to the manage exams page with a success message
        header("Location: manage_exams.php?msg=deleted");
        exit;

    } catch (PDOException $e) {
        // If any error occurs, rollback the changes so no partial data is deleted
        $pdo->rollBack();
        die("<div style='text-align:center; padding:50px; font-family:sans-serif;'>
                <h2 style='color:red;'>Database Error!</h2>
                <p>" . $e->getMessage() . "</p>
                <a href='manage_exams.php'>Go Back</a>
             </div>");
    }
} else {
    // If no ID is provided, redirect back to the manage exams page
    header("Location: manage_exams.php");
    exit;
}
?>