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

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();

// =============================
// LANG: robust + portable
// - source of truth for registration: current_page_lang hidden field (set below)
// - fallback chain: Auth Page context -> WordPress locale -> default_lang -> en
// - validate against the active Free language context
// =============================
if (!function_exists('custausu_reg_norm_lang')) {
  function custausu_reg_norm_lang(string $custausu_tpl_lang = ''): string {
    $custausu_tpl_lang = strtolower(trim((string)$custausu_tpl_lang));
    if ($custausu_tpl_lang === '') return '';
    $custausu_tpl_lang = str_replace('_', '-', $custausu_tpl_lang);
    $custausu_tpl_lang = preg_replace('/[^a-z0-9-]/', '', $custausu_tpl_lang);
    $base = explode('-', $custausu_tpl_lang)[0] ?? $custausu_tpl_lang;
    $base = sanitize_key($base);
    return $base !== '' ? $base : '';
  }
}

if (!function_exists('custausu_reg_allowed_langs')) {
  function custausu_reg_allowed_langs(): array {
    $default = function_exists('custausu_current_lang')
      ? custausu_reg_norm_lang((string) custausu_current_lang())
      : custausu_reg_norm_lang((string)(function_exists('custausu_config') ? custausu_config('routes.policy.default_lang', 'en') : 'en'));

    return [$default !== '' ? $default : 'en'];
  }
}

if (!function_exists('custausu_reg_pick_lang')) {
  function custausu_reg_pick_lang(string $custausu_tpl_lang = ''): string {
    $allowed = custausu_reg_allowed_langs();
    $default = custausu_reg_norm_lang((string)(function_exists('custausu_config') ? custausu_config('routes.policy.default_lang', 'en') : 'en'));

    $custausu_tpl_lang = custausu_reg_norm_lang($custausu_tpl_lang);

    if ($custausu_tpl_lang !== '' && in_array($custausu_tpl_lang, $allowed, true)) return $custausu_tpl_lang;
    if ($default !== '' && in_array($default, $allowed, true)) return $default;

    return (string)($allowed[0] ?? 'en');
  }
}

if (!function_exists('custausu_reg_detect_page_lang')) {
  function custausu_reg_detect_page_lang(): string {
    if (function_exists('custausu_auth_pages_frontend_route_lang')) {
      $lang = custausu_reg_norm_lang((string) custausu_auth_pages_frontend_route_lang());
      if ($lang !== '') return $lang;
    }

    if (function_exists('custausu_current_lang')) {
      $lang = custausu_reg_norm_lang((string) custausu_current_lang());
      if ($lang !== '') return $lang;
    }

    $locale = function_exists('determine_locale')
      ? determine_locale()
      : get_locale();
    $lang = custausu_reg_norm_lang((string) $locale);
    if (in_array($lang, ['en', 'it'], true)) return $lang;

    return custausu_reg_norm_lang((string)(function_exists('custausu_config') ? custausu_config('routes.policy.default_lang', 'en') : 'en'));
  }
}

$custausu_tpl_page_lang = custausu_reg_pick_lang(custausu_reg_detect_page_lang());
$custausu_tpl_login_url = custausu_route_url('login', $custausu_tpl_page_lang, '/');

$custausu_register_redirect_to_raw = isset($_GET['redirect_to'])
  ? sanitize_text_field(wp_unslash((string) $_GET['redirect_to']))
  : '';

$custausu_register_get = [
  'redirect_to' => $custausu_register_redirect_to_raw !== ''
    ? esc_url_raw(rawurldecode($custausu_register_redirect_to_raw))
    : '',
];

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

    $custausu_tpl_target = $custausu_tpl_default_after_login;

    if (!empty($custausu_register_get['redirect_to'])) {
        $custausu_tpl_rt_raw = (string) $custausu_register_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_page_lang, 'already_logged_in_register_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;
}

// SE IL FORM È STATO INVIATO
$errors = [];
$custausu_tpl_success = false;

$custausu_register_post = [];

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

