<?php


namespace App\Http\Controllers\V1;


use App\Core\Service\CurrencyService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AIController extends Controller
{

    private $currencyService;


    public function __construct()
    {
    }

    public function request(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];

        try {

            if (is_null($request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $request->params;

            $client = new \GuzzleHttp\Client([
                    'max' => 5,
                    'strict' => false,
                    'referer' => false,
                    'protocols' => ['https'],
                    'timeout' => 30,
                    'headers' => [
                        'Authorization' => 'Bearer ' . config('app.openAISecretKey'),
                        'Content-Type' => 'application/json',
                        'Cache-Control' => 'no-cache',
                        'Connection' => 'keep-alive',
                        'Accept-Encoding' => 'gzip'
                    ]
                ]
            );


            $result = $client->post('https://api.openai.com/v1/chat/completions', [
                'body' => json_encode($params['query'])
            ]);

            $result = $result->getBody()->getContents();
            $result = json_decode($result, 1);

            $choiceMessage = reset($result['choices']);

            if (isset($choiceMessage['message']['content'])) {
                $choiceMessage = json_decode($choiceMessage['message']['content'], 1);
                $data = $choiceMessage;
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $data];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 500;
        }

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

}

