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

if (!function_exists('custausu_admin_email_tools_t')) {
  function custausu_admin_email_tools_t(string $en, string $it = ''): string {
    if (function_exists('custausu_admin_t')) {
      return (string) custausu_admin_t($en, $it !== '' ? $it : $en);
    }

    return $en;
  }
}

// -----------------------------------------------------------------------------
// Preserve tokens in email templates while passing through wp_kses_post / SafeCSS
// -----------------------------------------------------------------------------
if (!function_exists('custausu_email_preserve_tokens')) {
  function custausu_email_preserve_tokens(string $html, string $mode = 'encode'): string {
    if ($html === '') return '';

    // Dummy values MUST be valid for KSES/SafeCSS (hex + https).
    $map = [
      // CSS tokens
      '{{wrap_bg}}'     => '#111111',
      '{{wrap_border}}' => '#222222',
      '{{wrap_text}}'   => '#333333',
      '{{h2_color}}'    => '#444444',
      '{{btn_bg}}'      => '#555555',
      '{{btn_text}}'    => '#666666',

      // URL tokens (prevent KSES from stripping href because protocol is "invalid")
      '{{verify_link}}' => 'https://example.com/verify',
      '{{support_url}}' => 'https://example.com/support',
      '{{profile_url}}' => 'https://example.com/profile',
    ];

    if ($mode === 'encode') {
      return str_replace(array_keys($map), array_values($map), $html);
    }

    return str_replace(array_values($map), array_keys($map), $html);
  }
}

