- <?php
- namespace App\Service\Aeat;
- use App\Entity\AeatResponseLogs;
- use App\Entity\CustomerAeat;
- use App\Entity\Taxation;
- use App\Util\AeatResponseLogUtil;
- use App\Service\Aeat\AeatRentDataProcessingService;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\GuzzleException;
- final class AeatService
- {
-     protected Client $client;
-     protected AeatResponseLogUtil $aeatResponseLogsUtil;
-     protected AeatRentDataProcessingService $aeatRentDataProcessingService;
-     public function __construct(
-         AeatResponseLogUtil $aeatResponseLogsUtil,
-         AeatRentDataProcessingService $aeatRentDataProcessingService
-     )
-     {
-         $this->client = new Client([
-             'base_uri' => $_ENV['AEAT_URI'],
-             'headers' => [
-                 'api-key' => $_ENV['AEAT_KEY'],
-             ]
-         ]);
-         $this->aeatResponseLogsUtil = $aeatResponseLogsUtil;
-         $this->aeatRentDataProcessingService = $aeatRentDataProcessingService;
-     }
-     public function esDomicilioRatificado(string $year, string $nif, CustomerAeat $customerAeat = null): bool
-     {
-         $array = [
-             'year' => $year,
-             'nif' => $nif,
-         ];
-         try {
-             $response = $this->client->get(sprintf('api/checkAddressStatus?%s', http_build_query($array)));
-             $statusCode = $response->getStatusCode();
-             $parsed = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
-             $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['ES_DOMICILIO'], 'cms/customer/{hash}/aeat/esDomicilioRatificado', $array, $parsed, $customerAeat, $statusCode, true);
-             return $parsed['isConfirmed'] ?? false;
-         } catch (\Exception $exception) {
-             if (isset($parsed, $statusCode) && is_array($parsed)) {// @phpstan-ignore-line
-                 $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['ES_DOMICILIO'], 'cms/customer/{hash}/aeat/esDomicilioRatificado', $array, $parsed, $customerAeat, $statusCode, false);// @phpstan-ignore-line
-             }
-             throw new \RuntimeException($exception->getMessage());
-         }
-     }
-     /**
-      * @throws GuzzleException
-      * @throws \JsonException
-      */
-     public function ratificate(string $nif, string $reference, int $situation, CustomerAeat $customerAeat = null): array
-     {
-         $array = [
-             'nif' => $nif,
-             'reference' => $reference,
-             'situation' => "$situation",
-         ];
-         $response = $this->client->post('api/ratificate', [
-             'json' => $array
-         ]);
-         $statusCode = $response->getStatusCode();
-         $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
-         $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['RATIFICATE'], 'cms/customer/{hash}/aeat/ratificate', $array, $response, $customerAeat, $statusCode, !$response['error']);
-         return $response ?? [];
-     }
-     /**
-      * @throws GuzzleException
-      * @throws \JsonException
-      */
-     public function obtenerReferencia(string $nif, ?string $validity = null, ?string $support = null, ?float $check = null, ?string $iban = null, CustomerAeat $customerAeat = null): array // @phpcs:ignore
-     {
-         $array = [
-             'nif' => $nif,
-             'validity' => $validity,
-             'support' => $support,
-             'check' => number_format($check, 2, ',', ''),
-             'iban' => $iban,
-         ];
-         $response = $this->client->get(sprintf('api/reference?%s', http_build_query($array)));
-         $statusCode = $response->getStatusCode();
-         $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
-         $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['OBTENER_REFERENCIA'], 'cms/customer/{hash}/aeat/obtenerReferencia', $array, $response, $customerAeat, $statusCode, !$response['error']);
-         return $response ?? [];
-     }
-     /**
-      * @throws GuzzleException
-      * @throws \JsonException
-      */
-     public function descargarDatosFiscales(string $nif, ?string $validity = null, ?string $support = null, ?float $check = null, ?string $iban = null, ?string $reference = null, CustomerAeat $customerAeat): array // @phpcs:ignore
-     {
-         $array = [
-             'nif' => $nif,
-             'validity' => $validity,
-             'support' => $support,
-             'check' => $check ? number_format($check, 2, ',', '') : null,
-             'iban' => $iban,
-             'reference' => $reference,
-         ];
-         $response = $this->client->get(sprintf('api/data?%s', http_build_query($array)));
-         $statusCode = $response->getStatusCode();
-         $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
-         $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['DESCARGAR_DATOS'], 'cms/customer/{hash}/aeat/datosFiscales', $array, $response, $customerAeat, $statusCode, !$response['error']);
-         return $response ?? [];
-     }
-     /**
-      * @throws GuzzleException
-      * @throws \JsonException
-      */
-     public function validarImpuesto(string $xml, Taxation $taxation, ?array $data): array // @phpcs:ignore
-     {
-         if (str_starts_with($taxation->getService()->getAlias(), "P005")) {
-             $model = '100';
-         }
-         if (str_starts_with($taxation->getService()->getAlias(), "MOD210")) {
-             $model = '210';
-         }
-         $array = [
-             'xml' => $xml,
-             'year' => $taxation->getServiceYear(),
-             'model' => $model ?? null
-         ];
-         $response = $this->client->post(sprintf('api/aeat-draft'), [
-             'json' => $array
-         ]);
-         $statusCode = $response->getStatusCode();
-         $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
-         if (isset($data['origin']) && $data['origin'] == 'API') {
-             $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['VALIDAR-IMPUESTO'], 'api/taxations/{hash}/validate', $array, $response, null, $statusCode, !$response['error'], $taxation);
-         } else {
-             $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['VALIDAR-IMPUESTO'], 'cms/taxations/{hash}/validate', $array, $response, null, $statusCode, !$response['error'], $taxation);
-         }
-         return $response ?? [];
-     }
-     /**
-      * @throws GuzzleException
-      * @throws \JsonException
-      */
-     public function presentarImpuesto(string $xml, Taxation $taxation, ?array $data): array // @phpcs:ignore
-     {
-         if (str_starts_with($taxation->getService()->getAlias(), "P005")) {
-             $model = '100';
-         }
-         if (str_starts_with($taxation->getService()->getAlias(), "MOD210")) {
-             $model = '210';
-         }
-         $array = [
-             'xml' => $xml,
-             'year' => $taxation->getServiceYear(),
-             'model' => $model ?? null
-         ];
-         if ($taxation->getNRC() !== null) {
-             $array['nrc'] = $taxation->getNRC();
-         }
-         $response = $this->client->post(sprintf('api/aeat-final'), [
-             'json' => $array
-         ]);
-         $statusCode = $response->getStatusCode();
-         $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
-         if (isset($data['origin']) && $data['origin'] == 'API') {
-             $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['PRESENTAR-IMPUESTO'], 'api/taxations/{hash}/present', $array, $response, null, $statusCode, !$response['error'], $taxation);
-         } else {
-             $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['PRESENTAR-IMPUESTO'], 'cms/taxations/{hash}/present', $array, $response, null, $statusCode, !$response['error'], $taxation);
-         }
-         return $response ?? [];
-     }
-     /**
-      * @throws GuzzleException
-      * @throws \JsonException
-      */
-     public function obtenerNRC(Taxation $taxation, ?array $data): array // @phpcs:ignore
-     {
-         if (str_starts_with($taxation->getService()->getAlias(), "P005")) {
-             $model = '100';
-         }
-         if (str_starts_with($taxation->getService()->getAlias(), "MOD210")) {
-             $model = '210';
-             $owner = $taxation->getTaxationPropertyOwner()->getOwner();
-             $document_number = $owner->getDocumentNumber();
-             $full_name = $owner->getSurname() . ' ' . $owner->getName();
-         }
-         $array = [
-             'year' => $taxation->getServiceYear(),
-             'model' => $model ?? null,
-             'period' => $taxation->getPeriod() ?? null,
-             'nif' => $document_number ?? null,
-             'full_name' => $full_name ?? null,
-             'amount' => $taxation->getResult(),
-             'iban' => $taxation->getBankAccount()
-         ];
-         $response = $this->client->post(sprintf('api/aeat-get-nrc'), [
-             'json' => $array
-         ]);
-         $statusCode = $response->getStatusCode();
-         $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
-         if (isset($data['origin']) && $data['origin'] == 'API') {
-             $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['PRESENTAR-IMPUESTO'], 'api/taxations/{hash}/get-nrc', $array, $response, null, $statusCode, !$response['error'], $taxation);
-         } else {
-             $this->aeatResponseLogsUtil->createLog(AeatResponseLogs::TYPE['PRESENTAR-IMPUESTO'], 'cms/taxations/{hash}/get-nrc', $array, $response, null, $statusCode, !$response['error'], $taxation);
-         }
-         return $response ?? [];
-     }
-     public function obtenerDatosFiscales(CustomerAeat $customerAeat)
-     {
-         $datos_fiscales = $customerAeat->getDatosFiscales();
-         $datos_fiscales_unleashed = explode("\r\n", $datos_fiscales);
-         $response = [];
-         $datos_procesados = [];
-         
-         foreach ($datos_fiscales_unleashed as $datos_para_procesado) {
-             $response[0] = array_merge($datos_procesados, $this->aeatRentDataProcessingService->procesaTiposRegistro($datos_procesados, $datos_para_procesado));
-         }
-         return $response;
-     }
- }
-