HEX
Server: Apache
System: Linux vpshost11508.publiccloud.com.br 5.15.179-grsec-vpshost-10.lc.el8.x86_64 #1 SMP Mon Apr 7 12:04:45 -03 2025 x86_64
User: wicomm2 (10002)
PHP: 8.3.0
Disabled: apache_child_terminate,dl,escapeshellarg,escapeshellcmd,exec,link,mail,openlog,passthru,pcntl_alarm,pcntl_exec,pcntl_fork,pcntl_get_last_error,pcntl_getpriority,pcntl_setpriority,pcntl_signal,pcntl_signal_dispatch,pcntl_sigprocmask,pcntl_sigtimedwait,pcntl_sigwaitinfo,pcntl_strerror,pcntl_wait,pcntl_waitpid,pcntl_wexitstatus,pcntl_wifexited,pcntl_wifsignaled,pcntl_wifstopped,pcntl_wstopsig,pcntl_wtermsig,php_check_syntax,php_strip_whitespace,popen,proc_close,proc_open,shell_exec,symlink,system
Upload Files
File: /home/storage/5/78/dd/wicomm2/public_html/blackfriday/lib/OpenAI.php
<?php
require_once __DIR__.'/Utils.php';

class OpenAIClient {
  private string $apiKey;
  private string $model;

  public function __construct() {
    if (!defined('OPENAI_API_KEY') || OPENAI_API_KEY === '') {
      throw new Exception('OPENAI_API_KEY não configurado em config/config.php');
    }
    $this->apiKey = OPENAI_API_KEY;
    $this->model  = defined('OPENAI_MODEL') ? OPENAI_MODEL : 'gpt-4o-mini';
  }

  private function post(string $endpoint, array $payload): array {
    $ch = curl_init("https://api.openai.com/v1/$endpoint");
    curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer '.$this->apiKey
      ],
      CURLOPT_TIMEOUT => 60,
      CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)
    ]);
    $res = curl_exec($ch);
    if ($res === false) throw new Exception('OpenAI request failed: '.curl_error($ch));
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $json = json_decode($res, true);
    if ($code >= 300) throw new Exception('OpenAI error '.$code.': '.$res);
    return $json;
  }

  public function classifyMaturity(array $qa5): string {
    $system = "Você é um avaliador objetivo de prontidão para Black Friday. Responda com UMA PALAVRA, em minúsculas: basico, intermediario ou avancado.";
    $user   = "Analise as 5 respostas e classifique o nível de maturidade do negócio para a Black Friday (uma palavra).\n\n".
              json_encode($qa5, JSON_UNESCAPED_UNICODE);

    $payload = [
      'model' => $this->model,
      'messages' => [
        ['role'=>'system','content'=>$system],
        ['role'=>'user','content'=>$user],
      ],
      'temperature' => 0
    ];
    $resp = $this->post('chat/completions', $payload);
    $txt = trim(strtolower($resp['choices'][0]['message']['content'] ?? ''));
    if (!in_array($txt, ['basico','intermediario','avancado'])) {
      if (strpos($txt,'bas') !== false) $txt='basico';
      elseif (strpos($txt,'inter') !== false) $txt='intermediario';
      elseif (strpos($txt,'avan') !== false) $txt='avancado';
      else $txt='intermediario';
    }
    return $txt;
  }

  public function summarizeLighthouse(array $psi): array {
    $system = "Você traduz resultados do Lighthouse para PT-BR em dicas curtas e práticas.";
    $user   = "A partir do JSON do PageSpeed (Lighthouse), gere:\n".
              "- score de performance (0-100)\n".
              "- top 5 oportunidades, cada uma com: titulo curto e recomendação prática em 1 frase.\n".
              "Responda em JSON { score, oportunidades[] }.\n\n".
              json_encode($psi, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

    $payload = [
      'model' => $this->model,
      'messages' => [
        ['role'=>'system','content'=>$system],
        ['role'=>'user','content'=>$user],
      ],
      'temperature' => 0.2
    ];
    $resp = $this->post('chat/completions', $payload);
    $txt = trim($resp['choices'][0]['message']['content'] ?? '{}');
    $json = json_decode($txt, true);

    if (!$json) {
      $score = (int) round((($psi['lighthouseResult']['categories']['performance']['score'] ?? 0) * 100));
      $json = ['score'=>$score, 'oportunidades'=>[]];
    }

    // garanta chaves
    $json['score'] = $json['score'] ?? (int) round((($psi['lighthouseResult']['categories']['performance']['score'] ?? 0) * 100));
    $json['oportunidades'] = $json['oportunidades'] ?? [];

    return $json;
  }
}