<?php
/**
 * ============================================================
 *  Custom Auth Suite — translations.php (Scalable Multi-language)
 * ============================================================
 *
 *  GOAL
 *  This file provides a scalable i18n layer for CAS.
 *  Instead of hardcoding EN/IT arrays inside each feature file,
 *  ALL user-facing strings should be translated via:
 *
 *      custausu_t('English String Key')
 *
 *  The "English string" is used as the translation KEY.
 *
 *  FALLBACK CHAIN
 *  When custausu_t($key) is called:
 *    1) it tries the active CAS and WordPress language context
 *    2) if missing, it tries SITE LANGUAGE (WPLANG → e.g. en, it, fr…)
 *    3) if missing, it tries 'en'
 *    4) if still missing, returns the original $key (safe)
 *
 *  ADDING NEW LANGUAGES
 *  1) Add a new top-level language key below:
 *        'tr' => [ 'Create Account' => '...' ],
 *        'sv' => [ 'Create Account' => '...' ],
 *  2) Translate ONLY the strings you want.
 *  3) Anything missing will fallback automatically.
 *
 *  BEST PRACTICE
 *  - Translate ONLY strings visible to end-users (UI/messages).
 *  - Do NOT translate debug log labels (keep logs in English).
 *
 *  USING WITH GETTEXT
 *  We keep the existing gettext filter so legacy templates that call
 *  __('Create Account') etc will still be translated automatically.
 *  New code should gradually switch to custausu_t().
 *
 *  ------------------------------------------------------------
 *  NOTE
 *  This file uses custausu_current_lang() when available, then the WordPress locale and EN.
 * ============================================================
 */

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


/**
 * Return the CAS translation dictionary.
 * You can extend this safely with new languages.
 */
