// Handle Blog Category Deletion (Alternative for category name)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_category'])) {
    $category_id = trim($_POST['category_id'] ?? '');
    
    // Validate category ID
    if (empty($category_id) || !is_numeric($category_id)) {
        $errors[] = "Invalid category ID.";
    } else {
        // Start transaction for data integrity
        $conn->begin_transaction();
        try {
            // Check if category exists
            $stmt = $conn->prepare("SELECT image, name FROM blog_category WHERE id = ?");
            $stmt->bind_param("i", $category_id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows === 0) {
                $errors[] = "Blog Category not found.";
            } else {
                $category = $result->fetch_assoc();
                $image_path = $category['image'];
                $category_name = $category['name'];
                
                // Check if category is used in blogs
                $stmt = $conn->prepare("SELECT id FROM blogs WHERE category = ?");
                $stmt->bind_param("s", $category_name);
                $stmt->execute();
                $blog_result = $stmt->get_result();
                if ($blog_result->num_rows > 0) {
                    $errors[] = "Cannot delete category because it is used by " . $blog_result->num_rows . " blog(s).";
                } else {
                    // Delete category
                    $stmt = $conn->prepare("DELETE FROM blog_category WHERE id = ?");
                    $stmt->bind_param("i", $category_id);
                    if ($stmt->execute()) {
                        // Delete associated image file
                        if (!empty($image_path) && file_exists($image_path)) {
                            if (!unlink($image_path)) {
                                $errors[] = "Failed to delete category image file.";
                            }
                        }
                        $success = "Blog Category deleted successfully!";
                        $conn->commit();
                    } else {
                        $errors[] = "Failed to delete category: " . $conn->error;
                        $conn->rollback();
                    }
                }
            }
            $stmt->close();
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Deletion failed due to an unexpected error: " . $e->getMessage();
        }
    }
}