<?php
if (!defined('WPINC')) { die; }

/**
 * Email verification and welcome email workflow.
 *
 * The email language follows user_lang saved at registration time.
 * Shared email helpers are loaded from inc/modules/freemium/email-helpers.php.
 */

/* ============================================================================
   Email verification state helpers
============================================================================ */

/**
 * Mark the current WordPress user email as verified in CAS storage.
 */
if (!function_exists('custausu_email_verification_mark_current_user_email_verified')) {
  function custausu_email_verification_mark_current_user_email_verified(
    int $user_id,
    string $purpose = 'wp_email_change',
    array $meta = []
  ): bool {
    if ($user_id <= 0) return false;

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

    if (
      !function_exists('custausu_db_email_verifications_is_ready') ||
      !custausu_db_email_verifications_is_ready() ||
      !function_exists('custausu_db_email_verifications_mark_user_email_verified')
    ) {
      update_user_meta($user_id, 'email_verified', 'yes');
      update_user_meta($user_id, 'email_verified_at', (string) time());
      return true;
    }

    $ok = custausu_db_email_verifications_mark_user_email_verified(
      $user_id,
      (string) $user->user_email,
      $purpose,
      array_merge([
        'source' => $purpose,
      ], $meta)
    );

    if ($ok) {
      update_user_meta($user_id, 'email_verified', 'yes');
      update_user_meta($user_id, 'email_verified_at', (string) time());
    }

    return $ok;
  }
}

add_action('profile_update', function ($user_id, $old_user_data) {
  $user_id = (int) $user_id;
  if ($user_id <= 0) return;

  if (!$old_user_data instanceof WP_User) {
    return;
  }

  $new_user = get_userdata($user_id);
  if (!$new_user) return;

  $old_email = strtolower(trim((string) $old_user_data->user_email));
  $new_email = strtolower(trim((string) $new_user->user_email));

  if ($old_email === '' || $new_email === '' || $old_email === $new_email) {
    return;
  }

  /*
   * WordPress applies profile email changes after its own confirmation flow.
   * At this point the new email can be considered verified by WP.
   */
  if (function_exists('custausu_email_verification_mark_current_user_email_verified')) {
    custausu_email_verification_mark_current_user_email_verified(
      $user_id,
      'wp_email_change',
      [
        'old_email_hash' => hash('sha256', $old_email),
        'new_email_hash' => hash('sha256', $new_email),
      ]
    );
  }

  if (function_exists('custausu_log')) {
    custausu_log('email', 'user email changed and marked verified through WP confirmation flow', [
      'user_id' => $user_id,
      'source'  => 'profile_update',
    ], 'info');
  }
}, 20, 2);

/* ============================================================================
   EMAIL SETTINGS (from WP Admin: custausu_global_settings[email_theme|email_tpl])
   - No translations.php fallback: if missing -> do not send, log warn.
============================================================================ */

