<?php
session_start();
include "../include/config.php";

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    $conn->begin_transaction();
    
    try {
        $programDeleteSql = "DELETE FROM course_programs WHERE course_id = $id";
        if (!$conn->query($programDeleteSql)) {
            throw new Exception("Error deleting program associations: " . $conn->error);
        }
        
        $courseDeleteSql = "DELETE FROM course WHERE id = $id";
        if ($conn->query($courseDeleteSql)) {
            $conn->commit();
            header("Location: course.php?success=Course deleted successfully");
        } else {
            throw new Exception("Error deleting course: " . $conn->error);
        }
    } catch (Exception $e) {
        $conn->rollback();
        header("Location: course.php?error=" . urlencode($e->getMessage()));
    }
} else {
    header("Location: course.php");
}
?>