<?php
// delete_course.php
// Handles the deletion of a course.

// Ensure session is started.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and is an admin.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'admin') {
    header("Location: index.php?page=login&error=unauthorized");
    exit();
}

require_once 'config/database.php';

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

if ($course_id > 0) {
    try {
        // First, check if there are any batches or enrollments associated with this course
        $stmt_check = $pdo->prepare("
            SELECT COUNT(id) FROM batches WHERE course_id = ?
        ");
        $stmt_check->execute([$course_id]);
        $batch_count = $stmt_check->fetchColumn();

        if ($batch_count > 0) {
            // Redirect with an error message if the course has active batches
            $_SESSION['message'] = "Cannot delete the course. It is associated with " . $batch_count . " batch(es).";
            $_SESSION['is_error'] = true;
            header("Location: index.php?page=manage_courses");
            exit();
        }

        // Proceed with deletion if no batches are found
        $stmt_delete = $pdo->prepare("DELETE FROM courses WHERE id = ?");
        $stmt_delete->execute([$course_id]);

        if ($stmt_delete->rowCount() > 0) {
            $_SESSION['message'] = "Course deleted successfully.";
            $_SESSION['is_error'] = false;
        } else {
            $_SESSION['message'] = "Course not found or could not be deleted.";
            $_SESSION['is_error'] = true;
        }

    } catch (PDOException $e) {
        $_SESSION['message'] = "Database error: " . $e->getMessage();
        $_SESSION['is_error'] = true;
        error_log("Course Deletion Error: " . $e->getMessage());
    }
} else {
    $_SESSION['message'] = "Invalid course ID.";
    $_SESSION['is_error'] = true;
}

header("Location: index.php?page=manage_courses");
exit();