<?php

if(!defined('ABSPATH'))
    exit;

class SyrusDeepL {
    
    private static $instance;
    private $api_key;
    private $api_url_free = 'https://api-free.deepl.com/v2/';
    private $api_url_pro = 'https://api.deepl.com/v2/';
    private $is_pro = false;
    
    private $supported_languages = [
        'source' => [
            'AUTO' => 'Auto-detect',
            'BG' => 'Bulgarian',
            'CS' => 'Czech', 
            'DA' => 'Danish',
            'DE' => 'German',
            'EL' => 'Greek',
            'EN' => 'English',
            'ES' => 'Spanish',
            'ET' => 'Estonian',
            'FI' => 'Finnish',
            'FR' => 'French',
            'HU' => 'Hungarian',
            'ID' => 'Indonesian',
            'IT' => 'Italian',
            'JA' => 'Japanese',
            'KO' => 'Korean',
            'LT' => 'Lithuanian',
            'LV' => 'Latvian',
            'NB' => 'Norwegian',
            'NL' => 'Dutch',
            'PL' => 'Polish',
            'PT' => 'Portuguese',
            'RO' => 'Romanian',
            'RU' => 'Russian',
            'SK' => 'Slovak',
            'SL' => 'Slovenian',
            'SV' => 'Swedish',
            'TR' => 'Turkish',
            'UK' => 'Ukrainian',
            'ZH' => 'Chinese'
        ],
        'target' => [
            'BG' => 'Bulgarian',
            'CS' => 'Czech',
            'DA' => 'Danish',
            'DE' => 'German',
            'EL' => 'Greek',
            'EN-GB' => 'English (British)',
            'EN-US' => 'English (American)',
            'ES' => 'Spanish',
            'ET' => 'Estonian',
            'FI' => 'Finnish',
            'FR' => 'French',
            'HU' => 'Hungarian',
            'ID' => 'Indonesian',
            'IT' => 'Italian',
            'JA' => 'Japanese',
            'KO' => 'Korean',
            'LT' => 'Lithuanian',
            'LV' => 'Latvian',
            'NB' => 'Norwegian',
            'NL' => 'Dutch',
            'PL' => 'Polish',
            'PT-BR' => 'Portuguese (Brazilian)',
            'PT-PT' => 'Portuguese (European)',
            'RO' => 'Romanian',
            'RU' => 'Russian',
            'SK' => 'Slovak',
            'SL' => 'Slovenian',
            'SV' => 'Swedish',
            'TR' => 'Turkish',
            'UK' => 'Ukrainian',
            'ZH' => 'Chinese (simplified)'
        ]
    ];

    public function __construct($api_key = null) {
        if($api_key) {
            $this->setApiKey($api_key);
        }
    }

    public static function getInstance($api_key = null) {
        if(!isset(self::$instance)) {
            self::$instance = new self($api_key);
        }
        
        if($api_key && !self::$instance->api_key) {
            self::$instance->setApiKey($api_key);
        }
        
        return self::$instance;
    }

    public function setApiKey($api_key) {
        $this->api_key = $api_key;
        $this->is_pro = strpos($api_key, ':fx') === false;
    }

    public function getApiKey() {
        return $this->api_key;
    }

    public function hasApiKey() {
        return !empty($this->api_key);
    }

    public function getApiUrl() {
        return $this->is_pro ? $this->api_url_pro : $this->api_url_free;
    }

    public function getSupportedLanguages($type = 'source') {
        return $this->supported_languages[$type] ?? [];
    }

