<?php
/**
 * Template Name: Account Login
 */

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

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- DONOTCACHEPAGE is a WordPress/cache interoperability constant and must keep its established name.
if (!defined('DONOTCACHEPAGE')) define('DONOTCACHEPAGE', true);
nocache_headers();

if (!function_exists('custausu_login_template_get_redirect_to')) {
  function custausu_login_template_get_redirect_to(): string {
    $raw = filter_input(INPUT_GET, 'redirect_to', FILTER_SANITIZE_URL);

    if (!is_scalar($raw) || (string) $raw === '') {
      return '';
    }

    return esc_url_raw(rawurldecode((string) $raw));
  }
}

if (!function_exists('custausu_login_template_get_query_key')) {
  function custausu_login_template_get_query_key(string $key): string {
    $key = sanitize_key($key);

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

    $raw = filter_input(
      INPUT_GET,
      $key,
      FILTER_SANITIZE_FULL_SPECIAL_CHARS
    );

    if (!is_scalar($raw) || (string) $raw === '') {
      return '';
    }

    return sanitize_key((string) $raw);
  }
}

// If the visitor is already logged in, do not show the login form.
// Prefer a valid redirect_to when present; otherwise use the CAS landing route.
if (is_user_logged_in()) {
  $custausu_tpl_lang = function_exists('custausu_auth_pages_frontend_route_lang') ? custausu_auth_pages_frontend_route_lang() : 'en';

  $custausu_tpl_default_after_login = function_exists('custausu_route_url')
    ? custausu_route_url('landing', $custausu_tpl_lang, '/')
    : home_url('/');

  $custausu_tpl_target = $custausu_tpl_default_after_login;

  $custausu_tpl_rt_raw = custausu_login_template_get_redirect_to();

  if ($custausu_tpl_rt_raw !== '') {
      $custausu_tpl_rt_norm = function_exists('custausu_redirect_to_normalize')
        ? (string) custausu_redirect_to_normalize($custausu_tpl_rt_raw, $custausu_tpl_lang, 'already_logged_in_login_template')
        : $custausu_tpl_rt_raw;

      $custausu_tpl_safe = wp_validate_redirect($custausu_tpl_rt_norm, $custausu_tpl_default_after_login);
      if ($custausu_tpl_safe !== '') {
        $custausu_tpl_target = $custausu_tpl_safe;
      }
  }

  wp_safe_redirect($custausu_tpl_target);
  exit;
}

// --- small helpers (template-safe) ---
if (!function_exists('custausu_tpl_t')) {
  function custausu_tpl_t(string $key): string {
    if (function_exists('custausu_t')) {
      return (string) custausu_t($key);
    }

    switch ($key) {
      case 'Login':
        return __('Login', 'custom-auth-suite');
      case 'Please login to continue.<br />If you don’t have an account yet, you can create one in a minute.':
        return __('Please login to continue.<br />If you don’t have an account yet, you can create one in a minute.', 'custom-auth-suite');
      case 'Username or eMail':
        return __('Username or eMail', 'custom-auth-suite');
      case 'Password':
        return __('Password', 'custom-auth-suite');
      case 'Show password':
        return __('Show password', 'custom-auth-suite');
      case 'Hide password':
        return __('Hide password', 'custom-auth-suite');
      case 'Remember Me':
        return __('Remember Me', 'custom-auth-suite');
      case 'Login with Face ID / Touch ID':
        return __('Login with Face ID / Touch ID', 'custom-auth-suite');
      case '⚠️ Invalid login details. Please try again.':
        return __('⚠️ Invalid login details. Please try again.', 'custom-auth-suite');
      case 'Forgot Password?':
        return __('Forgot Password?', 'custom-auth-suite');
      case 'Don’t have an account?':
        return __('Don’t have an account?', 'custom-auth-suite');
      case 'Create one':
        return __('Create one', 'custom-auth-suite');
      default:
        return $key;
    }
  }
}
if (!function_exists('custausu_tpl_t_html')) {
  function custausu_tpl_t_html(string $key): string {
    // allow <br>, <strong>, etc. from translations
    return wp_kses_post(custausu_tpl_t($key));
  }
}

$custausu_tpl_lang = function_exists('custausu_auth_pages_frontend_route_lang') ? custausu_auth_pages_frontend_route_lang() : 'en';

$custausu_tpl_login_url        = function_exists('custausu_route_url') ? custausu_route_url('login', $custausu_tpl_lang, '/') : wp_login_url();
$custausu_tpl_register_url     = function_exists('custausu_route_url') ? custausu_route_url('register', $custausu_tpl_lang, '/') : wp_registration_url();
$custausu_tpl_lost_password_url= function_exists('custausu_route_url') ? custausu_route_url('lostpassword', $custausu_tpl_lang, '/') : wp_lostpassword_url();
$custausu_tpl_default_after_login = function_exists('custausu_route_url') ? custausu_route_url('landing', $custausu_tpl_lang, '/') : home_url('/');

// redirect_to (normalize)
$custausu_tpl_rt_raw = custausu_login_template_get_redirect_to();

$custausu_tpl_rt_norm = '';
if ($custausu_tpl_rt_raw && function_exists('custausu_redirect_to_normalize')) {
  $custausu_tpl_rt_norm = (string) custausu_redirect_to_normalize($custausu_tpl_rt_raw, $custausu_tpl_lang, 'login_links');
}
$custausu_tpl_redirect = $custausu_tpl_rt_norm ?: $custausu_tpl_default_after_login;

