<?php
include '../../includes/conn.php';
include '../../includes/functions.php';
requireRole('teacher');

if (!isset($_GET['exam_id']) || !is_numeric($_GET['exam_id'])) {
    die("Exam ID not provided or invalid.");
}

$exam_id = intval($_GET['exam_id']);
$teacher_id = $_SESSION['user_id'] ?? 0;

try {
    // Check if the exam exists and belongs to this teacher
    $stmt = $pdo->prepare("SELECT status FROM cbt_exams WHERE id = ? AND teacher_id = ?");
    $stmt->execute([$exam_id, $teacher_id]);
    $exam = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$exam) {
        throw new Exception("Exam not found or access denied.");
    }

    // Toggle status
    $new_status = ($exam['status'] === 'active') ? 'inactive' : 'active';
    $update = $pdo->prepare("UPDATE cbt_exams SET status = ? WHERE id = ?");
    $update->execute([$new_status, $exam_id]);

    // Redirect with success message
    header("Location: manage_exams.php?status_updated=1");
    exit;

} catch (Exception $e) {
    // Simple error display (could be improved by redirecting with error parameter)
    die("Error: " . htmlspecialchars($e->getMessage()));
}
