model = new OrderModel(); } public function __invoke(ServerRequestInterface $request) { $body = json_decode((string)$request->getBody(), true) ?? []; try { // company_id é obrigatório para qualquer consulta de pedidos v::key('company_id', v::intType()->positive()) // order_id, status_status e table_id são opcionais, mas mutuamente exclusivos em alguns cenários ->key('order_id', v::optional(v::intType()->positive()), false) ->key('status_status', v::optional(v::stringType()->notEmpty()->in(['Aberta', 'Finalizada', 'Cancelada'])), false) ->key('table_id', v::optional(v::intType()->positive()), false) // Adicionado table_id como opcional ->assert($body); } catch (ValidationException $e) { return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400); } $companyId = (int) $body['company_id']; $orderId = $body['order_id'] ?? null; $statusStatus = $body['status_status'] ?? null; $tableId = $body['table_id'] ?? null; // Pega o table_id do payload $statusId = null; // Se status_status for fornecido, converte para status_id if ($statusStatus !== null) { $statusId = $this->model->getStatusIdByName($statusStatus); if ($statusId === null) { return ResponseLib::sendFail("Invalid status_status Provided: '{$statusStatus}'", [], "E_VALIDATE")->withStatus(400); } } $orders = []; if ($orderId !== null) { // Obter um pedido específico por order_id $order = $this->model->getOrderById($orderId, $companyId); if ($order) { $orders[] = $order; } } elseif ($tableId !== null) { // NOVO: Lógica para obter pedidos por table_id $orders = $this->model->getOrdersByTable($tableId, $companyId, $statusId); } else { // Obter todos os pedidos da empresa, ou filtrados apenas por status $orders = $this->model->getOrders($companyId, $statusId); } // Formata o retorno para incluir o status_status em vez do status_id foreach ($orders as &$order) { if (isset($order['status_id'])) { $order['status_status'] = $this->model->getStatusNameById($order['status_id']); unset($order['status_id']); // Remove o ID se não quiser expô-lo } } if (!empty($orders)) { return ResponseLib::sendOk($orders); } return ResponseLib::sendFail("No Orders Found for the Given Criteria", [], "E_DATABASE")->withStatus(204); } }