<?php

class Translate
{
    private $apiUrl;

    public function __construct()
    {
        $this->apiUrl = rtrim($_ENV['LIBRETRANSLATE_URL'], '/');
    }

    public function detectLanguage($text)
    {
        if (empty(trim($text))) {
            return null;
        }
        $response = $this->request('/detect', ['q' => $text]);
        return $response[0]['language'] ?? null;
    }

    public function translateText($text, $source, $target)
    {
        if (empty(trim($text))) {
            return null;
        }
        $response = $this->request('/translate', [
            'q' => $text,
            'source' => $source,
            'target' => $target,
            'format' => 'text'
        ]);
        return $response['translatedText'] ?? null;
    }

    private function request($endpoint, $data, $method = 'POST')
    {
        $url = $this->apiUrl . $endpoint;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        }

        $response_body = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code >= 400) {
            // In case of an error, log it or handle it
            error_log("LibreTranslate API error. HTTP Code: {$http_code}, Response: {$response_body}");
            return null;
        }

        return json_decode($response_body, true);
    }
}
