<?php
if (!function_exists('custausu_user_admin_columns_label')) {
    function custausu_user_admin_columns_label(string $key): string {
        $key = sanitize_key($key);

        $labels = [
            'email_verified' => esc_html__('eMail verified', 'custom-auth-suite'),
            'custausu_email_verified' => esc_html__('eMail verified', 'custom-auth-suite'),
            'verification_status' => esc_html__('Verification status', 'custom-auth-suite'),
            'custausu_verification_status' => esc_html__('Verification status', 'custom-auth-suite'),
            'registered' => esc_html__('Registered', 'custom-auth-suite'),
            'last_login' => esc_html__('Last login', 'custom-auth-suite'),
            'custausu_last_login' => esc_html__('Last login', 'custom-auth-suite'),
            'auth_method' => esc_html__('Auth method', 'custom-auth-suite'),
            'custausu_auth_method' => esc_html__('Auth method', 'custom-auth-suite'),
        ];

        return $labels[$key] ?? esc_html(ucwords(str_replace('_', ' ', $key)));
    }
}


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

/**
 * Users list email verification column and resend workflow.
 *
 * UI strings use CAS translations when available.
 * Resent verification emails follow user_lang saved at registration time.
 */

/* ============================================================================
   Admin UI helpers
============================================================================ */

if (!function_exists('custausu_ui_t')) {
  function custausu_ui_t(string $key, array $args = []): string {
    if (function_exists('custausu_t')) return custausu_t($key, $args);
    // Fallback to gettext when CAS translations are unavailable.
    $out = custausu_user_admin_columns_label((string) $key);
    if (!empty($args) && is_string($out)) {
      $tmp = @vsprintf($out, $args);
      if (is_string($tmp) && $tmp !== '') $out = $tmp;
    }
    return (string)$out;
  }
}

/* ============================================================================
   1) Column
============================================================================ */

if (!function_exists('custausu_user_admin_columns_enqueue_style')) {
  function custausu_user_admin_columns_enqueue_style(string $hook): void {
    if ($hook !== 'users.php') return;

    $style_path = CUSTAUSU_PLUGIN_DIR . 'inc/css/custausu-user-admin-columns.css';

    wp_enqueue_style(
      'custausu-user-admin-columns',
      CUSTAUSU_PLUGIN_URL . 'inc/css/custausu-user-admin-columns.css',
      [],
      is_readable($style_path) ? (string) filemtime($style_path) : CUSTAUSU_VERSION
    );
  }
}
add_action('admin_enqueue_scripts', 'custausu_user_admin_columns_enqueue_style');

add_filter('manage_users_columns', function($columns){
  $columns['email_verified'] = custausu_ui_t('eMail verification');
  return $columns;
});

/* ============================================================================
   2) Column content
============================================================================ */

add_filter('manage_users_custom_column', function($value, $column_name, $user_id){

  if ($column_name !== 'email_verified') return $value;

  $verified = function_exists('custausu_is_email_verified')
    ? custausu_is_email_verified((int) $user_id)
    : ((string) get_user_meta($user_id, 'email_verified', true) === 'yes');

  if ($verified) {
    return '<span class="custausu-email-verification-status custausu-email-verification-status--verified">'
      . esc_html(custausu_ui_t('Verified')) .
    '</span>';
  }

  $url = wp_nonce_url(
    admin_url('users.php?send_email_verification=' . (int)$user_id),
    'send_email_verification_' . (int)$user_id
  );

  return '<span class="custausu-email-verification-status custausu-email-verification-status--unverified">'
      . esc_html(custausu_ui_t('Not verified')) .
    '</span><br>
    <a href="' . esc_url($url) . '" class="custausu-email-verification-resend">'
      . esc_html(custausu_ui_t('📩 Resend verification')) .
    '</a>';

}, 10, 3);

/* ============================================================================
   3) Resend handler (admin_init)
============================================================================ */

