AgentSaveController.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\AgentsModel;
  5. use Models\UserModel;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. class AgentSaveController
  8. {
  9. private UserModel $userModel;
  10. private AgentsModel $agentsModel;
  11. public function __construct()
  12. {
  13. $this->userModel = new UserModel();
  14. $this->agentsModel = new AgentsModel();
  15. }
  16. public function __invoke(ServerRequestInterface $request)
  17. {
  18. $userId = (int) ($request->getAttribute('user_id') ?? 0);
  19. $body = json_decode((string) $request->getBody(), true) ?: [];
  20. if ($userId <= 0) {
  21. return ResponseLib::sendFail('Unauthorized: Missing authenticated user', [], 'E_VALIDATE')->withStatus(401);
  22. }
  23. try {
  24. $companyId = $this->userModel->getCompanyIdByUserId($userId);
  25. if ($companyId === null) {
  26. return ResponseLib::sendFail('User not found', [], 'E_NOT_FOUND')->withStatus(404);
  27. }
  28. $agent = $this->agentsModel->saveAgent($companyId, $body);
  29. if ($agent === null) {
  30. return ResponseLib::sendFail('Invalid payload, duplicated email, or agent not found', [], 'E_VALIDATE')->withStatus(400);
  31. }
  32. return ResponseLib::sendOk($agent, 'S_CREATED');
  33. } catch (\Throwable $e) {
  34. return ResponseLib::sendFail('Failed to save agent', [], 'E_GENERIC')->withStatus(500);
  35. }
  36. }
  37. }