<?php
if (!defined('ABSPATH')) exit;

/**
 * CAS shared email helpers.
 *
 * Shared by:
 * - Free email verification
 * - Admin user email verification column
 * - Premium WebAuthn verified-email gate
 */

if (!function_exists('custausu_email_norm_lang')) {
  function custausu_email_norm_lang(string $lang = ''): string {
    if (function_exists('custausu_norm_lang')) {
      $lang = (string) custausu_norm_lang($lang);
    } else {
      $lang = strtolower(trim((string) $lang));
      $lang = str_replace('_', '-', $lang);
      $lang = preg_replace('/[^a-z0-9-]/', '', $lang);
      $lang = explode('-', $lang)[0] ?? $lang;
      $lang = sanitize_key($lang);
    }

    return $lang !== '' ? $lang : 'en';
  }
}

if (!function_exists('custausu_email_allowed_langs')) {
  function custausu_email_allowed_langs(): array {
    $langs = (array) (function_exists('custausu_config') ? custausu_config('i18n.langs', []) : []);

    $langs = array_values(array_filter(array_map(static function ($x) {
      $x = custausu_email_norm_lang((string) $x);
      return $x !== '' ? $x : null;
    }, $langs)));

    $default = custausu_email_norm_lang((string) (function_exists('custausu_config') ? custausu_config('routes.policy.default_lang', 'en') : 'en'));

    if (empty($langs)) {
      $langs = [$default ?: 'en'];
    }

    $out = [];

    foreach ($langs as $lang) {
      $out[$lang] = true;
    }

    return array_keys($out);
  }
}

if (!function_exists('custausu_email_pick_lang')) {
  function custausu_email_pick_lang(string $lang = ''): string {
    $allowed = custausu_email_allowed_langs();
    $default = custausu_email_norm_lang((string) (function_exists('custausu_config') ? custausu_config('routes.policy.default_lang', 'en') : 'en'));

    $lang = custausu_email_norm_lang($lang);

    if ($lang !== '' && in_array($lang, $allowed, true)) {
      return $lang;
    }

    if ($default !== '' && in_array($default, $allowed, true)) {
      return $default;
    }

    return (string) ($allowed[0] ?? 'en');
  }
}

if (!function_exists('custausu_email_t')) {
  function custausu_email_t(string $lang, string $key, array $args = []): string {
    $key = (string) $key;
    $lang = custausu_email_pick_lang($lang);

    $dict = function_exists('custausu_translations_dict') ? (array) custausu_translations_dict() : [];
    $dict_langs_raw = array_keys(is_array($dict) ? $dict : []);

    $dict_langs = array_values(array_unique(array_filter(array_map(static function ($x) {
      return custausu_email_norm_lang((string) $x);
    }, $dict_langs_raw))));

    $site_locale = (string) get_option('WPLANG');

    if ($site_locale === '') {
      $site_locale = 'en_US';
    }

    $site = custausu_email_norm_lang((string) (explode('_', $site_locale)[0] ?? 'en'));

    if ($site === '') {
      $site = 'en';
    }

    $allowed = custausu_email_allowed_langs();
    $default = custausu_email_norm_lang((string) (function_exists('custausu_config') ? custausu_config('routes.policy.default_lang', 'en') : 'en'));
    $fallback = $default ?: (string) ($allowed[0] ?? 'en');

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

    if (!in_array('en', $chain, true) && in_array('en', $dict_langs, true)) {
      $chain[] = 'en';
    } elseif (!empty($dict_langs)) {
      $first_dict = '';

      if (!empty($allowed)) {
        foreach ($allowed as $allowed_lang) {
          $allowed_lang = custausu_email_norm_lang((string) $allowed_lang);

          if ($allowed_lang !== '' && in_array($allowed_lang, $dict_langs, true)) {
            $first_dict = $allowed_lang;
            break;
          }
        }
      }

      if ($first_dict === '') {
        $first_dict = (string) ($dict_langs[0] ?? '');
      }

      if ($first_dict !== '' && !in_array($first_dict, $chain, true)) {
        $chain[] = $first_dict;
      }
    }

    $dict_norm = [];

    foreach ($dict as $dict_key => $dict_value) {
      $normalized_key = custausu_email_norm_lang((string) $dict_key);

      if ($normalized_key !== '' && is_array($dict_value)) {
        $dict_norm[$normalized_key] = $dict_value;
      }
    }

    $out = '';

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

        if ($out !== '') {
          break;
        }
      }
    }

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

    if (!empty($args)) {
      if (array_values($args) === $args) {
        $tmp = @vsprintf($out, $args);

        if (is_string($tmp) && $tmp !== '') {
          $out = $tmp;
        }
      } else {
        foreach ($args as $arg_key => $arg_value) {
          $out = str_replace((string) $arg_key, (string) $arg_value, $out);
        }
      }
    }

    return $out;
  }
}

