<?php
/**
 * Freemius SDK chrome in the plugin's selected language.
 *
 * The SDK's admin strings (menu items, opt-in, licence and contact screens)
 * live in the 'freemius' textdomain. Two gaps to close so they follow the
 * plugin's own language switcher (stwc_user_locale_pref):
 *
 *  1. The SDK loads its catalogue at plugins_loaded — before the current
 *     user (and their language preference) is known — so we route the
 *     'freemius' domain through the preference and reload the catalogue at
 *     init. Covers the locales the SDK ships: de_DE es_ES fr_FR it_IT (+ cs
 *     da he hu ja nl ru ta zh_CN).
 *
 *  2. The SDK ships NO catalogue for tr_TR, pt_BR or ar, so for those the
 *     visible chrome is translated here via the domain-scoped gettext
 *     filter.
 *
 * @package Stocktake_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

/**
 * The language the Freemius chrome should render in: the user's explicit
 * plugin-language choice, else the admin locale.
 *
 * @return string Locale code, e.g. 'tr_TR'.
 */
if ( ! function_exists( 'stwc_fs_i18n_locale' ) ) :
function stwc_fs_i18n_locale() {
	if ( function_exists( 'stwc_user_locale_pref' ) && did_action( 'init' ) ) {
		$pref = stwc_user_locale_pref();
		if ( 'auto' !== $pref ) {
			return $pref;
		}
	}
	return determine_locale();
}
endif;

// The SDK loaded its catalogue before the user preference was readable.
// Since WP 6.5 translations are stored PER LOCALE, so (exactly like the
// plugin's own switcher in the main file) the preferred .mo must be loaded
// under the CURRENT locale key for lookups to hit it; plain unload also
// stops the just-in-time loader pulling the site language back in.
add_action(
	'init',
	function () {
		if ( ! is_admin() || ! function_exists( 'stwc_user_locale_pref' ) ) {
			return;
		}
		$pref = stwc_user_locale_pref();
		if ( 'auto' === $pref ) {
			return;
		}
		// The 'freemius' textdomain is SHARED by every Freemius-SDK plugin;
		// only re-key it on OUR own admin screens so this per-user choice
		// can't change another plugin's Freemius chrome elsewhere.
		$stwc_page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( 0 !== strpos( $stwc_page, 'stwc-sessions' ) ) {
			return;
		}
		unload_textdomain( 'freemius' );
		if ( 'en_US' !== $pref ) {
			$mofile = STWC_PATH . 'freemius/languages/freemius-' . $pref . '.mo';
			if ( file_exists( $mofile ) ) {
				load_textdomain( 'freemius', $mofile, determine_locale() ); // phpcs:ignore WordPress.WP.AlternativeFunctions -- intentional direct load under the active locale key.
			}
			// No catalogue for this language (tr/pt_BR/ar): the domain stays
			// unloaded and the gettext maps below carry the visible chrome.
		}
	},
	20
);

/**
 * Curated chrome translations for the locales the SDK does not ship.
 *
 * @param string $translation Current translation.
 * @param string $text        Original string.
 * @return string
 */
if ( ! function_exists( 'stwc_fs_chrome_gettext' ) ) :
function stwc_fs_chrome_gettext( $translation, $text ) {
	// The 'freemius' textdomain is SHARED by every Freemius-SDK plugin; only
	// map chrome on OUR own admin screens (same scope as the catalogue re-key
	// above) so this per-user choice can't re-language another plugin's
	// Freemius chrome elsewhere.
	static $stwc_own_page = null;
	if ( null === $stwc_own_page ) {
		$stwc_page     = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$stwc_own_page = ( 0 === strpos( $stwc_page, 'stwc-sessions' ) );
	}
	if ( ! $stwc_own_page ) {
		return $translation;
	}

	static $maps = array(
		'tr' => array(
			'Upgrade'               => 'Yükselt',
			'Contact Us'            => 'Bize Ulaşın',
			'Account'               => 'Hesap',
			'Pricing'               => 'Fiyatlandırma',
			'Support'               => 'Destek',
			'Support Forum'         => 'Destek Forumu',
			'Add-Ons'               => 'Ek Paketler',
			'Skip'                  => 'Atla',
			'Allow & Continue'      => 'İzin Ver ve Devam Et',
			'Activate License'      => 'Lisansı Etkinleştir',
			'Activate Free Version' => 'Ücretsiz Sürümü Etkinleştir',
			'License key'           => 'Lisans anahtarı',
			'License'               => 'Lisans',
			'Change License'        => 'Lisansı Değiştir',
			'Sync'                  => 'Eşitle',
			'Send'                  => 'Gönder',
			'Message'               => 'Mesaj',
			'Subject'               => 'Konu',
			'Details'               => 'Ayrıntılar',
		),
		'pt' => array(
			'Upgrade'               => 'Fazer upgrade',
			'Contact Us'            => 'Fale Conosco',
			'Account'               => 'Conta',
			'Pricing'               => 'Preços',
			'Support'               => 'Suporte',
			'Support Forum'         => 'Fórum de Suporte',
			'Add-Ons'               => 'Complementos',
			'Skip'                  => 'Pular',
			'Allow & Continue'      => 'Permitir e Continuar',
			'Activate License'      => 'Ativar Licença',
			'Activate Free Version' => 'Ativar Versão Gratuita',
			'License key'           => 'Chave de licença',
			'License'               => 'Licença',
			'Change License'        => 'Alterar Licença',
			'Sync'                  => 'Sincronizar',
			'Send'                  => 'Enviar',
			'Message'               => 'Mensagem',
			'Subject'               => 'Assunto',
			'Details'               => 'Detalhes',
		),
		'ar' => array(
			'Upgrade'               => 'الترقية',
			'Contact Us'            => 'اتصل بنا',
			'Account'               => 'الحساب',
			'Pricing'               => 'الأسعار',
			'Support'               => 'الدعم',
			'Support Forum'         => 'منتدى الدعم',
			'Add-Ons'               => 'الإضافات',
			'Skip'                  => 'تخطي',
			'Allow & Continue'      => 'السماح والمتابعة',
			'Activate License'      => 'تفعيل الترخيص',
			'Activate Free Version' => 'تفعيل النسخة المجانية',
			'License key'           => 'مفتاح الترخيص',
			'License'               => 'الترخيص',
			'Change License'        => 'تغيير الترخيص',
			'Sync'                  => 'مزامنة',
			'Send'                  => 'إرسال',
			'Message'               => 'الرسالة',
			'Subject'               => 'الموضوع',
			'Details'               => 'التفاصيل',
		),
	);

	$lang = substr( stwc_fs_i18n_locale(), 0, 2 );
	if ( isset( $maps[ $lang ][ $text ] ) ) {
		return $maps[ $lang ][ $text ];
	}
	return $translation;
}
endif;
add_filter( 'gettext_freemius', 'stwc_fs_chrome_gettext', 10, 2 );

// Some SDK strings carry a gettext context (e.g. _x( 'Skip', 'verb' )) and
// bypass the plain filter; route them through the same maps.
add_filter(
	'gettext_with_context_freemius',
	function ( $translation, $text ) {
		return stwc_fs_chrome_gettext( $translation, $text );
	},
	10,
	2
);
