<?php
/**
 * Presentation-only skin for WordPress Core password reset screens.
 *
 * Applies the existing CAS Auth Customizer palette and typography to the
 * native `rp` and `resetpass` screens, the Core invalid/expired-key
 * recovery screen and the Core `checkemail=confirm` handoff after a reset
 * email is requested. WordPress Core continues to validate
 * reset keys, enforce password policy, update credentials and fire its normal
 * compatibility hooks.
 *
 * This file does not replace or reimplement the password-reset engine.
 */

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

if (!function_exists('custausu_native_reset_skin_supported_actions')) {
  function custausu_native_reset_skin_supported_actions(): array {
    return ['rp', 'resetpass'];
  }
}

if (!function_exists('custausu_native_reset_skin_supported_recovery_errors')) {
  function custausu_native_reset_skin_supported_recovery_errors(): array {
    return ['invalidkey', 'expiredkey'];
  }
}

if (!function_exists('custausu_native_reset_skin_request_action')) {
  function custausu_native_reset_skin_request_action(
    string $fallback = ''
  ): string {
    $fallback = sanitize_key($fallback);

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen routing; no state mutation.
    if (isset($_REQUEST['action']) && is_string($_REQUEST['action'])) {
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sanitized read-only route selector; no state mutation.
      $action = sanitize_key(wp_unslash($_REQUEST['action']));

      if ($action !== '') {
        return $action;
      }
    }

    return $fallback;
  }
}

