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

/**
 * Custom lost-password flow handler.
 */

add_action('admin_post_nopriv_custom_auth_suite_lostpassword', 'custausu_handle_lostpassword');
add_action('admin_post_custom_auth_suite_lostpassword', 'custausu_handle_lostpassword');

if (!function_exists('custausu_lostpassword_log')) {
  function custausu_lostpassword_log(string $message, $context = null, string $level = 'debug'): void {
    if (function_exists('custausu_log')) {
      custausu_log('lostpassword', $message, $context, $level);
    }
  }
}

if (!function_exists('custausu_lostpassword_post_value')) {
  function custausu_lostpassword_post_value(string $key, string $default = ''): string {
    $key = sanitize_key($key);

    if ($key === '') {
      return $default;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Public lost-password POST helper reads the nonce/user fields; the handler verifies the nonce before processing.
    if (!isset($_POST[$key])) {
      return $default;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Public lost-password POST value is unslashed and sanitized immediately below.
    $value = wp_unslash($_POST[$key]);

    if (is_array($value)) {
      return $default;
    }

    return sanitize_text_field(trim((string) $value));
  }
}

if (!function_exists('custausu_lostpassword_current_lang')) {
  function custausu_lostpassword_current_lang(): string {
    $default_lang = function_exists('custausu_config')
      ? strtolower(trim((string) custausu_config('routes.policy.default_lang', 'en')))
      : 'en';

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

    $current_lang = strtolower(trim(custausu_lostpassword_post_value('current_page_lang')));

    if (function_exists('custausu_is_lang') && custausu_is_lang($current_lang)) {
      return $current_lang;
    }

    if (function_exists('custausu_auth_pages_frontend_route_lang')) {
      $current_lang = strtolower(trim((string) custausu_auth_pages_frontend_route_lang()));
      if (!function_exists('custausu_is_lang') || custausu_is_lang($current_lang)) {
        return $current_lang !== '' ? $current_lang : $default_lang;
      }
    }

    if (function_exists('custausu_current_lang')) {
      $current_lang = strtolower(trim((string) custausu_current_lang()));
      if (!function_exists('custausu_is_lang') || custausu_is_lang($current_lang)) {
        return $current_lang !== '' ? $current_lang : $default_lang;
      }
    }

    return $default_lang;
  }
}

if (!function_exists('custausu_handle_lostpassword')) {
  function custausu_handle_lostpassword(): void {
    $current_lang = custausu_lostpassword_current_lang();

    $lost_url = function_exists('custausu_route_url')
      ? custausu_route_url('lostpassword', $current_lang, home_url('/'))
      : home_url('/');

    $confirm_url = function_exists('custausu_route_url')
      ? custausu_route_url('lostpassword_confirm', $current_lang, $lost_url)
      : $lost_url;

    $fail = static function(string $code) use ($lost_url): void {
      wp_safe_redirect(add_query_arg('lost', $code, $lost_url));
      exit;
    };

    custausu_lostpassword_log('request received', ['lang' => $current_lang], 'info');

    $nonce = custausu_lostpassword_post_value('_wpnonce');

    if ($nonce === '' || !wp_verify_nonce($nonce, 'custom_auth_suite_lostpassword')) {
      custausu_lostpassword_log('nonce missing or invalid', null, 'warn');
      $fail('security');
    }

    $raw_input = custausu_lostpassword_post_value('user_login');

    if ($raw_input === '') {
      custausu_lostpassword_log('empty input', null, 'info');
      $fail('empty');
    }


    $login_input = strtolower(trim(sanitize_text_field($raw_input)));
    $user = is_email($login_input)
      ? get_user_by('email', $login_input)
      : get_user_by('login', $login_input);

    custausu_lostpassword_log('user lookup completed', [
      'mode'  => is_email($login_input) ? 'email' : 'login',
      'found' => $user && !empty($user->ID),
    ], 'debug');

    if (!$user || empty($user->ID)) {
      custausu_lostpassword_log('user not found', [
        'input_hash' => substr(hash('sha256', $login_input), 0, 12),
      ], 'info');
      $fail('notfound');
    }

    $reset = retrieve_password($user->user_login);

    if (is_wp_error($reset)) {
      custausu_lostpassword_log('retrieve_password failed', $reset->get_error_codes(), 'error');
      $fail('error');
    }

    custausu_lostpassword_log('retrieve_password completed', ['user_id' => (int) $user->ID], 'info');

    wp_safe_redirect(add_query_arg('reset', 'sent', $confirm_url));
    exit;
  }
}
