| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\CategoryModel;
- use Psr\Http\Message\ServerRequestInterface;
- class CategoryController
- {
- private CategoryModel $model;
- public function __construct()
- {
- $this->model = new CategoryModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $method = $request->getMethod();
- $body = json_decode((string)$request->getBody(), true) ?? [];
- $companyId = $body['company_id'] ?? null;
- if (!$companyId) {
- return ResponseLib::sendFail("Missing Company ID", [], "E_VALIDATE")->withStatus(401);
- }
- if ($method === 'GET') {
- $categories = $this->model->getCategories($companyId);
- return ResponseLib::sendOk($categories);
- }
- if ($method === 'POST') {
- if (isset($body['category_name'])) {
- $created = $this->model->createCategory(
- $body['category_name'],
- $companyId,
- $body['category_is_kitchen'] ?? false
- );
- return $created ? ResponseLib::sendOk(['created' => true]) : ResponseLib::sendFail("Failed to Create Category", [], "E_VALIDATE")->withStatus(402);
- }
- if (isset($body['delete'])) {
- $deleted = $this->model->deleteByName($body['delete'], $companyId);
- return $deleted ? ResponseLib::sendOk(['deleted' => true]) : ResponseLib::sendFail("Failed to Delete Category", [], "E_VALIDATE")->withStatus(403);
- }
- if (isset($body['product_name'], $body['category_name'], $body['product_price'])) {
- $added = $this->model->addProductToCategory(
- $body['product_name'],
- (float)$body['product_price'],
- $body['category_name'],
- $companyId
- );
- return $added ? ResponseLib::sendOk(['product_added' => true]) : ResponseLib::sendFail("Category Not Found", [], "E_VALIDATE")->withStatus(404);
- }
- return ResponseLib::sendFail("Missing Data", [], "E_VALIDATE")->withStatus(405);
- }
- return ResponseLib::sendMethodNotAllowed(['GET', 'POST']);
- }
- }
|