<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PerplexityController extends Controller
{   
    public static function perplexityCurl($data, $apiKey, $url)
    {
         $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            return 'Error en cURL: ' . curl_error($ch);
        } else {
            $responseArray = json_decode($response, true);
            $respuesta = $responseArray['choices'][0]['message']['content'] ?? 'Sin respuesta';
            $citations = $responseArray['citations'] ?? [];
            $tokens = $responseArray['usage'] ?? [];

            $resultadoLegible = [
                "respuesta" => strip_tags($respuesta), // o usar HTML si es para navegador
                "fuentes" => $citations,
                "tokens_usados" => [
                    "prompt" => $tokens['prompt_tokens'] ?? 0,
                    "respuesta" => $tokens['completion_tokens'] ?? 0,
                    "total" => $tokens['total_tokens'] ?? 0,
                ]
            ];

            header('Content-Type: application/json');

            return json_encode($resultadoLegible, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }

        curl_close($ch);
    }
}
