userModel = new UserModel(); $this->agentsModel = new AgentsModel(); } public function __invoke(ServerRequestInterface $request) { $userId = (int) ($request->getAttribute('user_id') ?? 0); $body = json_decode((string) $request->getBody(), true) ?: []; if ($userId <= 0) { return ResponseLib::sendFail('Unauthorized: Missing authenticated user', [], 'E_VALIDATE')->withStatus(401); } try { $companyId = $this->userModel->getCompanyIdByUserId($userId); if ($companyId === null) { return ResponseLib::sendFail('User not found', [], 'E_NOT_FOUND')->withStatus(404); } $agent = $this->agentsModel->saveAgent($companyId, $body); if ($agent === null) { return ResponseLib::sendFail('Invalid payload, duplicated email, or agent not found', [], 'E_VALIDATE')->withStatus(400); } return ResponseLib::sendOk($agent, 'S_CREATED'); } catch (\Throwable $e) { Logger::error('Failed to save agent', ['error' => $e->getMessage()]); return ResponseLib::sendFail('Failed to save agent', [], 'E_GENERIC')->withStatus(500); } } }