CategoryController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\CategoryModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class CategoryController
  7. {
  8. private CategoryModel $model;
  9. public function __construct()
  10. {
  11. $this->model = new CategoryModel();
  12. }
  13. public function __invoke(ServerRequestInterface $request)
  14. {
  15. $method = $request->getMethod();
  16. $body = json_decode((string)$request->getBody(), true) ?? [];
  17. $companyId = $body['company_id'] ?? null;
  18. if (!$companyId) {
  19. return ResponseLib::sendFail("Missing Company ID", [], "E_VALIDATE")->withStatus(401);
  20. }
  21. if ($method === 'GET') {
  22. $categories = $this->model->getCategories($companyId);
  23. return ResponseLib::sendOk($categories);
  24. }
  25. if ($method === 'POST') {
  26. if (isset($body['category_name'])) {
  27. $created = $this->model->createCategory(
  28. $body['category_name'],
  29. $companyId,
  30. $body['category_is_kitchen'] ?? false
  31. );
  32. return $created ? ResponseLib::sendOk(['created' => true]) : ResponseLib::sendFail("Failed to Create Category", [], "E_VALIDATE")->withStatus(402);
  33. }
  34. if (isset($body['delete'])) {
  35. $deleted = $this->model->deleteByName($body['delete'], $companyId);
  36. return $deleted ? ResponseLib::sendOk(['deleted' => true]) : ResponseLib::sendFail("Failed to Delete Category", [], "E_VALIDATE")->withStatus(403);
  37. }
  38. if (isset($body['product_name'], $body['category_name'], $body['product_price'])) {
  39. $added = $this->model->addProductToCategory(
  40. $body['product_name'],
  41. (float)$body['product_price'],
  42. $body['category_name'],
  43. $companyId
  44. );
  45. return $added ? ResponseLib::sendOk(['product_added' => true]) : ResponseLib::sendFail("Category Not Found", [], "E_VALIDATE")->withStatus(404);
  46. }
  47. return ResponseLib::sendFail("Missing Data", [], "E_VALIDATE")->withStatus(405);
  48. }
  49. return ResponseLib::sendMethodNotAllowed(['GET', 'POST']);
  50. }
  51. }