| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\ProductModel;
- use Psr\Http\Message\ServerRequestInterface;
- class ProductController
- {
- private ProductModel $model;
- public function __construct()
- {
- $this->model = new ProductModel();
- }
- 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') {
- $products = $this->model->getProducts($companyId);
- return ResponseLib::sendOk($products);
- }
- if ($method === 'POST') {
- // 1. Criar Produto
- if (isset($body['product_name'], $body['product_price'], $body['category_id'])) {
- $created = $this->model->createProduct(
- $body['product_name'],
- (float)$body['product_price'],
- (int)$body['category_id'],
- $companyId
- );
- return $created ? ResponseLib::sendOk(['created' => true]) : ResponseLib::sendFail("Failed to Create Product", [], "E_VALIDATE")->withStatus(402);
- }
- // 2. Deletar Produto (usando 'delete_product_id' para clareza)
- if (isset($body['delete_product_id'])) {
- $deleted = $this->model->deleteProduct((int)$body['delete_product_id'], $companyId);
- return $deleted ? ResponseLib::sendOk(['deleted' => true]) : ResponseLib::sendFail("Failed to Delete Product or Product Not Found", [], "E_VALIDATE")->withStatus(403);
- }
- // 3. Atualizar Produto (usando 'update_product_id')
- if (isset($body['update_product_id'])) {
- $productId = (int)$body['update_product_id'];
- $productName = $body['product_name'] ?? null;
- $productPrice = isset($body['product_price']) ? (float)$body['product_price'] : null;
- if ($productName === null && $productPrice === null) {
- return ResponseLib::sendFail("Missing product_name or product_price for update", [], "E_VALIDATE")->withStatus(400);
- }
- $updated = $this->model->updateProduct(
- $productId,
- $companyId,
- $productName,
- $productPrice
- );
- return $updated ? ResponseLib::sendOk(['updated' => true]) : ResponseLib::sendFail("Failed to Update Product or Product Not Found", [], "E_VALIDATE")->withStatus(404);
- }
- // Se nenhuma das ações POST acima for reconhecida
- return ResponseLib::sendFail("Missing Data for Product POST action", [], "E_VALIDATE")->withStatus(405);
- }
- return ResponseLib::sendMethodNotAllowed(['GET', 'POST']);
- }
- }
|