$custausu_register_request_method = isset($_SERVER['REQUEST_METHOD'])
  ? strtoupper(sanitize_text_field(wp_unslash((string) $_SERVER['REQUEST_METHOD'])))
  : '';

if ('POST' === $custausu_register_request_method) {
    $custausu_register_nonce = (
      isset($_POST['custausu_register_nonce']) &&
      is_string($_POST['custausu_register_nonce'])
    )
      ? sanitize_text_field(wp_unslash($_POST['custausu_register_nonce']))
      : '';

    $custausu_register_post = [
      'custausu_register_nonce' => $custausu_register_nonce,
      'firstname'          => '',
      'lastname'           => '',
      'username'           => '',
      'email'              => '',
      'password'           => '',
      'password2'          => '',
      'accept_privacy'     => '',
      'current_page_lang'  => '',
      'redirect_to'        => '',
    ];

    if (!wp_verify_nonce($custausu_register_nonce, 'custausu_register')) {
        $errors[] = __('Security check failed. Please reload the page and try again.', 'custom-auth-suite');
    }

    if (empty($errors)) {
      $custausu_register_post['firstname'] = (
        isset($_POST['firstname']) &&
        is_string($_POST['firstname'])
      )
        ? sanitize_text_field(wp_unslash($_POST['firstname']))
        : '';

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

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

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

      // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Passwords must remain byte-for-byte unchanged; they are compared, then hashed by WordPress in wp_create_user().
      $custausu_register_post['password'] = (
        isset($_POST['password']) &&
        is_string($_POST['password'])
      )
        ? wp_unslash($_POST['password'])
        : '';

      $custausu_register_post['password2'] = (
        isset($_POST['password2']) &&
        is_string($_POST['password2'])
      )
        ? wp_unslash($_POST['password2'])
        : '';
      // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

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

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

      $custausu_register_post['redirect_to'] = (
        isset($_POST['redirect_to']) &&
        is_string($_POST['redirect_to'])
      )
        ? esc_url_raw(wp_unslash($_POST['redirect_to']))
        : '';
    }

    if (function_exists('custausu_log')) {
      $custausu_tpl_register_ctx = [
        'uri'             => $custausu_register_request_uri,
        'has_redirect_to' => !empty($custausu_register_post['redirect_to']) ? 1 : 0,
        'email'           => isset($custausu_register_post['email']) ? sanitize_email((string) $custausu_register_post['email']) : '',
        'username_raw'    => isset($custausu_register_post['username']) ? sanitize_text_field((string) $custausu_register_post['username']) : '',
        'page_lang'       => (string) $custausu_tpl_page_lang,
      ];

      custausu_log('register', 'register request received', $custausu_tpl_register_ctx, 'debug');
      custausu_log('register', 'POST received', $custausu_tpl_register_ctx, 'info');
    }

    if (empty($errors)) {
      // --- RACCOLTA CAMPI ---
      $custausu_tpl_firstname = isset($custausu_register_post['firstname']) ? sanitize_text_field((string) $custausu_register_post['firstname']) : '';
      $custausu_tpl_lastname  = isset($custausu_register_post['lastname']) ? sanitize_text_field((string) $custausu_register_post['lastname']) : '';
      $custausu_tpl_username_raw = isset($custausu_register_post['username']) ? sanitize_text_field((string) $custausu_register_post['username']) : '';
      $custausu_tpl_username = sanitize_user($custausu_tpl_username_raw, true);
      $custausu_tpl_email     = isset($custausu_register_post['email']) ? sanitize_email((string) $custausu_register_post['email']) : '';
      $custausu_tpl_password  = isset($custausu_register_post['password']) ? (string) $custausu_register_post['password'] : '';
      $custausu_tpl_password2 = isset($custausu_register_post['password2']) ? (string) $custausu_register_post['password2'] : '';

      // Creiamo fullname automaticamente
      $custausu_tpl_fullname = trim($custausu_tpl_firstname . ' ' . $custausu_tpl_lastname);

      // --- VALIDAZIONI ---
      if (empty($custausu_tpl_firstname)) { $errors[] = __('Please enter your First Name.', 'custom-auth-suite'); }
      if (empty($custausu_tpl_lastname))  { $errors[] = __('Please enter your Last Name.', 'custom-auth-suite'); }
      if (empty($custausu_tpl_username))  { $errors[] = __('Please pick a Username.', 'custom-auth-suite'); }
      if (!empty($custausu_tpl_username_raw) && !preg_match('/^[A-Za-z0-9\-\_\.]+$/', $custausu_tpl_username_raw)) {
          $errors[] = __('Username may only contain letters, numbers, hyphens (-), underscores (_) and dots (.)', 'custom-auth-suite');
      }
      if (empty($custausu_tpl_email))     { $errors[] = __('Please input your Email.', 'custom-auth-suite'); }
      if (empty($custausu_tpl_password))  { $errors[] = __('Please pick a Password.', 'custom-auth-suite'); }
      if (empty($custausu_tpl_password2)) { $errors[] = __('Please confirm the Password.', 'custom-auth-suite'); }

      if (
        ($custausu_tpl_password !== '' && trim($custausu_tpl_password) !== $custausu_tpl_password) ||
        ($custausu_tpl_password2 !== '' && trim($custausu_tpl_password2) !== $custausu_tpl_password2)
      ) {
          $errors[] = __('Password cannot begin or end with whitespace.', 'custom-auth-suite');
      }

      if ($custausu_tpl_password !== $custausu_tpl_password2) {
          $errors[] = __('Passwords do not match.', 'custom-auth-suite');
      }

      if (email_exists($custausu_tpl_email)) {
          $errors[] = __('This eMail address is already registered.', 'custom-auth-suite');
      }

      if (username_exists($custausu_tpl_username)) {
          $errors[] = __('Username is already taken.', 'custom-auth-suite');
      }

      // --- Controllo accettazione Privacy ---
      if (empty($custausu_register_post['accept_privacy'])) {
          $errors[] = __('You must accept the Privacy Policy before registering.', 'custom-auth-suite');
      }

      // --- CREAZIONE UTENTE ---
      if (!empty($errors) && function_exists('custausu_log')) {
        $custausu_tpl_register_fail_ctx = [
          'count'      => count($errors),
          'errors'     => $errors,
          'username'   => (string) $custausu_tpl_username,
          'email'      => (string) $custausu_tpl_email,
          'page_lang'  => (string) $custausu_tpl_page_lang,
        ];

        custausu_log('register', 'registration pipeline failed', $custausu_tpl_register_fail_ctx + [
          'stage' => 'validation',
          'ok'    => 0,
        ], 'debug');

        custausu_log('register', 'validation failed', $custausu_tpl_register_fail_ctx, 'warn');
      }

      if (empty($errors)) {
          $custausu_tpl_user_id = wp_create_user($custausu_tpl_username, $custausu_tpl_password, $custausu_tpl_email);

          if (is_wp_error($custausu_tpl_user_id)) {
              if (function_exists('custausu_log')) {
                $custausu_tpl_register_error_ctx = [
                  'username'   => (string) $custausu_tpl_username,
                  'email'      => (string) $custausu_tpl_email,
                  'page_lang'  => (string) $custausu_tpl_page_lang,
                  'error'      => (string) $custausu_tpl_user_id->get_error_message(),
                  'errors'     => $custausu_tpl_user_id->get_error_codes(),
                ];

                custausu_log('register', 'registration pipeline failed', $custausu_tpl_register_error_ctx + [
                    'stage' => 'wp_create_user',
                    'ok'    => 0,
                ], 'debug');

                custausu_log('register', 'wp_create_user failed', $custausu_tpl_register_error_ctx, 'error');
              }

              $errors[] = sprintf(
                  /* translators: %1$s: WordPress user creation error message. */
                  __('An error occurred during the registration: %1$s', 'custom-auth-suite'),
                  $custausu_tpl_user_id->get_error_message()
              );
          } else {
              if (function_exists('custausu_log')) {
                $custausu_tpl_register_success_ctx = [
                  'user_id'   => (int) $custausu_tpl_user_id,
                  'username'  => (string) $custausu_tpl_username,
                  'email'     => (string) $custausu_tpl_email,
                  'page_lang' => (string) $custausu_tpl_page_lang,
                ];

                custausu_log('register', 'registration pipeline success', $custausu_tpl_register_success_ctx + [
                    'stage' => 'user_created',
                    'ok'    => 1,
                 ], 'debug');

                custausu_log('register', 'user created', $custausu_tpl_register_success_ctx, 'info');
              }

              // METADATI EXTRA
              update_user_meta($custausu_tpl_user_id, 'first_name', $custausu_tpl_firstname);
              update_user_meta($custausu_tpl_user_id, 'last_name',  $custausu_tpl_lastname);
              update_user_meta($custausu_tpl_user_id, 'full_name',  $custausu_tpl_fullname);

              // --- SALVA LINGUA DELL'UTENTE (source of truth = lingua pagina al submit) ---
              $custausu_tpl_form_lang = isset($custausu_register_post['current_page_lang'])
                ? sanitize_text_field((string) $custausu_register_post['current_page_lang'])
                : '';

              $custausu_tpl_form_lang = custausu_reg_pick_lang($custausu_tpl_form_lang !== '' ? $custausu_tpl_form_lang : $custausu_tpl_page_lang);

              update_user_meta($custausu_tpl_user_id, 'user_lang', $custausu_tpl_form_lang);

              // LOGIN AUTOMATICO
              wp_set_current_user($custausu_tpl_user_id);
              wp_set_auth_cookie($custausu_tpl_user_id);

              // SUCCESSO
              $custausu_tpl_success = true;

              // --- REDIRECT CON LINGUA UTENTE ---
              $custausu_tpl_user_lang = (string) get_user_meta($custausu_tpl_user_id, 'user_lang', true);
              $custausu_tpl_user_lang = custausu_reg_pick_lang($custausu_tpl_user_lang !== '' ? $custausu_tpl_user_lang : $custausu_tpl_page_lang);

              $custausu_tpl_dest = custausu_route_url('landing', $custausu_tpl_user_lang, '/');

              // Sovrascrive con redirect personalizzato se presente nel form
              if (!empty($custausu_register_post['redirect_to'])) {
                  $custausu_tpl_dest = esc_url_raw((string) $custausu_register_post['redirect_to']);
              }

              // Aggiungi parametro query per far comparire il popup JS
              $custausu_tpl_dest = add_query_arg('registration_done', '1', $custausu_tpl_dest);

              if (function_exists('custausu_log')) {
                $custausu_tpl_register_redirect_ctx = [
                  'user_id'   => (int) $custausu_tpl_user_id,
                  'username'  => (string) $custausu_tpl_username,
                  'email'     => (string) $custausu_tpl_email,
                  'dest'      => (string) $custausu_tpl_dest,
                  'user_lang' => (string) $custausu_tpl_user_lang,
                ];

                custausu_log('register', 'registration redirect resolved', $custausu_tpl_register_redirect_ctx, 'debug');
                custausu_log('register', 'redirect after register', $custausu_tpl_register_redirect_ctx, 'info');
              }

              wp_safe_redirect($custausu_tpl_dest);
              exit;
          }
      }
    }
}
$custausu_tpl_rt = '';
if (!empty($custausu_register_get['redirect_to'])) {
    $custausu_tpl_rt = (string) $custausu_register_get['redirect_to'];
} elseif (!empty($custausu_register_post['redirect_to'])) {
    $custausu_tpl_rt = esc_url_raw((string) $custausu_register_post['redirect_to']);
}

