<?php
/**
 * Admin - Delete Blog Category
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'admin/blog-categories.php', 'error', 'Invalid request');
}

if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
    redirect(BASE_URL . 'admin/blog-categories.php', 'error', 'Invalid security token');
}

$category_id = intval($_POST['category_id'] ?? 0);

if (!$category_id) {
    redirect(BASE_URL . 'admin/blog-categories.php', 'error', 'Invalid category ID');
}

try {
    // Check if category exists
    $stmt = db()->prepare("SELECT name FROM blog_categories WHERE id = ?");
    $stmt->execute([$category_id]);
    $category = $stmt->fetch();
    
    if (!$category) {
        redirect(BASE_URL . 'admin/blog-categories.php', 'error', 'Category not found');
    }
    
    // Check if category has posts
    $stmt = db()->prepare("SELECT COUNT(*) as count FROM blog_posts WHERE category_id = ?");
    $stmt->execute([$category_id]);
    $posts_count = $stmt->fetch()['count'];
    
    if ($posts_count > 0) {
        redirect(BASE_URL . 'admin/blog-categories.php', 'error', 'Cannot delete category with posts. Move or delete posts first.');
    }
    
    // Delete category
    $stmt = db()->prepare("DELETE FROM blog_categories WHERE id = ?");
    $stmt->execute([$category_id]);
    
    // Log activity
    log_activity('blog_category_deleted', "Deleted blog category: {$category['name']}", $_SESSION['admin_id'], 'admin');
    
    redirect(BASE_URL . 'admin/blog-categories.php', 'success', 'Blog category deleted successfully');
    
} catch (PDOException $e) {
    error_log("Delete blog category error: " . $e->getMessage());
    redirect(BASE_URL . 'admin/blog-categories.php', 'error', 'Failed to delete blog category');
}