$custausu_login_request_uri = isset($_SERVER['REQUEST_URI'])
  ? sanitize_text_field(wp_unslash((string) $_SERVER['REQUEST_URI']))
  : '';

if (function_exists('custausu_log') && ($custausu_tpl_rt_raw !== '' || $custausu_tpl_rt_norm !== '')) {
  custausu_log('redirect', 'login template init', [
    'uri'      => $custausu_login_request_uri,
    'lang'     => $custausu_tpl_lang,
    'rt_raw'   => $custausu_tpl_rt_raw,
    'rt_norm'  => $custausu_tpl_rt_norm,
    'redirect' => $custausu_tpl_redirect,
  ], 'debug');
}

// Optional small logo/icon near greeting.
// Runtime asset is resolved through CAS Core Assets:
// - Free: internal SVG fallback
// - Advanced/Premium: custom Login GIF URL when configured
// - Free always renders the built-in CAS login SVG
$custausu_tpl_greet_icon = function_exists('custausu_asset_should_render') && custausu_asset_should_render('login_gif');
if (function_exists('custausu_auth_template_header')) { custausu_auth_template_header(); } else { get_header(); }
?>

<div class="login-container">
  <div class="custom-auth-anim">

    <h2><?php echo esc_html(custausu_tpl_t('Login')); ?></h2>

    <h4>
      <?php
        // Se vuoi un testo diverso, aggiungi la stringa in translations.php e sostituisci la key qui.
        echo wp_kses_post(custausu_tpl_t_html('Please login to continue.<br />If you don’t have an account yet, you can create one in a minute.'));
      ?>
      <?php if ($custausu_tpl_greet_icon): ?>
        <br /><br />
        <span class="custausu-login-greet-icon">
          <?php
            echo wp_kses(custausu_asset_img_html('login_gif', [
              'width' => '58',
              'class' => 'custausu-login-greet-icon__image',
              'alt'   => 'Custom Auth Suite',
            ]), [
              'img' => [
                'src' => true,
                'alt' => true,
                'width' => true,
                'height' => true,
                'class' => true,
                'loading' => true,
                'decoding' => true,
              ],
            ], ['http', 'https', 'data']);
          ?>
        </span>
      <?php endif; ?>
    </h4>

    <form method="post"
      action="<?php echo esc_url(site_url('wp-login.php', 'login_post')); ?>">

      <label for="log"><?php echo esc_html(custausu_tpl_t('Username or eMail')); ?></label>
      <input type="text" name="log" id="log" autocomplete="username" required>

      <label for="pwd"><?php echo esc_html(custausu_tpl_t('Password')); ?></label>

      <div class="pwd-wrap">
        <input type="password" name="pwd" id="pwd" autocomplete="current-password" required>

        <button type="button"
          id="pwd-toggle"
          aria-pressed="false"
          aria-label="<?php echo esc_attr(custausu_tpl_t('Show password')); ?>"
          data-label-show="<?php echo esc_attr(custausu_tpl_t('Show password')); ?>"
          data-label-hide="<?php echo esc_attr(custausu_tpl_t('Hide password')); ?>">
          <svg id="eye-show" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
            <circle cx="12" cy="12" r="3"></circle>
          </svg>
          <svg id="eye-hide" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M17.94 17.94A10.94 10.94 0 0112 20c-7 0-11-8-11-8a21.8 21.8 0 014.06-5.94"></path>
            <path d="M1 1l22 22"></path>
          </svg>
        </button>
      </div>

      <label>
        <input type="checkbox" name="rememberme" value="forever">
        <?php echo esc_html(custausu_tpl_t('Remember Me')); ?>
      </label>

      <button type="submit"><?php echo esc_html(custausu_tpl_t('Login')); ?></button>

      <input type="hidden" name="redirect_to" value="<?php echo esc_attr($custausu_tpl_redirect); ?>">
      <input type="hidden" name="custausu_login_flow" value="1">
    </form>

    <?php if ('failed' === custausu_login_template_get_query_key('login')): ?>
      <div class="login-error">
        <?php echo esc_html(custausu_tpl_t('⚠️ Invalid login details. Please try again.')); ?>
      </div>
    <?php endif; ?>

    <p>
      <a href="<?php echo esc_url($custausu_tpl_rt_norm && function_exists('custausu_url_with_redirect_to') ? custausu_url_with_redirect_to($custausu_tpl_lost_password_url, $custausu_tpl_rt_norm) : $custausu_tpl_lost_password_url); ?>">
        <?php echo esc_html(custausu_tpl_t('Forgot Password?')); ?>
      </a>
    </p>

    <p>
      <?php echo esc_html(custausu_tpl_t('Don’t have an account?')); ?>
      <a href="<?php echo esc_url($custausu_tpl_rt_norm && function_exists('custausu_url_with_redirect_to') ? custausu_url_with_redirect_to($custausu_tpl_register_url, $custausu_tpl_rt_norm) : $custausu_tpl_register_url); ?>">
        <?php echo esc_html(custausu_tpl_t('Create one')); ?>
      </a>
    </p>

  </div>
</div>


<?php if (function_exists('custausu_auth_template_footer')) { custausu_auth_template_footer(); } else { get_footer(); } ?>