ProductController.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\ProductModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class ProductController
  7. {
  8. private ProductModel $model;
  9. public function __construct()
  10. {
  11. $this->model = new ProductModel();
  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. $products = $this->model->getProducts($companyId);
  23. return ResponseLib::sendOk($products);
  24. }
  25. if ($method === 'POST') {
  26. // 1. Criar Produto
  27. if (isset($body['product_name'], $body['product_price'], $body['category_id'])) {
  28. $created = $this->model->createProduct(
  29. $body['product_name'],
  30. $body['product_price'],
  31. (int)$body['category_id'],
  32. $companyId
  33. );
  34. return $created ? ResponseLib::sendOk(['created' => true]) : ResponseLib::sendFail("Failed to Create Product", [], "E_VALIDATE")->withStatus(402);
  35. }
  36. // 2. Deletar Produto (usando 'delete_product_id' para clareza)
  37. if (isset($body['delete_product_id'])) {
  38. $deleted = $this->model->deleteProduct((int)$body['delete_product_id'], $companyId);
  39. return $deleted ? ResponseLib::sendOk(['deleted' => true]) : ResponseLib::sendFail("Failed to Delete Product or Product Not Found", [], "E_VALIDATE")->withStatus(403);
  40. }
  41. // 3. Atualizar Produto (usando 'update_product_id')
  42. if (isset($body['update_product_id'])) {
  43. $productId = (int)$body['update_product_id'];
  44. $productName = $body['product_name'] ?? null;
  45. $productPrice = $body['product_price'] ?? null;
  46. if ($productName === null && $productPrice === null) {
  47. return ResponseLib::sendFail("Missing product_name or product_price for update", [], "E_VALIDATE")->withStatus(400);
  48. }
  49. $updated = $this->model->updateProduct(
  50. $productId,
  51. $companyId,
  52. $productName,
  53. $productPrice
  54. );
  55. return $updated ? ResponseLib::sendOk(['updated' => true]) : ResponseLib::sendFail("Failed to Update Product or Product Not Found", [], "E_VALIDATE")->withStatus(404);
  56. }
  57. // Se nenhuma das ações POST acima for reconhecida
  58. return ResponseLib::sendFail("Missing Data for Product POST action", [], "E_VALIDATE")->withStatus(405);
  59. }
  60. return ResponseLib::sendMethodNotAllowed(['GET', 'POST']);
  61. }
  62. }