<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

require_once 'db.php';

// ✅ Ensure program ID is provided
if (isset($_GET['id'])) {
    $program_id = $_GET['id'];

    // ✅ Step 1: Get the slot_number of the program being deleted
    $stmt = $pdo->prepare("SELECT slot_number FROM programs WHERE id = ?");
    $stmt->execute([$program_id]);
    $slot_number = $stmt->fetchColumn();

    if ($slot_number) {
        // ✅ Step 2: Remove associated user IDs from users table
        $program_column = "program_" . $slot_number;
        $stmt = $pdo->prepare("UPDATE users SET $program_column = NULL WHERE $program_column IS NOT NULL");
        $stmt->execute();
    }

    // ✅ Step 3: Delete the program from the programs table
    $stmt = $pdo->prepare("DELETE FROM programs WHERE id = ?");
    $stmt->execute([$program_id]);

    echo "<script>
        alert('✅ Program Deleted!');
        window.location.href = 'admin.php';
    </script>";
} else {
    echo "❌ Program ID is missing.";
}
?>
