<?php
// admin/delete-category.php (Fallback if JavaScript fails)
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

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

if ($id <= 0) {
    $_SESSION['error_msg'] = 'Invalid category ID';
    header('Location: categories.php');
    exit;
}

// Get category
$stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
$stmt->execute([$id]);
$category = $stmt->fetch();

if (!$category) {
    $_SESSION['error_msg'] = 'Category not found';
    header('Location: categories.php');
    exit;
}

try {
    // Delete image
    if ($category['image']) {
        $image_path = __DIR__ . '/../assets/images/categories/' . $category['image'];
        if (file_exists($image_path)) {
            unlink($image_path);
        }
    }
    
    // Delete category
    $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
    $stmt->execute([$id]);
    
    $_SESSION['success_msg'] = 'Category "' . $category['name'] . '" deleted successfully!';
    header('Location: categories.php');
    exit;
    
} catch (Exception $e) {
    $_SESSION['error_msg'] = 'Error deleting category: ' . $e->getMessage();
    header('Location: categories.php');
    exit;
}
?>