userModel = new UserModel(); $this->slaConfigsModel = new SlaConfigsModel(); } public function __invoke(ServerRequestInterface $request) { $userId = (int) ($request->getAttribute('user_id') ?? 0); if ($userId <= 0) { return Payload::fail('Unauthorized: Missing authenticated user', [], 'E_VALIDATE', 401); } $body = json_decode((string) $request->getBody(), true) ?: []; $id = trim((string) ($body['id'] ?? '')); $name = trim((string) ($body['name'] ?? '')); $firstResponseH = $body['firstResponseH'] ?? null; $firstResponseM = $body['firstResponseM'] ?? null; $resolutionH = $body['resolutionH'] ?? null; $alertPct = $body['alertPct'] ?? null; $validator = (new Validator([ 'firstResponseH' => $firstResponseH, 'firstResponseM' => $firstResponseM, 'resolutionH' => $resolutionH, 'alertPct' => $alertPct, 'name' => $name, ])) ->required('firstResponseH')->intRange('firstResponseH', 0, 72) ->required('firstResponseM')->intRange('firstResponseM', 0, 59) ->required('resolutionH')->intRange('resolutionH', 1, 720) ->required('alertPct')->intRange('alertPct', 1, 99) ->maxLength('name', 20); if ($id === '') { $validator->required('name'); } if ($validator->fails()) { return Payload::fail($validator->firstError() ?? 'Invalid payload', [], 'E_VALIDATE', 400); } $companyId = $this->userModel->getCompanyIdByUserId($userId); if ($companyId === null) { return Payload::fail('User not found', [], 'E_NOT_FOUND', 404); } try { $result = $this->slaConfigsModel->saveConfig($companyId, $body); } catch (\Throwable $e) { return Payload::fail('Failed to save SLA config', [], 'E_GENERIC', 500); } if (($result['status'] ?? '') === 'not_found') { return Payload::fail('SLA config not found', [], 'E_NOT_FOUND', 404); } if (($result['status'] ?? '') === 'invalid') { return Payload::fail('Invalid payload', [], 'E_VALIDATE', 400); } if (($result['status'] ?? '') === 'duplicate') { return Payload::fail('Department already has an SLA config', [], 'E_VALIDATE', 400); } if (($result['status'] ?? '') === 'error' || !isset($result['item'])) { return Payload::fail('Failed to save SLA config', [], 'E_GENERIC', 500); } if (($result['status'] ?? '') === 'created') { return Payload::ok($result['item'], 'S_CREATED', 'SLA config created.'); } return Payload::ok($result['item'], 'S_OK', 'SLA config updated.'); } }