<?php
defined('ABSPATH') || exit;

if (! function_exists('reeid_detect_target_language')) {
    /**
     * Detect current target language code.
     *
     * @return string
     */
    function reeid_detect_target_language(): string
    {
        if (function_exists('pll_current_language')) {
            $lang = pll_current_language();
            if ($lang) {
                return (string) $lang;
            }
        }

        if (defined('ICL_LANGUAGE_CODE')) {
            return (string) ICL_LANGUAGE_CODE;
        }

        $locale = get_locale() ?: '';
        if ($locale === '') {
            return '';
        }

        if (strpos($locale, '_') !== false) {
            return substr($locale, 0, strpos($locale, '_'));
        }

        return (string) $locale;
    }
}

if (! function_exists('reeid_clear_woo_string_cache')) {
    /**
     * Clear cached static translations for a language.
     *
     * @param string $lang Language code.
     * @return void
     */
    function reeid_clear_woo_string_cache($lang): void
    {
        $opt_name = 'reeid_woo_strings_' . sanitize_key((string) $lang);
        delete_option($opt_name);
    }
}

if (! function_exists('reeid_get_translated_woocommerce_strings')) {
    /**
     * Return original => translated map for common WooCommerce strings.
     *
     * @param string $target_lang   Target language.
     * @param bool   $force_refresh Force refresh.
     * @return array
     */
    function reeid_get_translated_woocommerce_strings($target_lang, $force_refresh = false): array
    {
        $target_lang = (string) $target_lang;
        if ($target_lang === '') {
            return [];
        }

        $opt_name = 'reeid_woo_strings_' . sanitize_key($target_lang);

        if (! $force_refresh) {
            $cached = get_option($opt_name);
            if (is_array($cached) && ! empty($cached)) {
                return $cached;
            }
        }

        if (! is_admin() && ! wp_doing_ajax()) {
            return [];
        }

        $strings = [
            'Home',
            'Description',
            'Additional information',
            'Reviews',
            'Related products',
            'You may also like&hellip;',
            'SKU:',
            'Category:',
            'Tags:',
            'Only %s left in stock - order soon.',
            'Add to cart',
            'Out of stock',
            'In stock',
            'View cart',
            'Uncategorized',
        ];

        $input_map = [];
        foreach ($strings as $s) {
            $input_map[$s] = $s;
        }

        $json_in = wp_json_encode($input_map, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        $prompt = "Task: Translate the JSON VALUES to {$target_lang}. Keep keys EXACTLY unchanged and return STRICT JSON object only.\n"
            . "- Do not change formatting placeholders like %s, %d, HTML entities, or markup.\n"
            . "- Preserve punctuation and trailing colons where present.\n"
            . "- Return JSON only.";

        $out = reeid_translate_html_with_openai(
            $prompt . "\n" . $json_in,
            'en',
            $target_lang,
            'classic',
            'neutral',
            ['response_format' => ['type' => 'json_object']]
        );

        $translations = [];

        if (is_string($out)) {
            if (preg_match('/\{.*\}/s', $out, $m)) {
                $clean = $m[0];
            } else {
                $clean = $out;
            }

            if (function_exists('reeid_json_sanitize_controls_v2')) {
                $clean = reeid_json_sanitize_controls_v2($clean, []);
            }

            if (function_exists('reeid_safe_json_decode')) {
                $decoded = reeid_safe_json_decode($clean);
            } else {
                $decoded = json_decode($clean, true);
            }

            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $translations = $decoded;
            }
        }

        if (empty($translations)) {
            foreach ($input_map as $k => $v) {
                $tr = reeid_translate_html_with_openai($v, 'en', $target_lang, 'classic', 'neutral');
                $translations[$k] = (is_wp_error($tr) || empty($tr)) ? $v : (string) $tr;
            }
        }

        update_option($opt_name, $translations, false);

        return $translations;
    }
}

if (! function_exists('reeid_woo_normalize_candidates')) {
    /**
     * Build candidate keys for Woo static string matching.
     *
     * @param string $text Source text.
     * @return array
     */
    function reeid_woo_normalize_candidates($text): array
    {
        $cands   = [];
        $orig    = (string) $text;
        $cands[] = $orig;

        $trim = trim($orig);
        if ($trim !== $orig) {
            $cands[] = $trim;
        }

        $decoded = html_entity_decode($trim, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        if ($decoded !== $trim) {
            $cands[] = $decoded;
        }

        if (substr($trim, -1) === ':') {
            $cands[] = rtrim($trim, ':');
        }

        $lower = function_exists('mb_strtolower') ? mb_strtolower($trim, 'UTF-8') : strtolower($trim);
        if ($lower !== $trim) {
            $cands[] = $lower;
        }

        $out = [];
        foreach ($cands as $v) {
            if ($v === '') {
                continue;
            }
            if (! in_array($v, $out, true)) {
                $out[] = $v;
            }
        }

        return $out;
    }
}