<?php

if (!function_exists('ppq_translate_config')) {
    function ppq_translate_config($source = null) {
        $allowed = array('zh-CN', 'zh-TW', 'en', 'ja', 'ko', 'vi', 'id', 'ms', 'th', 'fil', 'hi', 'fr');
        if (!is_array($source)) {
            $configFile = dirname(__DIR__, 2) . '/PPQSQL/Admin/Basic/AdminBasic.php';
            $source = is_file($configFile) ? json_decode(file_get_contents($configFile), true) : array();
        }
        if (!is_array($source)) {
            $source = array();
        }

        $languages = isset($source['FrontendTranslateLanguages']) && is_array($source['FrontendTranslateLanguages'])
            ? $source['FrontendTranslateLanguages'] : $allowed;
        $languages = array_values(array_unique(array_values(array_filter($languages, function ($language) use ($allowed) {
            return in_array($language, $allowed, true);
        }))));
        if (!in_array('zh-CN', $languages, true)) {
            array_unshift($languages, 'zh-CN');
        }
        /* 免费版限制：仅开放 简体中文 / 繁體中文 / English */
        $languages = array_values(array_intersect($languages, array('zh-CN', 'zh-TW', 'en')));
        if (empty($languages)) { $languages = array('zh-CN'); }

        $position = isset($source['FrontendTranslatePosition']) ? $source['FrontendTranslatePosition'] : 'bottom-right';
        if (!in_array($position, array('bottom-right', 'bottom-left'), true)) {
            $position = 'bottom-right';
        }

        return array(
            'enabled' => isset($source['FrontendTranslateOpen']) && (string)$source['FrontendTranslateOpen'] === '1',
            'auto' => !isset($source['FrontendTranslateAuto']) || (string)$source['FrontendTranslateAuto'] === '1',
            'position' => $position,
            'languages' => $languages,
            'baseLanguage' => 'zh-CN',
        );
    }
}

if (!function_exists('ppq_translate_assets')) {
    function ppq_translate_assets($source = null) {
        $config = ppq_translate_config($source);
        if (!$config['enabled']) {
            return '';
        }
        $json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return '<link rel="stylesheet" href="/Static/Home/ppq-translate.css?v=20260902a">'
            . '<script>window.PPQ_TRANSLATE_CONFIG=' . $json . ';</script>'
            . '<script src="/Static/Home/translate.js?v=20260902a" defer></script>'
            . '<script src="/Static/Home/ppq-translate.js?v=20260902a" defer></script>';
    }
}
