render('layout.twig', ['active_page' => 'categories']); } // Get single category (JSON) public static function getCategory($id) { header('Content-Type: application/json'); try { $db = Database::getInstance(); $category = Category::getById($db, $id); if ($category) { echo json_encode($category); } else { http_response_code(404); echo json_encode(['error' => 'Category not found']); } } catch (Exception $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); } } // Returns the HTML content for the categories page (used by AJAX) public static function listCategories() { global $twig; try { $db = Database::getInstance(); $categories = Category::getAll($db); // Render only the content block echo $twig->render('categories.twig', [ 'categories' => $categories, ]); } catch (\Exception $e) { http_response_code(500); error_log("Error fetching categories: " . $e->getMessage()); echo "Error: " . $e->getMessage(); } } // CRUD operations (returns JSON) public static function create() { header('Content-Type: application/json'); try { $db = Database::getInstance(); $data = $_POST; $name = trim($data['new_category_name'] ?? ''); $parentId = !empty($data['parent_category_id']) ? (int)$data['parent_category_id'] : null; if (empty($name)) { http_response_code(400); echo json_encode(['error' => 'Category name is required']); return; } $category = new Category($db, null, $name, $parentId); if ($category->save()) { echo json_encode(['success' => true, 'message' => 'Category added successfully', 'id' => $category->getId()]); } else { throw new Exception('Failed to save category'); } } catch (Exception $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); } } public static function update($id) { header('Content-Type: application/json'); try { $db = Database::getInstance(); $data = json_decode(file_get_contents('php://input'), true) ?? $_POST; $existing = Category::getById($db, $id); if (!$existing) { http_response_code(404); echo json_encode(['error' => 'Category not found']); return; } $name = trim($data['category_name'] ?? $existing['name']); if (empty($name)) { http_response_code(400); echo json_encode(['error' => 'Category name is required']); return; } $category = new Category($db, $id, $name); if ($category->save()) { echo json_encode(['success' => true, 'message' => 'Category updated successfully']); } else { throw new Exception('Failed to update category'); } } catch (Exception $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); } } public static function delete($id) { header('Content-Type: application/json'); try { $db = Database::getInstance(); if (Category::delete($db, $id)) { echo json_encode(['success' => true, 'message' => 'Category deleted successfully']); } else { http_response_code(404); echo json_encode(['error' => 'Category not found']); } } catch (Exception $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); } } }