if (!function_exists('custausu_email_tpl_defaults')) {
  function custausu_email_tpl_defaults(): array {
    // Supported template types: verify_register, verify_resend, welcome.
    // Supported languages: EN and IT.
    // Template variables: {{site_name}} {{username}} {{first_name}} {{verify_link}} {{support_url}} {{profile_url}} {{year}}.
    // Palette variables: {{wrap_bg}} {{wrap_border}} {{wrap_text}} {{h2_color}} {{btn_bg}} {{btn_text}}.
    return [
      'en' => [
        'verify_register' => [
          'subject' => 'Confirm your email — {{site_name}}',
          'body'    => "
<h2 style=\"margin:0 0 12px 0; color:{{h2_color}};\">Confirm your eMail</h2>
<p style=\"margin:0 0 14px 0;\">Hi {{first_name}},</p>
<p style=\"margin:0 0 18px 0;\">Click the button below to verify your email address.</p>
<p style=\"margin:0 0 22px 0;\">
  <a href=\"{{verify_link}}\" style=\"display:inline-block;background:{{btn_bg}};color:{{btn_text}};padding:12px 22px;border-radius:6px;text-decoration:none;font-weight:bold;\">Verify email</a>
</p>
<p style=\"margin:18px 0 0 0;font-size:13px;opacity:.9;\">If you didn’t request this, you can ignore this email.</p>
",
        ],
        'verify_resend' => [
          'subject' => 'Your verification link — {{site_name}}',
          'body'    => "
<h2 style=\"margin:0 0 12px 0; color:{{h2_color}};\">Verify your eMail</h2>
<p style=\"margin:0 0 14px 0;\">Hi {{first_name}},</p>
<p style=\"margin:0 0 18px 0;\">Here is your new verification link:</p>
<p style=\"margin:0 0 22px 0;\">
  <a href=\"{{verify_link}}\" style=\"display:inline-block;background:{{btn_bg}};color:{{btn_text}};padding:12px 22px;border-radius:6px;text-decoration:none;font-weight:bold;\">Verify email</a>
</p>
",
        ],
        'welcome' => [
          'subject' => 'Welcome to {{site_name}}!',
          'body'    => "
<h2 style=\"margin:0 0 12px 0; color:{{h2_color}};\">Welcome!</h2>
<p style=\"margin:0 0 14px 0;\">Hi {{first_name}},</p>
<p style=\"margin:0 0 18px 0;\">Your email is verified. You can now access your account.</p>
<p style=\"margin:0 0 22px 0;\">
  <a href=\"{{profile_url}}\" style=\"display:inline-block;background:{{btn_bg}};color:{{btn_text}};padding:12px 22px;border-radius:6px;text-decoration:none;font-weight:bold;\">Go to profile</a>
</p>
",
        ],
      ],

      'it' => [
        'verify_register' => [
          'subject' => 'Conferma la tua eMail — {{site_name}}',
          'body'    => "
<h2 style=\"margin:0 0 12px 0; color:{{h2_color}};\">Conferma la tua eMail</h2>
<p style=\"margin:0 0 14px 0;\">Ciao {{first_name}},</p>
<p style=\"margin:0 0 18px 0;\">Clicca il pulsante qui sotto per verificare il tuo indirizzo email.</p>
<p style=\"margin:0 0 22px 0;\">
  <a href=\"{{verify_link}}\" style=\"display:inline-block;background:{{btn_bg}};color:{{btn_text}};padding:12px 22px;border-radius:6px;text-decoration:none;font-weight:bold;\">Verifica email</a>
</p>
<p style=\"margin:18px 0 0 0;font-size:13px;opacity:.9;\">Se non hai richiesto tu questa operazione, puoi ignorare questa email.</p>
",
        ],
        'verify_resend' => [
          'subject' => 'Link di verifica — {{site_name}}',
          'body'    => "
<h2 style=\"margin:0 0 12px 0; color:{{h2_color}};\">Verifica la tua eMail</h2>
<p style=\"margin:0 0 14px 0;\">Ciao {{first_name}},</p>
<p style=\"margin:0 0 18px 0;\">Ecco il tuo nuovo link di verifica:</p>
<p style=\"margin:0 0 22px 0;\">
  <a href=\"{{verify_link}}\" style=\"display:inline-block;background:{{btn_bg}};color:{{btn_text}};padding:12px 22px;border-radius:6px;text-decoration:none;font-weight:bold;\">Verifica email</a>
</p>
",
        ],
        'welcome' => [
          'subject' => 'Benvenuto su {{site_name}}!',
          'body'    => "
<h2 style=\"margin:0 0 12px 0; color:{{h2_color}};\">Benvenuto!</h2>
<p style=\"margin:0 0 14px 0;\">Ciao {{first_name}},</p>
<p style=\"margin:0 0 18px 0;\">La tua email è verificata. Ora puoi accedere al tuo account.</p>
<p style=\"margin:0 0 22px 0;\">
  <a href=\"{{profile_url}}\" style=\"display:inline-block;background:{{btn_bg}};color:{{btn_text}};padding:12px 22px;border-radius:6px;text-decoration:none;font-weight:bold;\">Vai al profilo</a>
</p>
",
        ],
      ],
    ];
  }
}

