<?php
include('../includes/db.php');

if(!isset($_POST['id'])){
    exit('Invalid request');
}

$id = (int)$_POST['id'];

// Check if this course is part of any bundle
$res = mysqli_query($conn, "SELECT id, course_name FROM courses WHERE bundle_courses LIKE '%{$id}%'");
if($res && mysqli_num_rows($res) > 0){
    exit('Cannot delete: This course is included in a bundle.');
}

// Get current image
$curr = mysqli_query($conn, "SELECT image FROM courses WHERE id={$id} LIMIT 1");
$img = '';
if($curr && mysqli_num_rows($curr) > 0){
    $row = mysqli_fetch_assoc($curr);
    $img = $row['image'] ?? '';
}

// Delete database entry
mysqli_query($conn, "DELETE FROM courses WHERE id={$id}");

// Remove image file
if($img && file_exists('../uploads/courses/'.$img)){
    @unlink('../uploads/courses/'.$img);
}

echo 'success';
