<?php
// school_admission/public/admin_delete_course_action.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php';

requireRole(['super_admin']); // Only Super Admin can delete courses

$course_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($course_id === 0) {
    $_SESSION['message'] = "<div class='message error'>Invalid course ID.</div>";
    redirect('admin_manage_courses.php');
}

// Check if there are any applicants enrolled in this course first
$can_delete = true;
$error_reason = "";

$stmt_check_applicants = $conn->prepare("SELECT COUNT(*) FROM applicants WHERE course_id = ?");
$stmt_check_applicants->bind_param("i", $course_id);
$stmt_check_applicants->execute();
$stmt_check_applicants->bind_result($applicant_count);
$stmt_check_applicants->fetch();
$stmt_check_applicants->close();

if ($applicant_count > 0) {
    $can_delete = false;
    $error_reason = "There are " . $applicant_count . " applicants enrolled in this course. You cannot delete a course with active applications.";
}

if ($can_delete) {
    $stmt = $conn->prepare("DELETE FROM courses WHERE course_id = ?");
    $stmt->bind_param("i", $course_id);

    if ($stmt->execute()) {
        $_SESSION['message'] = "<div class='message success'>Course deleted successfully!</div>";
    } else {
        $_SESSION['message'] = "<div class='message error'>Error deleting course: " . $stmt->error . "</div>";
    }
    $stmt->close();
} else {
    $_SESSION['message'] = "<div class='message error'>Cannot delete course: " . $error_reason . "</div>";
}

redirect('admin_manage_courses.php');
$conn->close();
?>