if (!function_exists('custausu_is_email_verified')) {
  function custausu_is_email_verified(int $user_id): bool {
    if ($user_id <= 0) {
      return false;
    }

    $user = get_userdata($user_id);

    if (!$user || empty($user->user_email)) {
      return false;
    }

    $email = (string) $user->user_email;

    if (
      function_exists('custausu_db_email_verifications_is_ready') &&
      custausu_db_email_verifications_is_ready() &&
      function_exists('custausu_db_email_verifications_is_user_email_verified')
    ) {
      $verified = custausu_db_email_verifications_is_user_email_verified($user_id, $email);

      if ($verified) {
        if ((string) get_user_meta($user_id, 'email_verified', true) !== 'yes') {
          update_user_meta($user_id, 'email_verified', 'yes');
        }

        if ((string) get_user_meta($user_id, 'email_verified_at', true) === '') {
          update_user_meta($user_id, 'email_verified_at', (string) time());
        }

        return true;
      }

      if (
        (string) get_user_meta($user_id, 'email_verified', true) === 'yes' &&
        function_exists('custausu_db_email_verifications_mark_user_email_verified')
      ) {
        $repaired = custausu_db_email_verifications_mark_user_email_verified(
          (int) $user_id,
          (string) $email,
          'wp_email_change',
          [
            'source'        => 'wp_meta_repair_after_wp_email_change',
            'repair_reason' => 'current_email_not_used_in_sql_but_wp_meta_verified',
          ]
        );

        if (
          $repaired &&
          function_exists('custausu_db_email_verifications_is_user_email_verified') &&
          custausu_db_email_verifications_is_user_email_verified($user_id, $email)
        ) {
          return true;
        }
      }

      return false;
    }

    return ((string) get_user_meta($user_id, 'email_verified', true) === 'yes');
  }
}

if (!function_exists('custausu_email_settings_get')) {
  function custausu_email_settings_get(): array {
    $opt = get_option('custausu_global_settings', []);
    return is_array($opt) ? $opt : [];
  }
}

if (!function_exists('custausu_email_theme_get')) {
  function custausu_email_theme_get(): array {
    $opt = custausu_email_settings_get();
    $theme = (array) ($opt['email_theme'] ?? []);

    $defaults = [
      'wrap_bg'     => '#000000',
      'wrap_border' => '#ff4437',
      'wrap_text'   => '#ffffff',
      'h2_color'    => '#06d6a0',
      'btn_bg'      => '#06d6a0',
      'btn_text'    => '#036349',
    ];

    $theme = array_merge($defaults, $theme);

    foreach ($theme as $key => $value) {
      $clean = is_string($value) ? sanitize_hex_color($value) : '';
      $theme[$key] = $clean ?: ($defaults[$key] ?? '#000000');
    }

    return $theme;
  }
}

if (!function_exists('custausu_email_tpl_get')) {
  function custausu_email_tpl_get(string $lang, string $type): array {
    $lang = custausu_email_pick_lang($lang);
    $type = sanitize_key($type);

    $opt = custausu_email_settings_get();
    $tpl = (array) ($opt['email_tpl'] ?? []);

    $subject = (string) ($tpl[$lang][$type]['subject'] ?? '');
    $body = (string) ($tpl[$lang][$type]['body'] ?? '');

    if (($subject === '' || $body === '') && function_exists('custausu_email_tpl_defaults')) {
      $defaults = custausu_email_tpl_defaults();

      if (is_array($defaults)) {
        $default_subject = '';
        $default_body = '';

        if (isset($defaults[$lang][$type]) && is_array($defaults[$lang][$type])) {
          $default_subject = (string) ($defaults[$lang][$type]['subject'] ?? '');
          $default_body = (string) ($defaults[$lang][$type]['body'] ?? '');
        } elseif (isset($defaults[$type][$lang]) && is_array($defaults[$type][$lang])) {
          $default_subject = (string) ($defaults[$type][$lang]['subject'] ?? '');
          $default_body = (string) ($defaults[$type][$lang]['body'] ?? '');
        } elseif (isset($defaults['en'][$type]) && is_array($defaults['en'][$type])) {
          $default_subject = (string) ($defaults['en'][$type]['subject'] ?? '');
          $default_body = (string) ($defaults['en'][$type]['body'] ?? '');
        }

        if ($subject === '') {
          $subject = $default_subject;
        }

        if ($body === '') {
          $body = $default_body;
        }
      }
    }

    return [
      'subject' => sanitize_text_field($subject),
      'body'    => is_string($body) ? $body : '',
    ];
  }
}

if (!function_exists('custausu_email_tpl_apply_vars')) {
  function custausu_email_tpl_apply_vars(string $html, array $vars): string {
    if ($html === '') {
      return '';
    }

    foreach ($vars as $key => $value) {
      $html = str_replace('{{' . $key . '}}', (string) $value, $html);
    }

    return $html;
  }
}
