<?php

namespace ChinaPayments\Optimizations;

use ChinaPayments\Settings;
class ChineseLocalization {
    /**
     * @var ChineseLocalization|null
     */
    protected static $_instance = null;

    /**
     * @var array
     */
    protected $_translations = array();

    public static function instance() : ChineseLocalization {
        if ( self::$_instance === null ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function setup() {
        if ( !$this->_is_enabled() ) {
            return;
        }
        if ( is_admin() ) {
            return;
        }
        // FULL-COVERAGE LOCALE: force the WordPress locale to the configured
        // storefront locale (default zh_CN for backward compat with the legacy
        // `chinese_localization_enabled` toggle). WP will then automatically
        // load every available .mo file for that locale — WP core, WooCommerce,
        // the plugin's own strings, the theme, every active plugin — instead
        // of relying on our 12-entry override dictionary alone.
        //
        // REQUIRES the language pack to be installed (admin: Tools → wp-cli
        //   `wp language plugin install woocommerce zh_CN`
        //   `wp language plugin install wp-stripe-global-payments zh_CN`
        //   `wp language core install zh_CN`).
        //
        // The override dictionary stays loaded with priority 100 (highest
        // reasonable) so plugin-specific phrasing overrides anything in the
        // WP.org translation set.
        add_filter( 'locale', array($this, '_force_storefront_locale'), 1 );
        add_filter( 'determine_locale', array($this, '_force_storefront_locale'), 1 );
        $this->_load_translations();
        add_filter(
            'gettext',
            array($this, '_translate_string'),
            100,
            3
        );
        add_filter(
            'gettext_with_context',
            array($this, '_translate_string_with_context'),
            100,
            4
        );
        add_filter(
            'ngettext',
            array($this, '_translate_plural'),
            100,
            5
        );
        // Enqueue frontend JS for WooCommerce Blocks translation (some block
        // strings are React-rendered and not caught by PHP gettext filters).
        add_action( 'wp_enqueue_scripts', array($this, '_enqueue_frontend_script') );
    }

    /**
     * Force the storefront locale. Returns the locale configured in plugin
     * settings (`storefront_locale` if set, otherwise 'zh_CN' for legacy
     * `chinese_localization_enabled=1` users). Admin context is never affected
     * because setup() bails out on is_admin().
     *
     * @param string $locale Locale WP would otherwise use (e.g. 'en_US').
     * @return string
     */
    public function _force_storefront_locale( $locale ) {
        $forced = Settings::instance()->get( 'storefront_locale' );
        if ( !empty( $forced ) && is_string( $forced ) ) {
            return $forced;
        }
        // Legacy behaviour: chinese_localization_enabled=1 implies zh_CN.
        return 'zh_CN';
    }

    protected function _is_enabled() : bool {
        if ( !function_exists( 'china_payments_fs' ) ) {
            return false;
        }
        return false;
        if ( !china_payments_fs()->can_use_premium_code() ) {
            return false;
        }
        return (bool) Settings::instance()->get( 'chinese_localization_enabled' );
    }

    protected function _load_translations() {
        $translations_file = CHINA_PAYMENTS_BASE_PATH . '/app/Optimizations/translations/woocommerce-zh_CN.php';
        if ( file_exists( $translations_file ) ) {
            $this->_translations = (include $translations_file);
        }
    }

    /**
     * Filter gettext for WooCommerce domains.
     *
     * @param string $translated Translated string
     * @param string $text       Original string
     * @param string $domain     Text domain
     * @return string
     */
    public function _translate_string( $translated, $text, $domain ) {
        if ( !$this->_is_supported_domain( $domain ) ) {
            return $translated;
        }
        if ( isset( $this->_translations[$text] ) ) {
            return $this->_translations[$text];
        }
        return $translated;
    }

    /**
     * Filter gettext_with_context for WooCommerce domains.
     */
    public function _translate_string_with_context(
        $translated,
        $text,
        $context,
        $domain
    ) {
        if ( !$this->_is_supported_domain( $domain ) ) {
            return $translated;
        }
        $key_with_context = $text . '|' . $context;
        if ( isset( $this->_translations[$key_with_context] ) ) {
            return $this->_translations[$key_with_context];
        }
        if ( isset( $this->_translations[$text] ) ) {
            return $this->_translations[$text];
        }
        return $translated;
    }

    /**
     * Filter ngettext for WooCommerce domains.
     */
    public function _translate_plural(
        $translated,
        $single,
        $plural,
        $number,
        $domain
    ) {
        if ( !$this->_is_supported_domain( $domain ) ) {
            return $translated;
        }
        $key = ( $number === 1 ? $single : $plural );
        if ( isset( $this->_translations[$key] ) ) {
            return $this->_translations[$key];
        }
        return $translated;
    }

    /**
     * Enqueue frontend JS for WooCommerce Blocks translation.
     *
     * WooCommerce Blocks (Cart/Checkout) render via React, so PHP gettext
     * filters don't catch their strings. This script translates them in
     * the browser DOM using MutationObserver.
     */
    public function _enqueue_frontend_script() {
        // Only enqueue on frontend WooCommerce pages
        if ( is_admin() ) {
            return;
        }
        $script_url = plugins_url( 'interface/js/chinese-localization-frontend.js', CHINA_PAYMENTS_BASE_FILE_PATH );
        wp_enqueue_script(
            'china-payments-localization-frontend',
            $script_url,
            array(),
            CHINA_PAYMENTS_VERSION,
            true
        );
        wp_localize_script( 'china-payments-localization-frontend', 'chinaPaymentsLocalization', array(
            'translations' => $this->_translations,
        ) );
    }

    /**
     * Check if the text domain should be translated.
     */
    protected function _is_supported_domain( $domain ) : bool {
        return in_array( $domain, array(
            'woocommerce',
            'woo-gutenberg-products-block',
            'wc-blocks',
            'default',
            'wp-stripe-global-payments'
        ), true );
    }

}
