| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- <?php
- namespace Controllers;
- use Libs\Logger;
- use Libs\ResponseLib;
- use Models\AgentsModel;
- use Models\UserModel;
- use Psr\Http\Message\ServerRequestInterface;
- class AgentSaveController
- {
- private UserModel $userModel;
- private AgentsModel $agentsModel;
- public function __construct()
- {
- $this->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);
- }
- }
- }
|