if (!function_exists('custausu_native_reset_skin_request_error')) {
  function custausu_native_reset_skin_request_error(): string {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only Core error routing; no state mutation.
    if (!isset($_GET['error']) || !is_string($_GET['error'])) {
      return '';
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sanitized read-only Core error selector; no state mutation.
    return sanitize_key(wp_unslash($_GET['error']));
  }
}

if (!function_exists('custausu_native_reset_skin_request_checkemail')) {
  function custausu_native_reset_skin_request_checkemail(): string {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only Core password-reset handoff state; no state mutation.
    if (!isset($_GET['checkemail']) || !is_string($_GET['checkemail'])) {
      return '';
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sanitized read-only Core password-reset handoff selector; no state mutation.
    return sanitize_key(wp_unslash($_GET['checkemail']));
  }
}

if (!function_exists('custausu_native_reset_skin_should_apply')) {
  function custausu_native_reset_skin_should_apply(
    string $action = ''
  ): bool {
    $action = custausu_native_reset_skin_request_action($action);

    if (custausu_native_reset_skin_request_checkemail() === 'confirm') {
      return true;
    }

    if (in_array(
      $action,
      custausu_native_reset_skin_supported_actions(),
      true
    )) {
      return true;
    }

    return $action === 'lostpassword'
      && in_array(
        custausu_native_reset_skin_request_error(),
        custausu_native_reset_skin_supported_recovery_errors(),
        true
      );
  }
}

if (!function_exists('custausu_native_reset_skin_request_locale')) {
  function custausu_native_reset_skin_request_locale(): string {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only locale routing; no state mutation.
    if (isset($_GET['wp_lang']) && is_string($_GET['wp_lang'])) {
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sanitized read-only locale selector; no state mutation.
      $locale = sanitize_locale_name(wp_unslash($_GET['wp_lang']));

      if ($locale !== '') {
        return $locale;
      }
    }

    if (function_exists('determine_locale')) {
      $locale = sanitize_locale_name((string)determine_locale());

      if ($locale !== '') {
        return $locale;
      }
    }

    return sanitize_locale_name((string)get_locale());
  }
}

if (!function_exists('custausu_native_reset_skin_lang')) {
  function custausu_native_reset_skin_lang(): string {
    $settings = get_option('custausu_global_settings', []);
    $settings = is_array($settings) ? $settings : [];

    $allowed = [];

    if (!empty($settings['i18n_langs']) && is_array($settings['i18n_langs'])) {
      foreach ($settings['i18n_langs'] as $candidate) {
        $candidate = sanitize_key((string)$candidate);

        if ($candidate !== '') {
          $allowed[] = $candidate;
        }
      }
    }

    $default = sanitize_key(
      (string)($settings['routes_default_lang'] ?? '')
    );

    if ($default === '' && function_exists('custausu_config')) {
      $default = sanitize_key(
        (string)custausu_config('routes.policy.default_lang', 'en')
      );
    }

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

    $allowed[] = $default;
    $allowed = array_values(
      array_unique(array_filter($allowed))
    );

    $locale = strtolower(
      str_replace('_', '-', custausu_native_reset_skin_request_locale())
    );
    $locale = sanitize_key($locale);
    $base = sanitize_key((string)explode('-', $locale)[0]);

    foreach ([$locale, $base, $default] as $candidate) {
      if (
        $candidate !== ''
        && in_array($candidate, $allowed, true)
      ) {
        return $candidate;
      }
    }

    return $default;
  }
}

if (!function_exists('custausu_native_reset_skin_text')) {
  function custausu_native_reset_skin_text(
    string $translated,
    string $english,
    string $italian
  ): string {
    if (
      $translated === $english
      && str_starts_with(custausu_native_reset_skin_lang(), 'it')
    ) {
      return $italian;
    }

    return $translated;
  }
}

if (!function_exists('custausu_native_reset_skin_resolve_login_url')) {
  function custausu_native_reset_skin_resolve_login_url(
    string $fallback_url,
    string $redirect = '',
    bool $force_reauth = false
  ): string {
    static $resolving = false;

    if ($resolving) {
      return $fallback_url;
    }

    $resolving = true;
    $lang = custausu_native_reset_skin_lang();
    $resolved = '';

    if (function_exists('custausu_login_url_for_lang')) {
      $resolved = trim(
        (string)custausu_login_url_for_lang($lang)
      );
    } elseif (function_exists('custausu_route_url')) {
      $resolved = trim((string)custausu_route_url('login', $lang));
    }

    $resolving = false;
    $resolved = esc_url_raw($resolved);

    if ($resolved === '') {
      return $fallback_url;
    }

    $fallback_path = (string)wp_parse_url(
      $fallback_url,
      PHP_URL_PATH
    );
    $resolved_path = (string)wp_parse_url(
      $resolved,
      PHP_URL_PATH
    );

    if (
      $fallback_path !== ''
      && $resolved_path !== ''
      && rtrim($fallback_path, '/') === rtrim($resolved_path, '/')
    ) {
      return $fallback_url;
    }

    if ($redirect !== '') {
      $resolved = (string)add_query_arg(
        'redirect_to',
        esc_url_raw($redirect),
        $resolved
      );
    }

    if ($force_reauth) {
      $resolved = (string)add_query_arg('reauth', '1', $resolved);
    }

    return $resolved;
  }
}

if (!function_exists('custausu_native_reset_skin_filter_login_url')) {
  function custausu_native_reset_skin_filter_login_url(
    string $login_url,
    string $redirect,
    bool $force_reauth
  ): string {
    if (!custausu_native_reset_skin_should_apply()) {
      return $login_url;
    }

    return custausu_native_reset_skin_resolve_login_url(
      $login_url,
      $redirect,
      $force_reauth
    );
  }
}

if (!function_exists('custausu_native_reset_skin_header_url')) {
  function custausu_native_reset_skin_header_url(
    string $header_url
  ): string {
    if (!custausu_native_reset_skin_should_apply()) {
      return $header_url;
    }

    return custausu_native_reset_skin_resolve_login_url(
      $header_url
    );
  }
}

if (!function_exists('custausu_native_reset_skin_header_text')) {
  function custausu_native_reset_skin_header_text(
    string $header_text
  ): string {
    if (!custausu_native_reset_skin_should_apply()) {
      return $header_text;
    }

    return 'Custom Auth Suite';
  }
}

if (!function_exists('custausu_native_reset_skin_body_class')) {
  function custausu_native_reset_skin_body_class(
    array $classes,
    string $action
  ): array {
    if (!custausu_native_reset_skin_should_apply($action)) {
      return $classes;
    }

    $classes[] = 'custausu-native-reset-skin';
    $classes[] = 'custausu-native-reset-skin--' . sanitize_html_class($action);

    return array_values(
      array_unique(array_filter($classes))
    );
  }
}

if (!function_exists('custausu_native_reset_skin_message')) {
  function custausu_native_reset_skin_message(
    string $message
  ): string {
    $action = custausu_native_reset_skin_request_action();

    if (!custausu_native_reset_skin_should_apply($action)) {
      return $message;
    }

    /*
     * On Core's checkemail=confirm handoff the instructional message is
     * generated by WordPress itself. Keep that Core message byte-for-byte and
     * apply presentation only through the body class/enqueued CAS stylesheet.
     */
    if (custausu_native_reset_skin_request_checkemail() === 'confirm') {
      return $message;
    }

    if ($action === 'resetpass') {
      $title = custausu_native_reset_skin_text(
        __('Password updated', 'custom-auth-suite'),
        'Password updated',
        'Password aggiornata'
      );
    } elseif ($action === 'lostpassword') {
      $title = custausu_native_reset_skin_text(
        __('Request a new password reset link', 'custom-auth-suite'),
        'Request a new password reset link',
        'Richiedi un nuovo link per reimpostare la password'
      );
    } else {
      $title = custausu_native_reset_skin_text(
        __('Reset your password', 'custom-auth-suite'),
        'Reset your password',
        'Reimposta la password'
      );
    }

    return '<h2 class="custausu-native-reset-title">'
      . esc_html($title)
      . '</h2>'
      . $message;
  }
}

if (!function_exists('custausu_native_reset_skin_inline_css')) {
  function custausu_native_reset_skin_inline_css(): string {
    $colors = function_exists('custausu_auth_theme_saved_colors')
      ? custausu_auth_theme_saved_colors()
      : [];
    $sizes = function_exists('custausu_auth_theme_saved_sizes')
      ? custausu_auth_theme_saved_sizes()
      : [];

    $variables = [];
    $color_map = [
      'page_bg' => '--custausu-auth-page-bg',
      'box_bg' => '--custausu-auth-box-bg',
      'box_border' => '--custausu-auth-box-border',
      'title_color' => '--custausu-auth-title-color',
      'text_color' => '--custausu-auth-text-color',
      'link_color' => '--custausu-auth-link-color',
      'button_bg' => '--custausu-auth-button-bg',
      'button_text' => '--custausu-auth-button-text',
      'input_border' => '--custausu-auth-input-border',
    ];

    foreach ($color_map as $setting => $variable) {
      if (!empty($colors[$setting])) {
        $variables[] = $variable . ':' . $colors[$setting];
      }
    }

    $size_map = [
      'title_font_size' => '--custausu-auth-title-size',
      'field_label_font_size' => '--custausu-auth-label-size',
      'body_font_size' => '--custausu-auth-body-size',
      'button_font_size' => '--custausu-auth-button-size',
    ];

    foreach ($size_map as $setting => $variable) {
      if (!empty($sizes[$setting])) {
        $variables[] = $variable . ':' . absint($sizes[$setting]) . 'px';
      }
    }

    $css = [];
    $scope = 'body.login.custausu-native-reset-skin';

    /*
     * Match the static stylesheet selector exactly. The D7 selector omitted
     * the `login` class and therefore lost the cascade to the more specific
     * fallback declarations in the enqueued stylesheet.
     */
    if ($variables !== []) {
      $css[] = $scope . '{'
        . implode(';', $variables)
        . ';}';
    }

    /*
     * Reuse the same package-aware Assets boundary as the CAS Auth templates:
     * - Free: bundled CAS fallback only;
     * - Advanced/Premium: custom Login asset when configured;
     * - all editions: assets_logingif_enabled controls visibility.
     */
    $logo_should_render = function_exists('custausu_asset_should_render')
      ? custausu_asset_should_render('login_gif')
      : true;
    $logo_url = function_exists('custausu_asset_url')
      ? (string)custausu_asset_url('login_gif')
      : (
          function_exists('custausu_asset_fallback_url')
            ? (string)custausu_asset_fallback_url('login_gif')
            : ''
        );

    if (!$logo_should_render) {
      $css[] = $scope
        . ' #login h1.wp-login-logo{display:none !important;}';
    } elseif ($logo_url !== '') {
      $css[] = $scope
        . ' #login h1.wp-login-logo a{background-image:url('
        . wp_json_encode($logo_url)
        . ') !important;}';
    }

    return implode("\n", $css);
  }
}

if (!function_exists('custausu_native_reset_skin_enqueue')) {
  function custausu_native_reset_skin_enqueue(): void {
    if (!custausu_native_reset_skin_should_apply()) {
      return;
    }

    $relative = 'inc/css/custausu-native-reset-skin.css';
    $path = CUSTAUSU_PLUGIN_DIR . $relative;

    if (!is_readable($path)) {
      return;
    }

    wp_enqueue_style(
      'custausu-native-reset-skin',
      CUSTAUSU_PLUGIN_URL . $relative,
      [],
      (string)filemtime($path)
    );

    // CSS-safe string: dynamic values are normalized by custausu_native_reset_skin_inline_css().
    $inline_css_safe = custausu_native_reset_skin_inline_css();

    if ($inline_css_safe !== '') {
      wp_add_inline_style(
        'custausu-native-reset-skin',
        $inline_css_safe
      );
    }
  }
}

add_filter(
  'login_body_class',
  'custausu_native_reset_skin_body_class',
  20,
  2
);
add_action(
  'login_enqueue_scripts',
  'custausu_native_reset_skin_enqueue',
  20
);
add_filter(
  'login_message',
  'custausu_native_reset_skin_message',
  20
);
add_filter(
  'login_url',
  'custausu_native_reset_skin_filter_login_url',
  20,
  3
);
add_filter(
  'login_headerurl',
  'custausu_native_reset_skin_header_url',
  20
);
add_filter(
  'login_headertext',
  'custausu_native_reset_skin_header_text',
  20
);