if (!function_exists('custausu_translations_dict')) {
  function custausu_translations_dict(): array {

    return [

      /**
       * ======================
       * ITALIAN (it)
       * ======================
       */
      'it' => [
         
        // Math Check
        'How much is %d + %d?*' => 'Quanto fa %d + %d?*',

        // Template Register
        'Create Account'        => 'Crea Account',
        'First Name'            => 'Nome',
        'Last Name'             => 'Cognome',
        'Username'              => 'Username',
        'Username may only contain letters, numbers, hyphens (-), underscores (_) and dots (.)'
          => 'Lo username può contenere esclusivamente lettere, numeri, trattini (-), underscore (_) e punti (.)',
        'eMail'                 => 'eMail',
        'Password'              => 'Password',
        'Confirm Password'      => 'Conferma Password',
        'I accept the Privacy Policy' => 'Accetto i termini del servizio',
        'Read here'             => 'Leggi qui',
        'Register'              => 'Registrati',
        'Already registered?'   => 'Hai già un account?',
        'required field'        => 'campo obbligatorio',
        'Login'                 => 'Accedi',
        'Logout'                => 'Esci',
        'Your Profile'          => 'Il tuo Profilo',
        'Edit Profile'          => 'Modifica Profilo',
        '📩 Resend verification' => '📩 Invia verifica',
        'eMail verification'    => 'Verifica eMail',
        'Not verified'          => 'Non verificata',
        'Verified'              => 'Verificata',
        'Verification eMail sent successfully.' => 'eMail di verifica inviata con successo all\'utente.',
        'New registration'      => 'Nuova registrazione',
        '⚡️ New user registered on %s: %s' => '⚡️ Nuovo utente registrato su %s: %s',
        '✅ Thanks! Your email is now verified'=> '✅ Grazie! La tua email è stata verificata',
        '✅ Registration successful!<br />Check your inbox to confirm your account.' => '✅ Registrazione completata!<br />Controlla la tua email per confermare l\'account.',
        'Hi %s' => 'Ciao %s',
        
        
                /**
         * ===============================
         * EMAIL FOOTER KEYS ONLY (shared)
         * ===============================
         * Email bodies/subjects are edited in WP Admin HTML templates:
         *   custausu_global_settings[email_tpl]
         *
         * Keep HERE only tiny shared labels used by email wrappers/footers:
         *   - custausu_email_t($user_lang, 'Support')
         *   - custausu_email_t($user_lang, '— All rights reserved')
         *
         * IMPORTANT:
         * - These keys MUST exist at least in one dict language.
         * - custausu_email_t() has its own fallback chain, so missing langs won’t break.
         */
        'Support'               => 'Supporto',
        '— All rights reserved' => '— Tutti i diritti riservati',
        
        // Template Login
        'To listen to the albums in full version you need to login or register an account.<br />It doesn\'t cost you anything and it\'s a sign of your appreciation for my work.'
          => 'Per poter ascoltare gli album in versione integrale, è necessario effettuare il login o registrare un account.<br />Non ti costa niente ed è per me segno di apprezzamento per il mio lavoro da parte tua.',
        'Username or eMail'     => 'Username o eMail',
        'Remember Me'           => 'Ricordami',
        'Don’t have an account?' => 'Non hai un account?',
        'Create one'            => 'Creane uno',
        'Forgot Password?'      => 'Hai dimenticato la password?',
        '⚠️ Invalid login details. Please try again.' => '⚠️ Dati di Login errati. Riprova.',
          
         // ===== Login template (Portable + OET) =====
        'Show password' => 'Mostra password',
        'Hide password' => 'Nascondi password',

        // Portable H4 copy
        'Please login to continue.<br />If you don’t have an account yet, you can create one in a minute.'
         => 'Per continuare devi effettuare l’accesso.<br />Se non hai ancora un account, puoi crearlo in un minuto.',

        // Template Lost Password
        'Lost Password' => 'Recupero Password',
        'Enter your Username or eMail to receive a password reset link.'
          => 'Inserisci lo Username o l\'indirizzo eMail ad esso associato per ricevere il link di reset della password.',
        'Username or eMail' => 'Username o eMail',
        'Send Reset Link' => 'Ottieni Link',
        'Back to Login' => 'Torna al Login',
        'Create an Account' => 'Crea un Account',

        // Error messages (lost=...)
        '⚠️ Please enter your username or email.'
          => '⚠️ Inserisci username o email.',
        '⚠️ Security check failed.<br />Please quit browser and try again.'
          => '⚠️ Hai fallito il controllo di sicurezza.<br />Chiudi il browser e riprova.',
        '⚠️ Account not found.<br />Please check username/email and try again.'
          => '⚠️ Account non trovato.<br />Controlla username/email e riprova',
        '⚠️ Account is inactive.<br />Please contact website admin.'
          => '⚠️ L\'account non è attivo.<br />Contatta l\'admin del sito.',
        '⚠️ An unexpected error occurred.<br />Please try again later.'
          => '⚠️ Si è verificato un errore.<br />Riprova più tardi.',

        // Template Lost Password Confirmation
        'Check Your eMail' => 'Controlla la tua eMail',
        'Visit the link you just received to begin the password reset process.'
          => 'Visita il link che hai ricevuto per reimpostare la tua password.',
        'Back to Login' => 'Torna al Login',

        // Error messages
        'I need to know your Name.' => 'Devo sapere il tuo nome.',
        'Please pick a Username.'   => 'Scegli un username.',
        'Please input your Email.'  => 'Inserisci una email.',
        'Passwords do not match.'   => 'Le password non corrispondono.',
        'This eMail address is already registered.' => 'Questa email è già registrata.',
        'Username is already taken.' => 'Username già presente nel database.',
        'You must accept the Privacy Policy before registering.' => 'Per la registrazione è necessario accettare ii termini.',
        'An error occurred during the registration: %s' => 'Si è verificato un errore durante la registrazione: %s',
        'Security check failed. Please reload the page and try again.'
          => 'Hai fallito il controllo sicurezza. Ricarica la pagina e riprova.',
        'Security check failed. Please try again.'
          => 'Hai fallito il controllo sicurezza. Riprova.',
        'Google reCAPTCHA check failed. Quit browser session and try again.'
          => 'Controllo Google reCAPTCHA non riuscito. Chiudi il browser e riprova.',
        'Security Math check failed.'
          => 'Controllo matematico di sicurezza non superato.',
        '⚠️ Security check unavailable. Please reload the page.' => '⚠️ Controllo di sicurezza non disponibile. Ricarica la pagina.',

        ],

      /**
       * ======================
       * ENGLISH (en) — optional
       * ======================
       * You MAY keep it empty because EN is the key itself.
       * If you want, you can also define overrides here.
       */
      'en' => [

        // Keep this minimal: EN is usually the key itself.
        // Add only what you want to be explicit/stable for email footers & admin UI.

        // Email footer micro-labels (used by custausu_email_t)
        '— All rights reserved' => '— All rights reserved',
        'Support'               => 'Support',

        // Users admin column (optional explicit)
        'eMail verification'    => 'eMail verification',
        'Verified'              => 'Verified',
        'Not verified'          => 'Not verified',
        '📩 Resend verification' => '📩 Resend verification',
        'Verification eMail sent successfully.' => 'Verification eMail sent successfully.',

                
        // Health Check (admin)
        'Health Check' => 'Health Check',
        'Run check' => 'Run check',
        'Show' => 'Show',
        'Hide' => 'Hide',
        'Checks your environment and configuration.' => 'Checks your environment and configuration.',
        'Status' => 'Status',
        'Check' => 'Check',
        'Value' => 'Value',
        'Notes' => 'Notes',
        'Minimum required: PHP 8.1+ (recommended 8.4+).' => 'Minimum required: PHP 8.1+ (recommended 8.4+).',
        'Please update WordPress (recommended 6.x+).' => 'Please update WordPress (recommended 6.x+).',
        'Logs folder is not writable. Please check filesystem permissions.' => 'Logs folder is not writable. Please check filesystem permissions.',
        'If you want automatic multi-language support, install/activate Polylang.' => 'If you want automatic multi-language support, install/activate Polylang.',
        'CF7 is optional (only needed for Math Check).' => 'CF7 is optional (only needed for Math Check).',
        'active' => 'active',
        'not installed' => 'not installed',
        'enabled' => 'enabled',
        'disabled' => 'disabled',
        'Missing keys (or wp-config mode is OFF).' => 'Missing keys (or wp-config mode is OFF).',

        ],

      /**
       * ======================
       * EXAMPLES FOR NEW LANGUAGES
       * ======================
       *
       * 'tr' => [
       *   'Create Account' => 'Hesap Oluştur',
       * ],
       *
       * 'sv' => [
       *   'Create Account' => 'Skapa konto',
       * ],
       */
    ];
  }
}