if (!function_exists('custausu_email_log_delivery_result')) {
  function custausu_email_log_delivery_result(
    int $user_id,
    string $email,
    string $lang,
    string $type,
    bool $sent,
    array $extra = []
  ): void {
    if (!function_exists('custausu_log')) return;

    $debug_ctx = array_merge([
      'user_id' => (int) $user_id,
      'to'      => (string) $email,
      'lang'    => (string) $lang,
      'type'    => (string) $type,
      'ok'      => $sent ? 1 : 0,
    ], $extra);

    custausu_log('email', $sent ? 'email pipeline success' : 'email pipeline failed', $debug_ctx, 'debug');

    $level_ctx = $debug_ctx;
    unset($level_ctx['ok']);

    custausu_log('email', $sent ? 'email sent' : 'email send failed', $level_ctx, $sent ? 'info' : 'error');
  }
}
/* ============================================================================
   WELCOME EMAIL — only after verification
============================================================================ */
if (!function_exists('custausu_send_verified_welcome_email_portable')) {
  function custausu_send_verified_welcome_email_portable(int $user_id): void {
    $user = get_userdata($user_id);
    if (!$user || !$user->user_email) return;

    // language from profile meta (set at registration time)
    $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);

    $site_name = get_bloginfo('name');
    $opt_email = custausu_email_settings_get();
    $logo_url = '';
    $logo_w = 180;
    $support_url = home_url('/');
    $profile_url = custausu_profile_login_url($lang);
    $theme = custausu_email_theme_get();
    $tpl = custausu_email_tpl_get($lang, 'welcome');
    
    if ($tpl['subject'] === '' || $tpl['body'] === '') {
      if (function_exists('custausu_log')) {
        $ctx = [
          'user_id' => (int) $user_id,
          'to'      => (string) $user->user_email,
          'lang'    => (string) $lang,
          'type'    => 'welcome',
          'stage'   => 'template_resolve',
          'need'    => ['subject','body'],
          'ok'      => 0,
        ];

        custausu_log('email', 'email pipeline failed', $ctx, 'debug');
        unset($ctx['ok']);
        custausu_log('email', 'welcome template missing', $ctx, 'warn');
      }
      return;
    }

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

    $vars = [
      'site_name'   => (string)$site_name,
      'username'    => (string)$user->user_login,
      'first_name'  => (string)$first,
      'profile_url' => (string)$profile_url,
      'support_url' => (string)$support_url,
      'year'        => (string) wp_date('Y', time(), wp_timezone()),
      '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 = $tpl['subject'];
    $body_html = custausu_email_tpl_apply_vars($tpl['body'], $vars);

        // Email wrapper and footer.
    $site_name = (string) get_bloginfo('name');
    $year = (string) wp_date('Y', time(), wp_timezone());

    // Body variables are applied before wrapping the email layout.
    $body_safe = wp_kses_post($body_html);

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

    // Email wrapper.
    $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:15px;line-height:1.6;text-align:left;'>
    {$body_safe}
  </div>
</div>";

    // Footer outside the wrapper.
    $support_label = (string) custausu_email_t($lang, '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>© {$year} ".esc_html($site_name)." ".esc_html(custausu_email_t($lang, '— All rights reserved'))."</div>
</div>";

    $html = $wrapper . $footer;

    // Subject may contain template variables.
    $subject = custausu_email_tpl_apply_vars($subject, $vars);

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

    custausu_email_log_delivery_result(
      (int) $user_id,
      (string) $user->user_email,
      (string) $lang,
      'welcome',
      (bool) $sent
    );

  }
}

/* ============================================================================
   REGISTER: generate token + send verification email
============================================================================ */
add_action('user_register', function($user_id){
  $user = get_userdata($user_id);
  if (!$user || !$user->user_email) return;

  // Generate 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' => 'register',
      ]
    ) : false;

  if (!$stored_in_db) {
    if (function_exists('custausu_log')) {
      $ctx = [
        'user_id' => (int) $user_id,
        'to'      => (string) $user->user_email,
        'lang'    => '',
        'type'    => 'verify_register',
        'stage'   => 'token_store',
        'ok'      => 0,
      ];

      custausu_log('email', 'email pipeline failed', $ctx, 'debug');
      unset($ctx['ok']);
      custausu_log('email', 'email verification token could not be stored in custom DB', $ctx, 'error');
    }
    return;
  }

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

  if (function_exists('custausu_log')) {
    custausu_log('email', 'verification token stored', [
      'user_id' => (int) $user_id,
      'to'      => (string) $user->user_email,
      'type'    => 'verify_register',
      'stage'   => 'token_store',
      'ok'      => 1,
    ], 'debug');
  }

  // language from user meta (authoritative)
  $raw_lang = (string) get_user_meta($user_id, 'user_lang', true);
  if ($raw_lang === '' && function_exists('custausu_current_lang')) {
    $raw_lang = (string) custausu_current_lang();
  }
  $lang = custausu_email_pick_lang($raw_lang);

  // base URL for that lang
  $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' => (int)$user_id,
    'token'        => $token,
  ], $base_url);

  $theme = custausu_email_theme_get();
  $tpl = custausu_email_tpl_get($lang, 'verify_register');

  if ($tpl['subject'] === '' || $tpl['body'] === '') {
    if (function_exists('custausu_log')) {
      $ctx = [
        'user_id' => (int) $user_id,
        'to'      => (string) $user->user_email,
        'lang'    => (string) $lang,
        'type'    => 'verify_register',
        'stage'   => 'template_resolve',
        'need'    => ['subject','body'],
        'ok'      => 0,
      ];

      custausu_log('email', 'email pipeline failed', $ctx, 'debug');
      unset($ctx['ok']);
      custausu_log('email', 'verify_register template missing', $ctx, 'warn');
    }
    return;
  }

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

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

  // Palette tokens for customizable email templates.
  '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 = $tpl['subject'];
