<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$examId = intval($_POST['exam_id'] ?? 0);

if (!$examId) {
    $_SESSION['error_message'] = 'Invalid exam ID';
    header('Location: index.php');
    exit;
}

try {
    $db->beginTransaction();

    // Check if exam exists and belongs to current instructor
    $stmt = $db->prepare("SELECT id, title FROM exams WHERE id = ? AND instructor_id = ?");
    $stmt->execute([$examId, $userId]);
    $exam = $stmt->fetch();

    if (!$exam) {
        throw new Exception('Exam not found or you do not have permission to delete it');
    }

    // Check if exam has attempts
    $stmt = $db->prepare("SELECT COUNT(*) as attempt_count FROM exam_attempts WHERE exam_id = ?");
    $stmt->execute([$examId]);
    $attemptCount = $stmt->fetch()['attempt_count'];

    if ($attemptCount > 0) {
        throw new Exception('Cannot delete exam that has been attempted by students');
    }

    // Delete exam questions first (due to foreign key constraints)
    $stmt = $db->prepare("DELETE FROM exam_questions WHERE exam_id = ?");
    $stmt->execute([$examId]);

    // Delete exam assignments
    $stmt = $db->prepare("DELETE FROM exam_access WHERE exam_id = ?");
    $stmt->execute([$examId]);

    // Delete the exam
    $stmt = $db->prepare("DELETE FROM exams WHERE id = ? AND instructor_id = ?");
    $stmt->execute([$examId, $userId]);

    $db->commit();

    // Log the activity
    logUserActivity($userId, 'exam_deleted', 'Deleted exam: ' . $exam['title']);

    $_SESSION['success_message'] = 'Exam deleted successfully!';

} catch (Exception $e) {
    $db->rollBack();
    $_SESSION['error_message'] = 'Error deleting exam: ' . $e->getMessage();
}

header('Location: index.php');
exit;
?>