<?php

namespace Lokalize\Translators;

class LibreTranslate {

    protected array $config = [];

    public function __construct(array $config = []) {
        $this->config = $config;
    }

    public function translate(string $text, string $to, $context = null) {

        $data = [
            'api_key' => $this->config['apiKey'] ?? '',
            'q' => $text,
            'target' => $to,
            'source' => 'auto',
            'format' => $this->isHTML($text) ? 'html' : 'text',
            'alternatives' => 1
        ];

        $endpoint = rtrim($this->config['url'] ?? '', '/').'/translate';

        $ch = curl_init($endpoint);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json'
            ]
        ]);

        $error = null;
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $error = ['error' => curl_error($ch)];
        }

        curl_close($ch);

        if ($error) {
            return $error;
        }

        $json = \json_decode($response, true);
        $translation = '';

        if (isset($json['translatedText'])) {
            $translation = $json['translatedText'];
        }

        return $translation;
    }

    protected function isHTML(string $string): bool {

        if (empty($string)) {
            return false;
        }

        // Convert string to lowercase for easier pattern matching
        $string = strtolower($string);

        // Check for common HTML tags and entities
        $patterns = [
            // Check for any HTML tag
            '/<[^>]*>/',
            // Check for HTML entities like &nbsp; &amp; etc.
            '/&[a-z]+;/',
            // Check for numeric HTML entities like &#39;
            '/&#[0-9]+;/',
            // Check for hex HTML entities like &#x27;
            '/&#x[a-f0-9]+;/i'
        ];

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $string)) {
                return true;
            }
        }

        return false;
    }
}