/**
 * Normalize a language slug:
 * - "sv-SE" or "sv_SE" => "sv"
 * - "tr-TR" => "tr"
 */
if (!function_exists('custausu_norm_lang')) {
  function custausu_norm_lang(string $lang): string {
    $lang = strtolower(trim($lang));
    if ($lang === '') return '';
    $lang = str_replace('_', '-', $lang);
    $lang = preg_replace('/[^a-z0-9-]/', '', $lang);
    $parts = explode('-', $lang);
    $base = $parts[0] ?? $lang;
    $base = sanitize_key($base);
    return $base !== '' ? $base : '';
  }
}

/**
 * Detect the active CAS and WordPress language with fallbacks.
 */
if (!function_exists('custausu_detect_lang')) {
  function custausu_detect_lang(): string {
    if (function_exists('custausu_current_lang')) {
      $lang = custausu_norm_lang((string) custausu_current_lang());
      if (in_array($lang, ['en', 'it'], true)) return $lang;
    }

    $locale = function_exists('determine_locale')
      ? determine_locale()
      : get_locale();
    $lang = custausu_norm_lang((string) $locale);
    if (in_array($lang, ['en', 'it'], true)) return $lang;

    $site_locale = (string) get_option('WPLANG');
    $lang = custausu_norm_lang($site_locale !== '' ? $site_locale : 'en_US');
    return in_array($lang, ['en', 'it'], true) ? $lang : 'en';
  }
}