if ($custausu_tpl_rt && function_exists('custausu_redirect_to_normalize')) {
    $custausu_tpl_rt = custausu_redirect_to_normalize($custausu_tpl_rt, $custausu_tpl_page_lang, 'register_links');
}

$custausu_tpl_login_link = $custausu_tpl_login_url;

if ($custausu_tpl_rt !== '') {
    if (function_exists('custausu_url_with_redirect_to')) {
        $custausu_tpl_login_link = custausu_url_with_redirect_to($custausu_tpl_login_url, $custausu_tpl_rt);
    } else {
        $custausu_tpl_login_link_separator = strpos($custausu_tpl_login_url, '?') === false ? '?' : '&';
        $custausu_tpl_login_link = $custausu_tpl_login_url
          . $custausu_tpl_login_link_separator
          . 'redirect_to='
          . rawurlencode($custausu_tpl_rt);
    }
}


$custausu_register_lang = function_exists('custausu_auth_pages_frontend_route_lang')
  ? custausu_auth_pages_frontend_route_lang()
  : (isset($custausu_tpl_page_lang) ? (string) $custausu_tpl_page_lang : 'en');

$custausu_privacy_cookies_url = function_exists('custausu_legal_url')
  ? custausu_legal_url('privacy_cookies', $custausu_register_lang)
  : (function_exists('get_privacy_policy_url') ? get_privacy_policy_url() : '');

