0, 'name' => '', 'slug' => '', 'description' => '', 'icon' => 'fas fa-tag', 'image' => '', 'status' => 1]; if ($id) { $stmt = $db->prepare("SELECT * FROM categories WHERE id = ?"); $stmt->execute([$id]); $category = $stmt->fetch(PDO::FETCH_ASSOC); if (!$category) { admin_set_flash('error', 'Category not found'); header('Location: ' . ADMIN_PATH . 'pages/categories.php'); exit; } $page_title = 'Edit Category'; } if ($_SERVER['REQUEST_METHOD'] == 'POST' && verify_csrf($_POST[CSRF_TOKEN_NAME] ?? '')) { $name = trim($_POST['name']); $slug = !empty($_POST['slug']) ? create_slug($_POST['slug']) : create_slug($name); $description = trim($_POST['description'] ?? ''); $icon = trim($_POST['icon'] ?? 'fas fa-tag'); $status = intval($_POST['status']); $image = $category['image'] ?? ''; if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) { $new_image = upload_image($_FILES['image'], 'categories', $name); if ($new_image) $image = $new_image; } try { if ($id) { $stmt = $db->prepare("UPDATE categories SET name=?, slug=?, description=?, icon=?, image=?, status=? WHERE id=?"); $stmt->execute([$name, $slug, $description, $icon, $image, $status, $id]); admin_set_flash('success', 'Category updated'); } else { $stmt = $db->prepare("INSERT INTO categories (name, slug, description, icon, image, status) VALUES (?, ?, ?, ?, ?, ?)"); $stmt->execute([$name, $slug, $description, $icon, $image, $status]); admin_set_flash('success', 'Category added'); } header('Location: ' . ADMIN_PATH . 'pages/categories.php'); exit; } catch (Exception $e) { if (strpos($e->getMessage(), 'Duplicate') !== false) { $error = 'A category with this slug already exists.'; } else { $error = 'Failed: ' . $e->getMessage(); } } } ?>