HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux Bradford-Sitios 6.14.0-1017-azure #17~24.04.1-Ubuntu SMP Mon Dec 1 20:10:50 UTC 2025 x86_64
User: www-data (33)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/dtw.bradford/app/Services/ApiFormulariosBfService.php
<?php

namespace App\Services;

use App\Models\ApiConnections;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class ApiFormulariosBfService
{
    protected $client;
    protected $token;
    protected $credentials;
    public $lastRequest;
    public $lastResponse;

    public function __construct()
    {
        $credentials = ApiConnections::where('software_id', 4)->first();

        if (empty($credentials)) {
            throw new Exception('Error de configuración de cuenta API', 503);
        }
        if (empty($credentials->endpoint) || empty($credentials->api_key)) {
            throw new Exception('Error de configuración de cuenta API', 503);
        }
        if (!$credentials->status) {
            throw new Exception('Cuenta API deshabilitada', 503);
        }
        if($credentials->deleted) {
            throw new Exception('Cuenta API no existe o fue eliminada', 404);
        }

        $this->client = new Client([
            // 'timeout'  => 10.0, // Tiempo de espera en segundos
        ]);

        try {
            $this->credentials = $credentials;
            $response = $this->client->get($credentials->endpoint . '/health', [
                'headers' => [
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                    'X-API-KEY' => $credentials->api_key
                ],
            ]);

            $data = $response->getBody()->getContents();

        } catch (RequestException $e) {
            $statusCode = $e->hasResponse() ? $e->getResponse()->getStatusCode() : null;
                throw new Exception($e->getMessage(), $statusCode ? $statusCode : 503);
        } catch (Exception $e) {
            throw new Exception('Error de configuración de cuenta API', 503);
        }
    }

    public function getLastRequest(): array
    {
        return $this->lastRequest ?? [
            'method' => 'N/A',
            'url' => 'N/A',
            'headers' => [],
            'body' => null
        ];
    }

    public function getLastResponse(): array
    {
        return $this->lastResponse ?? [
            'status_code' => 'N/A',
            'headers' => [],
            'body' => null
        ];
    }

    public function get(string $model, array $queryParams = [])
    {
        try {
            $url = $this->credentials->endpoint . $model;
            $all_data = [];

            $queryParams['per_page'] = $queryParams['per_page'] ?? 500;
            $queryParams['page'] = 1;

            do {
                $query_string = http_build_query($queryParams);
                $full_url = $url . '?' . $query_string;

                $this->lastRequest = [
                    'method' => 'GET',
                    'url' => $full_url,
                    'headers' => [
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json',
                        'X-API-KEY' => $this->credentials->api_key
                    ],
                    'body' => null
                ];

                $response = $this->client->get($full_url, [
                    'headers' => [
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json',
                        'X-API-KEY' => $this->credentials->api_key
                    ],
                ]);

                $rawResponse = $response->getBody()->getContents();
                $response_data = json_decode($response->getBody(), true);

                // Registrar el response
                $this->lastResponse = [
                    'status_code' => $response->getStatusCode(),
                    'headers' => $response->getHeaders(),
                    'body' => $response_data
                ];


                if (isset($response_data['error']) && $response_data['error']) {
                    throw new Exception("Error en la solicitud: " . $response_data['message']);
                }

                if (!empty($response_data['data'])) {
                    $all_data = array_merge($all_data, $response_data['data']);
                }

                $current_page = (int) ($response_data['current_page'] ?? 1);
                $total_pages = (int) ($response_data['last_page'] ?? 1);

                $queryParams['page'] = $current_page + 1;
            } while ($current_page < $total_pages); // Corregido

            return $all_data;

        } catch (RequestException $e) {
            $statusCode = $e->hasResponse() ? $e->getResponse()->getStatusCode() : null;
            throw new Exception('Error en la solicitud: ' . $e->getMessage(), $statusCode ?: 500);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }


    // public function post(string $endpoint, array $data = [])
    // {
    //     try {
    //         $response = $this->client->post($endpoint, ['form_params' => $data]);
    //         return json_decode($response->getBody(), true);
    //     } catch (\Exception $e) {
    //         return [
    //             'error' => true,
    //             'message' => $e->getMessage(),
    //         ];
    //     }
    // }
}