add_action('admin_init', function(){

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin resend action target is read before nonce verification so the nonce action can include the user ID.
  if (!isset($_GET['send_email_verification'])) return;
  if (!current_user_can('edit_users')) return;

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin resend action target is sanitized before building the nonce action string.
  $user_id = isset($_GET['send_email_verification']) ? absint(wp_unslash($_GET['send_email_verification'])) : 0;
  if ($user_id <= 0) return;

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce value is sanitized immediately and verified below.
  $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
  if (!wp_verify_nonce($nonce, 'send_email_verification_' . $user_id)) return;

  $user = get_userdata($user_id);
  if (!$user || !$user->user_email) return;

  // Generate a fresh verification token.
  $token = wp_generate_password(32, false);
  update_user_meta($user_id, 'email_verified', 'no');

  $expires_ts = time() + 48 * HOUR_IN_SECONDS;
  $expires_at = function_exists('custausu_db_email_verifications_ts_to_mysql_utc')
    ? custausu_db_email_verifications_ts_to_mysql_utc($expires_ts)
    : gmdate('Y-m-d H:i:s', $expires_ts);

  $stored_in_db = (
    function_exists('custausu_db_email_verifications_is_ready') &&
    custausu_db_email_verifications_is_ready() &&
    function_exists('custausu_db_email_verifications_create_or_replace_pending')
  ) ? custausu_db_email_verifications_create_or_replace_pending(
      (int) $user_id,
      (string) $user->user_email,
      (string) $token,
      $expires_at,
      'register_verify',
      [
        'source' => 'admin_resend',
      ]
    ) : false;

  if (!$stored_in_db) {
    if (function_exists('custausu_log')) {
      custausu_log('email', 'email verification resend could not be stored in custom DB', [
        'user_id' => (int) $user_id,
        'email'   => (string) $user->user_email,
      ], 'error');
    }
    wp_safe_redirect(admin_url('users.php?verify_sent=2'));
    exit;
  }

  delete_user_meta($user_id, 'email_verification_token');
  delete_user_meta($user_id, 'email_verification_expires');

  // Source of truth for email language: user_lang saved at registration.
  $raw_lang = (string) get_user_meta($user_id, 'user_lang', true);
  if ($raw_lang === '' && function_exists('custausu_user_lang')) {
    $raw_lang = (string) custausu_user_lang($user_id, (string) (function_exists('custausu_config') ? custausu_config('routes.policy.default_lang','en') : 'en'));
  }
  $lang = custausu_email_pick_lang($raw_lang);

  // Base URL for the selected language.
  $base_url = function_exists('custausu_home_url_for_lang')
    ? (string) custausu_home_url_for_lang($lang)
    : home_url('/');

  $verify_link = add_query_arg([
    'verify_email' => $user_id,
    'token'        => $token,
  ], $base_url);

    // Email template from CAS admin settings.
  $theme = custausu_email_theme_get();
  $tpl   = custausu_email_tpl_get($lang, 'verify_resend');

  if ($tpl['subject'] === '' || $tpl['body'] === '') {
    if (function_exists('custausu_log')) {
      custausu_log('email', 'verify_resend template missing', [
        'lang' => $lang,
        'need' => ['subject','body'],
      ], 'warn');
    }
    wp_safe_redirect(admin_url('users.php?verify_sent=0'));
    exit;
  }

  $site_name = (string) get_bloginfo('name');

  $first = trim((string) ($user->first_name ?? ''));
  if ($first === '') $first = (string) ($user->display_name ?: $user->user_login);

  // Template variables available to subject and HTML body.
  $opt_email  = custausu_email_settings_get();
  $support_url = home_url('/');
  $profile_url = custausu_profile_login_url($lang);

  $vars = [
    'site_name'   => $site_name,
    'username'    => (string) $user->user_login,
    'first_name'  => (string) $first,
    'verify_link' => (string) $verify_link,
    'support_url' => (string) $support_url,
    'profile_url' => (string) $profile_url,
    'year'        => (string) wp_date('Y', time(), wp_timezone()),

    // Palette variables available to the HTML body.
    'wrap_bg'     => $theme['wrap_bg'],
    'wrap_border' => $theme['wrap_border'],
    'wrap_text'   => $theme['wrap_text'],
    'h2_color'    => $theme['h2_color'],
    'btn_bg'      => $theme['btn_bg'],
    'btn_text'    => $theme['btn_text'],
  ];

  $subject   = custausu_email_tpl_apply_vars($tpl['subject'], $vars);
  $body_html = custausu_email_tpl_apply_vars($tpl['body'], $vars);

  // Palette-based email layout.
  $opt_email = custausu_email_settings_get();
    $logo = '';
    $logo_w = 180;

    $logo_html = $logo !== ''
      ? "<img src='".esc_url($logo)."' alt='Logo' style='width:{$logo_w}px; margin-bottom:20px;'>"
      : '';

  $body_html = wp_kses_post($body_html);

  $wrapper = "
<div style='font-family:Arial;background:{$theme['wrap_bg']};border:4px solid {$theme['wrap_border']};padding:20px;border-radius:15px;max-width:650px;margin:0 auto;color:{$theme['wrap_text']};text-align:center;'>
  {$logo_html}
  <div style='font-size:16px;line-height:1.6;text-align:left;'>
    {$body_html}
  </div>
</div>";

  $support_label = ($lang === 'it') ? 'Supporto' : 'Support';

  $footer = "
<div style='max-width:650px;margin:12px auto 0;font-family:Arial;font-size:12px;line-height:1.5;color:#6b6f76;text-align:center;'>
  <div style='margin:0 0 6px 0;'>
    <a href='".esc_url($support_url)."' style='color:#6b6f76;text-decoration:underline;font-weight:600;'>{$support_label}</a>
  </div>
  <div>© ".esc_html(wp_date('Y', time(), wp_timezone()))." ".esc_html($site_name)." ".esc_html(custausu_email_t($lang, '— All rights reserved'))."</div>
</div>";

  $html = $wrapper . $footer;

  $sent = wp_mail(
     $user->user_email,
     $subject,
     $html,
     ['Content-Type: text/html; charset=UTF-8']
   );

    if (function_exists('custausu_log')) {
    custausu_log('email', $sent ? 'email sent' : 'email send failed', [
        'to'   => $user->user_email,
        'lang' => $lang,
        'type' => 'verify_resend',
    ], $sent ? 'info' : 'error');
    }

  wp_safe_redirect(admin_url('users.php?verify_sent=1'));
  exit;
});

/* ============================================================================
   4) Admin notice
============================================================================ */

add_action('admin_notices', function () {

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin notice query arg after redirect; no state change is performed here.
  $v = isset($_GET['verify_sent']) ? sanitize_key(wp_unslash($_GET['verify_sent'])) : '';
  if ($v === '') return;

  if ($v === '1') {
    $msg = custausu_ui_t('Verification eMail sent successfully.');
    echo '<div class="notice notice-success is-dismissible"><p><strong>' .
      esc_html($msg) .
    '</strong></p></div>';
    return;
  }

  if ($v === '0') {
    $msg = custausu_ui_t('Verification eMail not sent: missing email template in CAS Settings.');
    echo '<div class="notice notice-error is-dismissible"><p><strong>' .
      esc_html($msg) .
    '</strong></p></div>';
    return;
  }

  if ($v === '2') {
    $msg = custausu_ui_t('Verification eMail not sent: custom email verification table not available.');
    echo '<div class="notice notice-error is-dismissible"><p><strong>' .
      esc_html($msg) .
    '</strong></p></div>';
    return;
  }
});