    public function translate($text, $target_lang, $source_lang = null, $options = []) {
        if(!$this->hasApiKey()) {
            return ['error' => true, 'message' => 'API key not configured'];
        }

        if(empty($text)) {
            return ['error' => true, 'message' => 'Text cannot be empty'];
        }

        $params = [
            'text' => $text,
            'target_lang' => $target_lang
        ];

        if($source_lang && $source_lang !== 'AUTO') {
            $params['source_lang'] = $source_lang;
        }

        if(isset($options['preserve_formatting'])) {
            $params['preserve_formatting'] = $options['preserve_formatting'];
        }

        if(isset($options['formality'])) {
            $params['formality'] = $options['formality'];
        }

        if(isset($options['tag_handling'])) {
            $params['tag_handling'] = $options['tag_handling'];
        } else {
            $params['tag_handling'] = 'html';
        }

        $response = $this->makeApiCall('translate', $params);

        if(isset($response['error'])) {
            return $response;
        }

        if(isset($response['translations']) && count($response['translations']) > 0) {
            return [
                'success' => true,
                'text' => $response['translations'][0]['text'],
                'detected_source_language' => $response['translations'][0]['detected_source_language'] ?? null
            ];
        }

        return ['error' => true, 'message' => 'Translation failed'];
    }

    public function getUsage() {
        if(!$this->hasApiKey()) {
            return ['error' => true, 'message' => 'API key not configured'];
        }

        return $this->makeApiCall('usage');
    }

    public function getLanguages($type = 'source') {
        if(!$this->hasApiKey()) {
            return ['error' => true, 'message' => 'API key not configured'];
        }

        $endpoint = $type === 'source' ? 'languages?type=source' : 'languages?type=target';
        return $this->makeApiCall($endpoint);
    }

    private function makeApiCall($endpoint, $data = null) {
        $url = $this->getApiUrl() . $endpoint;

        $args = [
            'headers' => [
                'Authorization' => 'DeepL-Auth-Key ' . $this->api_key,
                'Content-Type' => 'application/x-www-form-urlencoded'
            ],
            'timeout' => 30
        ];

        if($data) {
            $args['body'] = http_build_query($data);
            $args['method'] = 'POST';
        } else {
            $args['method'] = 'GET';
        }

        $response = wp_remote_request($url, $args);

        if(is_wp_error($response)) {
            return [
                'error' => true,
                'message' => $response->get_error_message()
            ];
        }

        $body = wp_remote_retrieve_body($response);
        $http_code = wp_remote_retrieve_response_code($response);

        if($http_code !== 200) {
            $error_data = json_decode($body, true);
            return [
                'error' => true,
                'message' => $error_data['message'] ?? 'API Error: HTTP ' . $http_code,
                'code' => $http_code
            ];
        }

        return json_decode($body, true);
    }

    public function translateBatch($texts, $target_lang, $source_lang = null, $options = []) {
        if(!is_array($texts)) {
            return ['error' => true, 'message' => 'Texts must be an array'];
        }

        if(!$this->hasApiKey()) {
            return ['error' => true, 'message' => 'API key not configured'];
        }

        $params = [
            'text' => $texts,
            'target_lang' => $target_lang
        ];

        if($source_lang && $source_lang !== 'AUTO') {
            $params['source_lang'] = $source_lang;
        }

        if(isset($options['preserve_formatting'])) {
            $params['preserve_formatting'] = $options['preserve_formatting'];
        }

        if(isset($options['formality'])) {
            $params['formality'] = $options['formality'];
        }

        if(isset($options['tag_handling'])) {
            $params['tag_handling'] = $options['tag_handling'];
        } else {
            $params['tag_handling'] = 'html';
        }

        $response = $this->makeApiCall('translate', $params);

        if(isset($response['error'])) {
            return $response;
        }

        if(isset($response['translations'])) {
            $translated_texts = [];
            foreach($response['translations'] as $translation) {
                $translated_texts[] = $translation['text'];
            }
            return [
                'success' => true,
                'texts' => $translated_texts,
                'detected_source_language' => $response['translations'][0]['detected_source_language'] ?? null
            ];
        }

        return ['error' => true, 'message' => 'Translation failed'];
    }

    public static function isConfigured() {
        global $syrus;
        $api_key = $syrus->get_option('generali', 'deepl_api_key');
        return !empty($api_key);
    }
}