$body_html = custausu_email_tpl_apply_vars($tpl['body'], $vars);
$subject  = custausu_email_tpl_apply_vars($subject, $vars);
$body_html = wp_kses_post($body_html);

// Palette-based email layout.
$opt_email = custausu_email_settings_get();
$logo = '';
$logo_html = $logo ? "<img src='".esc_url($logo)."' alt='Logo' style='width:180px; margin-bottom:20px;'>" : '';

// Email wrapper box.
$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.55;text-align:left;'>{$body_html}</div>
</div>";

// Footer outside the email box.
$site_name = (string) get_bloginfo('name');
$year = (string) wp_date('Y', time(), wp_timezone());

$support_label = (string) custausu_email_t($lang, '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($vars['support_url'])."' style='color:#6b6f76;text-decoration:underline;font-weight:600;'>{$support_label}</a>
  </div>
  <div>© {$year} ".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']
   );

    custausu_email_log_delivery_result(
      (int) $user_id,
      (string) $user->user_email,
      (string) $lang,
      'verify_register',
      (bool) $sent
    );
});

/* ============================================================================
   ATOMIC EMAIL VERIFY HANDLER (no login required)
   URL: ?verify_email={user_id}&token={token}
   - validates token vs user_meta
   - sets email_verified=yes
   - clears token (+ optional expires)
   - redirects to home (lang-aware) with popup signal
============================================================================ */

