<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/config.php';

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

if ($id <= 0) {
    header('Location: list.php?message=not_found');
    exit;
}

$stmt = $conn->prepare("SELECT image FROM categories WHERE id = ? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$category = $result->fetch_assoc();

if (!$category) {
    header('Location: list.php?message=not_found');
    exit;
}

if (!empty($category['image'])) {
    $image_file = __DIR__ . '/../' . $category['image'];
    if (file_exists($image_file)) {
        @unlink($image_file);
    }
}

$delete_stmt = $conn->prepare("DELETE FROM categories WHERE id = ?");
$delete_stmt->bind_param("i", $id);
$delete_stmt->execute();

header('Location: list.php?message=deleted');
exit;