if (function_exists('custausu_auth_template_header')) { custausu_auth_template_header(); } else { get_header(); }
?>

<div class="register-container">
  <div class="custom-auth-anim">
    <h2><?php esc_html_e('Create Account', 'custom-auth-suite'); ?></h2>

    <?php if (!empty($errors)): ?>
        <div class="errors">
            <?php foreach ($errors as $custausu_tpl_e) { printf('<p>%s</p>', esc_html((string) $custausu_tpl_e)); } ?>
        </div>
    <?php endif; ?>

    <?php if (!$custausu_tpl_success): ?>
        <form method="post">
            <?php wp_nonce_field('custausu_register', 'custausu_register_nonce'); ?>

            <label class="required"><?php esc_html_e('First Name', 'custom-auth-suite'); ?></label>
            <input type="text" name="firstname" required>

            <label class="required"><?php esc_html_e('Last Name', 'custom-auth-suite'); ?></label>
            <input type="text" name="lastname" required>

            <label class="required"><?php esc_html_e('Username', 'custom-auth-suite'); ?></label>
            <input type="text" name="username" required>

            <label class="required"><?php esc_html_e('eMail', 'custom-auth-suite'); ?></label>
            <input type="email" name="email" required>

            <label class="required"><?php esc_html_e('Password', 'custom-auth-suite'); ?></label>
            <input type="password" name="password" required>

            <label class="required"><?php esc_html_e('Confirm Password', 'custom-auth-suite'); ?></label>
            <input type="password" name="password2" required>
            
            <input type="hidden" name="current_page_lang" value="<?php echo esc_attr($custausu_tpl_page_lang); ?>">

            <input type="hidden" name="redirect_to" value="<?php echo esc_attr($custausu_tpl_rt); ?>">
<!-- Checkbox Privacy -->
            <p>
                <label>
                    <input type="checkbox" name="accept_privacy" value="1" required>
                    <?php esc_html_e('I accept the Privacy Policy', 'custom-auth-suite'); ?>
                    <?php if (!empty($custausu_privacy_cookies_url)) : ?>
                    <a href="<?php echo esc_url($custausu_privacy_cookies_url); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('Read here', 'custom-auth-suite'); ?></a>
                  <?php else : ?>
                    <span><?php esc_html_e('Read here', 'custom-auth-suite'); ?></span>
                  <?php endif; ?>
                </label>
            </p>

            <button type="submit"><?php esc_html_e('Register', 'custom-auth-suite'); ?></button>
        </form>
        
    <?php endif; ?>

    <p><?php esc_html_e('Already registered?', 'custom-auth-suite'); ?>  
       <a href="<?php echo esc_url($custausu_tpl_login_link); ?>">
        <?php esc_html_e('Login', 'custom-auth-suite'); ?></a>
    </p>
    <p class="custausu-register-required-legend"><span class="custausu-register-required-legend__marker">*</span> <span class="custausu-register-required-legend__text"><?php esc_html_e('required field', 'custom-auth-suite'); ?></span></p>
  </div>
</div>




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