add_action('init', function () {

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public email verification is token-based; no logged-in WP nonce is available or appropriate.
  if (!isset($_GET['verify_email'], $_GET['token'])) return;

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public token-based email verification link; value is unslashed and sanitized immediately.
  $user_id = isset($_GET['verify_email']) ? absint(wp_unslash($_GET['verify_email'])) : 0;
  if ($user_id <= 0) return;

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public token-based email verification link; token is unslashed and sanitized immediately.
  $token = isset($_GET['token']) ? sanitize_text_field(wp_unslash($_GET['token'])) : '';
  // Keep only safe token characters.
  $token = preg_replace('/[^a-zA-Z0-9]/', '', $token);
  if ($token === '' || strlen($token) < 12) {
    custausu_verify_redirect_result($user_id, 'invalid');
  }

  $user = get_userdata($user_id);
  if (!$user) {
    custausu_verify_redirect_result($user_id, 'invalid');
  }

  // Already verified: return a success redirect.
  $verified = (string) get_user_meta($user_id, 'email_verified', true);
  if ($verified === 'yes') {
    custausu_verify_redirect_result($user_id, 'ok');
  }

  if (
    !function_exists('custausu_db_email_verifications_is_ready') ||
    !custausu_db_email_verifications_is_ready() ||
    !function_exists('custausu_db_email_verifications_verify_token')
  ) {
    if (function_exists('custausu_log')) {
      $ctx = [
        'user_id' => (int) $user_id,
        'to'      => (string) $user->user_email,
        'type'    => 'verify_register',
        'stage'   => 'verify_handler',
        'reason'  => 'db_layer_not_ready',
        'ok'      => 0,
      ];

      custausu_log('email', 'email pipeline failed', $ctx, 'debug');
      unset($ctx['ok']);
      custausu_log('email', 'email verification DB layer not ready during verify handler', $ctx, 'error');
    }
    custausu_verify_redirect_result($user_id, 'invalid');
  }

  $res = custausu_db_email_verifications_verify_token($user_id, $token, 'register_verify');

  if (empty($res['ok'])) {
    $reason = (string)($res['reason'] ?? 'invalid');

    if (function_exists('custausu_log')) {
      custausu_log('email', 'email verification failed', [
        'user_id' => (int) $user_id,
        'to'      => (string) $user->user_email,
        'type'    => 'verify_register',
        'stage'   => 'verify_handler',
        'reason'  => $reason,
        'ok'      => 0,
      ], 'debug');
    }

    custausu_verify_redirect_result($user_id, $reason === 'expired' ? 'expired' : 'invalid');
  }

  // Success: mark verified and clean up pending token state.
  update_user_meta($user_id, 'email_verified', 'yes');
  delete_user_meta($user_id, 'email_verification_token');
  delete_user_meta($user_id, 'email_verification_expires');
  update_user_meta($user_id, 'email_verified_at', (string) time());

  if (function_exists('custausu_log')) {
    custausu_log('email', 'email verification completed', [
      'user_id' => (int) $user_id,
      'to'      => (string) $user->user_email,
      'type'    => 'verify_register',
      'stage'   => 'verify_handler',
      'ok'      => 1,
    ], 'debug');
  }

  // send welcome only once (on first verification)
  if (function_exists('custausu_send_verified_welcome_email_portable')) {
    custausu_send_verified_welcome_email_portable($user_id);
  }

  custausu_verify_redirect_result($user_id, 'ok');
});


/**
 * Redirect helper (lang-aware + popup signal via query + cookie fallback)
 */
function custausu_verify_redirect_result(int $user_id, string $result): void {

  // lang target: prefer user_lang (saved at register) else current/site default
  $raw_lang = (string) get_user_meta($user_id, 'user_lang', true);
  if ($raw_lang === '' && function_exists('custausu_current_lang')) {
    $raw_lang = (string) custausu_current_lang();
  }
  if (function_exists('custausu_email_pick_lang')) {
    $lang = custausu_email_pick_lang($raw_lang);
  } else {
    $lang = strtolower(trim($raw_lang ?: 'en'));
  }

  $base = function_exists('custausu_home_url_for_lang')
    ? (string) custausu_home_url_for_lang($lang)
    : home_url('/');

  // Flash cookie survives stripped query parameters or alternate redirects.
  $cookie_name = 'custausu_email_verify_result';
  $cookie_val  = $result; // ok | invalid | expired
  @setcookie(
    $cookie_name,
    $cookie_val,
    time() + 120,
    COOKIEPATH ?: '/',
    COOKIE_DOMAIN ?: '',
    is_ssl(),
    true
  );

  // query param (still useful)
  // - ok => email_verificata=1
  // - fail => email_verificata=0&reason=...
  if ($result === 'ok') {
    $url = add_query_arg(['email_verificata' => '1'], $base);
  } else {
    $url = add_query_arg(['email_verificata' => '0', 'reason' => $result], $base);
  }

  wp_safe_redirect($url);
  exit;
}