if (!function_exists('custausu_admin_handle_test_email_ajax')) {
  function custausu_admin_handle_test_email_ajax(): void {
    $T = 'custausu_admin_email_tools_t';

    if (!current_user_can('manage_options')) {
      wp_send_json_error($T('Forbidden.', 'Non autorizzato.'), 403);
    }

    if (false === check_ajax_referer('custausu_send_test_email', 'nonce', false)) {
      wp_send_json_error($T('Invalid security token.', 'Token di sicurezza non valido.'), 400);
    }

    $to = isset($_POST['to']) && is_string($_POST['to'])
      ? sanitize_email(wp_unslash($_POST['to']))
      : '';

    $lang = isset($_POST['lang']) && is_string($_POST['lang'])
      ? sanitize_key(wp_unslash($_POST['lang']))
      : '';

    $type = isset($_POST['type']) && is_string($_POST['type'])
      ? sanitize_key(wp_unslash($_POST['type']))
      : '';

    $subject = isset($_POST['subject']) && is_string($_POST['subject'])
      ? sanitize_text_field(wp_unslash($_POST['subject']))
      : '';

    $body = '';
    if (isset($_POST['body']) && is_string($_POST['body'])) {
      // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Raw HTML is token-encoded and sanitized by wp_kses_post() immediately below.
      $body_raw = wp_unslash($_POST['body']);
      $body_raw = custausu_email_preserve_tokens((string) $body_raw, 'encode');
      $body_raw = wp_kses_post($body_raw);
      $body = custausu_email_preserve_tokens($body_raw, 'decode');
    }

    if ($to === '' || !is_email($to)) {
      wp_send_json_error($T('Invalid email address.', 'Indirizzo email non valido.'), 400);
    }

    if ($subject === '' || $body === '') {
      wp_send_json_error($T('Subject or email body is missing.', 'Oggetto o corpo email mancante.'), 400);
    }

    $wrap_bg = (
      isset($_POST['theme']['wrap_bg']) &&
      is_string($_POST['theme']['wrap_bg'])
    )
      ? sanitize_hex_color(wp_unslash($_POST['theme']['wrap_bg']))
      : '';

    $wrap_border = (
      isset($_POST['theme']['wrap_border']) &&
      is_string($_POST['theme']['wrap_border'])
    )
      ? sanitize_hex_color(wp_unslash($_POST['theme']['wrap_border']))
      : '';

    $wrap_text = (
      isset($_POST['theme']['wrap_text']) &&
      is_string($_POST['theme']['wrap_text'])
    )
      ? sanitize_hex_color(wp_unslash($_POST['theme']['wrap_text']))
      : '';

    $h2_color = (
      isset($_POST['theme']['h2_color']) &&
      is_string($_POST['theme']['h2_color'])
    )
      ? sanitize_hex_color(wp_unslash($_POST['theme']['h2_color']))
      : '';

    $btn_bg = (
      isset($_POST['theme']['btn_bg']) &&
      is_string($_POST['theme']['btn_bg'])
    )
      ? sanitize_hex_color(wp_unslash($_POST['theme']['btn_bg']))
      : '';

    $btn_text = (
      isset($_POST['theme']['btn_text']) &&
      is_string($_POST['theme']['btn_text'])
    )
      ? sanitize_hex_color(wp_unslash($_POST['theme']['btn_text']))
      : '';

    $theme = [
      'wrap_bg'     => $wrap_bg ?: '#f7f7f7',
      'wrap_border' => $wrap_border ?: '#222222',
      'wrap_text'   => $wrap_text ?: '#222222',
      'h2_color'    => $h2_color ?: '#222222',
      'btn_bg'      => $btn_bg ?: '#222222',
      'btn_text'    => $btn_text ?: '#ffffff',
    ];

    $site_name = wp_strip_all_tags((string) get_bloginfo('name'));
    $home      = esc_url_raw(home_url('/'));

    $opt = get_option('custausu_global_settings', []);
    $opt = is_array($opt) ? $opt : [];
    $assets_support = $home;
    $assets_logo = '';
    $profile_url = custausu_profile_login_url($lang);

    $vars = [
      'site_name'   => $site_name,
      'username'    => 'demo_user',
      'first_name'  => 'Demo',
      'verify_link' => $home,
      'support_url' => $assets_support,
      'profile_url' => $profile_url,
      'year'        => (string) gmdate('Y'),
      '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'],
    ];

    $apply = function(string $s) use ($vars): string {
      foreach ($vars as $k => $v) {
        $s = str_replace('{{' . $k . '}}', (string)$v, $s);
      }
      return $s;
    };

    $subject = $apply($subject);
    $body    = $apply($body);
    $logo_w = 180;

    $logo_html = $assets_logo
      ? "<div style='text-align:center;margin:0 0 16px 0;'>
           <img src='" . esc_url($assets_logo) . "' alt='Logo' style='width:{$logo_w}px;height:auto;'>
         </div>"
      : "";

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

    $mail_error_message = '';
    $mail_error_data = [];

    $capture_wp_mail_failed = function($wp_error) use (&$mail_error_message, &$mail_error_data) {
      if ($wp_error instanceof WP_Error) {
        $mail_error_message = $wp_error->get_error_message();
        $mail_error_data = $wp_error->get_error_data();
      }
    };

    add_action('wp_mail_failed', $capture_wp_mail_failed, 10, 1);

    try {
      $ok = wp_mail($to, $subject, $html, ['Content-Type: text/html; charset=UTF-8']);
    } finally {
      remove_action('wp_mail_failed', $capture_wp_mail_failed, 10);
    }

    if (!$ok) {
      if (function_exists('custausu_log')) {
        custausu_log('email', 'CAS test email failed', [
          'to' => $to,
          'lang' => $lang,
          'type' => $type,
          'subject' => $subject,
          'wp_mail_failed_message' => $mail_error_message,
          'wp_mail_failed_data' => $mail_error_data,
        ], 'error');
      }

      $msg = $mail_error_message !== ''
        ? $mail_error_message
        : $T('wp_mail failed to send the test email.', 'wp_mail non è riuscito a inviare l’email di test.');

      wp_send_json_error($msg, 500);
    }

    wp_send_json_success(true);
  }
}