model = new OrderModel(); $this->userModel = new UserModel(); } public function __invoke(ServerRequestInterface $request) { $body = json_decode((string)$request->getBody(), true) ?? []; try { v::key('table_id', v::intType()->positive()) ->key('user_name', v::stringType()->notEmpty()->alnum('_')) ->key('company_id', v::intType()->positive()) ->key('order_name', v::stringType()->notEmpty()->alnum(' ')) ->key('order_phone', v::optional(v::stringType()->notEmpty()->length(8, 20)), false) ->key('status_status', v::stringType()->notEmpty()->in(['Aberta', 'Finalizada', 'Cancelada'])) ->assert($body); } catch (ValidationException $e) { return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(422); } $tableId = (int) $body['table_id']; $companyId = (int) $body['company_id']; $orderName = $body['order_name']; $orderPhone = $body['order_phone'] ?? ''; $statusStatus = $body['status_status']; $userName = $body['user_name']; // Buscar user_id correspondente ao user_name $userId = $this->getUserIdByUserName($userName, $companyId); if (!$userId) { return ResponseLib::sendFail("User '{$userName}' Not Found", [], "E_USER_NOT_FOUND")->withStatus(404); } $statusId = $this->model->getStatusIdByName($statusStatus); if ($statusId === null) { return ResponseLib::sendFail("Invalid status_status Provided: '{$statusStatus}'", [], "E_VALIDATE")->withStatus(400); } $created = $this->model->createOrder( $tableId, $userId, $companyId, $orderName, $orderPhone, $statusId ); return $created ? ResponseLib::sendOk(['created' => true, 'order_id' => $created]) : ResponseLib::sendFail("Failed to Create Order", [], "E_DATABASE")->withStatus(500); } private function getUserIdByUserName(string $username, int $companyId): ?int { $users = $this->userModel->getUsersByCompany($companyId); foreach ($users as $user) { if ($user['user_name'] === $username) { return (int) $user['user_id']; } } return null; } }