| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Psr\Http\Message\ServerRequestInterface;
- use React\Http\Message\Response;
- use Models\CprQueryModel;
- class CprQueryController
- {
- private CprQueryModel $model;
- public function __construct()
- {
- $this->model = new CprQueryModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true);
- if (!is_array($body)) {
- return ResponseLib::sendFail('Invalid JSON body', [], 'E_VALIDATE')->withStatus(400);
- }
- $authCompanyId = (int)($request->getAttribute('api_company_id') ?? 0);
- if ($authCompanyId <= 0) {
- return ResponseLib::sendFail('Authenticated company not found', [], 'E_VALIDATE')->withStatus(401);
- }
- $bodyCompanyId = (int)($body['company_id'] ?? $authCompanyId);
- if ($bodyCompanyId <= 0) {
- return ResponseLib::sendFail('company_id is required', [], 'E_VALIDATE')->withStatus(400);
- }
- if ($authCompanyId !== 1 && $authCompanyId !== $bodyCompanyId) {
- return ResponseLib::sendFail(
- 'Unauthorized company access',
- [],
- 'E_AUTH'
- )->withStatus(403);
- }
- $hasGlobalAccess = $authCompanyId === 1;
- $cprId = isset($body['cpr_id']) ? (int)$body['cpr_id'] : null;
- try {
- if ($cprId) {
- $record = $hasGlobalAccess
- ? $this->model->getById($cprId)
- : $this->model->getByIdAndCompany($cprId, $authCompanyId);
- if (!$record) {
- return ResponseLib::sendFail(
- 'CPR not found',
- [],
- 'E_NOT_FOUND'
- )->withStatus(404);
- }
- return Response::json($record)->withStatus(200);
- }
- $list = $hasGlobalAccess
- ? $this->model->listAll()
- : $this->model->listByCompany($authCompanyId);
- return Response::json($list)->withStatus(200);
- } catch (\Throwable $e) {
- return ResponseLib::sendFail(
- 'Failed to query CPRs: ' . $e->getMessage(),
- [],
- 'E_DATABASE'
- )->withStatus(500);
- }
- }
- }
|