<?php

namespace Korkz\Demirteknoloji\traits;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

trait TranslateTrait
{
    use ENVConfig;
    /**
     * @param string $text
     * @param string $lang
     * @return array
     */
    public function translate(string $text, string $lang): array
    {
        $client = new Client();
        try {
            $ssl=false;
            if ($_SERVER["REQUEST_SCHEME"]==="https") {
                $ssl=true;
            }

            $translateApiKey=$this->env()["TRANSLATE_API_KEY"];

            $response = $client->post('https://google-translate1.p.rapidapi.com/language/translate/v2', ['headers' => ['Accept-Encoding' => 'application/gzip', 'X-RapidAPI-Host' => 'google-translate1.p.rapidapi.com', 'X-RapidAPI-Key' => $translateApiKey, 'Content-Type' => 'application/x-www-form-urlencoded',], 'body' => "q=$text&target=$lang",
                'curl' => [CURLOPT_SSL_VERIFYPEER => $ssl, CURLOPT_SSL_VERIFYHOST => $ssl,]
            ]);
            $result = json_decode($response->getBody()->getContents());
            return ["boolean" => true, "data" => $result];
        } catch (GuzzleException $e) {
            return ["boolean" => false, 'Error: ' . $e->getMessage()];
        }
    }
}