/**
 * custausu_t($key) — scalable translation getter with fallback chain:
 * current_lang -> site_lang -> en -> key
 */
if (!function_exists('custausu_t')) {
  function custausu_t(string $key, array $args = []): string {
    $key = (string)$key;

    $dict = (array) custausu_translations_dict();

    $cur = custausu_norm_lang(custausu_detect_lang());

    // site lang
    $site_locale = (string) get_option('WPLANG');
    if ($site_locale === '') $site_locale = 'en_US';
    $site = custausu_norm_lang((string)(explode('_', $site_locale)[0] ?? 'en'));
    if ($site === '') $site = 'en';

    // fallback chain
    $chain = array_values(array_unique(array_filter([$cur, $site, 'en'])));

    $out = '';
    foreach ($chain as $lng) {
      if (!empty($dict[$lng]) && is_array($dict[$lng]) && array_key_exists($key, $dict[$lng])) {
        $out = (string)$dict[$lng][$key];
        if ($out !== '') break;
      }
    }

    if ($out === '') $out = $key;

    // sprintf support (optional)
    if (!empty($args)) {
      if (array_values($args) === $args) {
        $tmp = @vsprintf($out, $args);
        if (is_string($tmp) && $tmp !== '') $out = $tmp;
      } else {
        foreach ($args as $k => $v) {
          $out = str_replace((string)$k, (string)$v, $out);
        }
      }
    }

    return $out;
  }
}

/**
 * custausu_t_lang($lang, $key) — translate using a SPECIFIC language (user_lang),
 * with fallback chain: $lang -> site_lang -> en -> key
 */
if (!function_exists('custausu_t_lang')) {
  function custausu_t_lang(string $lang, string $key, array $args = []): string {
    $key = (string)$key;

    $dict = (array) custausu_translations_dict();

    $lang = custausu_norm_lang($lang);

    // site lang
    $site_locale = (string) get_option('WPLANG');
    if ($site_locale === '') $site_locale = 'en_US';
    $site = custausu_norm_lang((string)(explode('_', $site_locale)[0] ?? 'en'));
    if ($site === '') $site = 'en';

    $chain = array_values(array_unique(array_filter([$lang, $site, 'en'])));

    $out = '';
    foreach ($chain as $lng) {
      if (!empty($dict[$lng]) && is_array($dict[$lng]) && array_key_exists($key, $dict[$lng])) {
        $out = (string)$dict[$lng][$key];
        if ($out !== '') break;
      }
    }

    if ($out === '') $out = $key;

    // sprintf support (same as custausu_t)
    if (!empty($args)) {
      if (array_values($args) === $args) {
        $tmp = @vsprintf($out, $args);
        if (is_string($tmp) && $tmp !== '') $out = $tmp;
      } else {
        foreach ($args as $k => $v) {
          $out = str_replace((string)$k, (string)$v, $out);
        }
      }
    }

    return $out;
  }
}

/**
 * Legacy support: translate via gettext filter.
 * This keeps your existing templates working without rewriting them immediately.
 * As you refactor feature files, prefer custausu_t() directly.
 */
add_filter('gettext', function($translated_text, $text, $domain) {

  // Only touch strings that exist in CAS dict.
  $dict = (array) custausu_translations_dict();

  $cur = custausu_norm_lang(custausu_detect_lang());

  // site lang
  $site_locale = (string) get_option('WPLANG');
  if ($site_locale === '') $site_locale = 'en_US';
  $site = custausu_norm_lang((string)(explode('_', $site_locale)[0] ?? 'en'));
  if ($site === '') $site = 'en';

  $chain = array_values(array_unique(array_filter([$cur, $site, 'en'])));

  foreach ($chain as $lng) {
    if (!empty($dict[$lng]) && is_array($dict[$lng]) && array_key_exists($text, $dict[$lng])) {
      $out = (string)$dict[$lng][$text];
      if ($out !== '') return $out;
    }
  }

  return $translated_text;

}, 10, 3);