<?php

namespace Clonable\Helpers;

use Clonable\Objects\ClonableConfig;
use Exception;


/**
 * Translate text.
 * @param array $content
 * @return array
 */

class TextTranslator
{
    /**
     * Translate a given string (plain text or HTML) using Clonable's Translation API.
     *
     * @param string      $content      The text or HTML to translate.
     * @param string|null $cloneId      The clone ID for the desired target language (required for private keys).
     * @param bool        $textOnly     True if $content is plain text, false if it contains HTML.
     *
     * @return string                   The translated content.
     *
     * @throws \RuntimeException        If the request fails or the API returns an error.
     */

    public static function translateText(
        string $content,
        ?string $cloneId = null,
        bool $textOnly = true // no trailing comma for PHP 7.4
    ): string {

        $editorMode = false;
        $editorToken = null;
        $timeoutSec = 10;
        $max_length = 49152;

        if ($content === '') {
            throw new \RuntimeException('Content cannot be empty.');
        }

        if (strlen($content) > $max_length) {
            return $content; // Content length exceeds limit, return original content
        }

        $api_key = get_option('clonable_api_key');
        if ($api_key === null) {
            throw new Exception("api key is null");
        }

        $url = 'https://' . ClonableConfig::TRANSLATIONS_API_ENDPOINT . '/translate';

        $payload = [
            'content'     => $content,
            'text_only'   => $textOnly,
            'editor_mode' => $editorMode,
            'create_new' => true
        ];

        if ($editorMode) {
            if (!$editorToken) {
                throw new \RuntimeException('editor_token is required when editor_mode is true.');
            }
            $payload['editor_token'] = $editorToken;
        }

        if ($cloneId !== null) {
            $payload['clone_id'] = $cloneId;
        } else {
            // For private API keys, clone_id is required.
            throw new \RuntimeException('clone_id is required.');
        }

        $curl_handle = curl_init($url);
        curl_setopt_array($curl_handle, [
            CURLOPT_POST           => true,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Accept: application/json',
                'Authorization: Bearer ' . $api_key,
            ],
            CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_TIMEOUT        => $timeoutSec,
            CURLOPT_USERAGENT => "Clonable Wordpress " . CLONABLE_VERSION . " (curl)",
        ]);

        $response_body = curl_exec($curl_handle);
        $curl_err_no    = curl_errno($curl_handle);
        $curl_err_msg   = curl_error($curl_handle);
        $status       = (int) curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
        curl_close($curl_handle);

        if ($curl_err_no !== 0) {
            throw new \RuntimeException("cURL error ({$curl_err_no}): {$curl_err_msg}");
        }

        if ($response_body === false || $response_body === '') {
            throw new \RuntimeException("Empty response from API (HTTP {$status}).");
        }

        $json = json_decode($response_body, true);
        if (!is_array($json)) {
            throw new \RuntimeException("Invalid JSON response (HTTP {$status}): {$response_body}");
        }

        if ($status !== 200) {
            $code    = $json['error_code']        ?? 'unknown_error';
            $desc    = $json['error_description'] ?? 'Unknown error';
            $fields  = $json['error_fields']      ?? null;
            $details = $fields ? ('; fields: ' . json_encode($fields)) : '';
            throw new \RuntimeException("API error (HTTP {$status}) {$code}: {$desc}{$details}");
        }

        if (!array_key_exists('translation', $json)) {
            throw new \RuntimeException("Missing 'translation' in API response.");
        }

        return (string) $json['translation'];
    }

	/*
        * Translate a document (HTML or plain text) using the TextTranslator.
        * @param string $clone_id The clone ID to translate for.
        * @param string|null $content The content to translate.
        * @param bool $minify_html Whether to minify HTML content before translation.
        * @return string|null The translated content, or original if no translation occurred.
    */
	public static function translate_document(string $clone_id, ?string $content, $minify_html = false): ?string
	{
		if (empty($content) || empty($clone_id)) {
			return $content;
		}

		$content = trim($content);
		$is_html = strip_tags($content) !== $content;
		$text_only = !$is_html;
		$max_length = 49152;

		// if HTML, minify and clean it first
		if ($is_html && $minify_html) {
			$content = Functions::minify_html($content);
		}

		if (strlen($content) > $max_length) {
			//Content length exceeds limit, return original content
			return $content;
		}

		// $translate function that translates a single chunk
		$translate = static function (string $text) use ($clone_id, $text_only): string {
			return TextTranslator::translateText($text, $clone_id , $text_only);
		};

		// Content within charlength limits: translate in one go.
		try {
			return $translate($content);
		} catch (\Throwable $e) {
			error_log('ClonableWooCommerceService translate_document error: ' . $e->getMessage());
			return $content;
		}
	}
}
