<?php
/**
 * Plugin Name: Custom Auth Suite™
 * Description: Custom Auth Suite creates custom login, registration, password reset and email verification flows with protected paths and optional assisted support.
 * Version: 0.9.2
 * Requires at least: 6.4
 * Requires PHP: 8.1
 * Author: DevDorado
 * Author URI:        https://customauthsuite.com
 * Text Domain: custom-auth-suite
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

if (!defined('WPINC')) { die; }

// ================================
// Plugin bootstrap
// ================================
if (!defined('CUSTAUSU_VERSION')) {
  define('CUSTAUSU_VERSION', '0.9.2');

/**
 * Migrate pre-prefix-cleanup local option names to the current custausu_* keys.
 *
 * The cas_* strings in this map are historical local storage identifiers only.
 * Remote/Mother protocol fields and licensing-history contracts are intentionally
 * outside this migration and remain unchanged.
 */
if (!function_exists('custausu_migrate_legacy_local_option_prefixes')) {
  function custausu_migrate_legacy_local_option_prefixes(): void {
    $custausu_marker_key = 'custausu_prefix_option_key_migration_ci2b';

    if (get_option($custausu_marker_key, '') === '20260817_ci2b') {
      return;
    }

    $custausu_missing = '__custausu_ci2b_missing_8f61b30a__';
    $custausu_option_map = [
      'cas_safe_mode_state'           => 'custausu_safe_mode_state',
      'cas_db_version'                => 'custausu_db_version',
      'cas_db_migrations'             => 'custausu_db_migrations',
      'cas_db_installed_package_plan' => 'custausu_db_installed_package_plan',
      'cas_support_diagnostics_state' => 'custausu_support_diagnostics_state',
    ];

    foreach ($custausu_option_map as $custausu_old_key => $custausu_new_key) {
      $custausu_new_value = get_option($custausu_new_key, $custausu_missing);

      if ($custausu_new_value === $custausu_missing) {
        $custausu_old_value = get_option($custausu_old_key, $custausu_missing);

        if ($custausu_old_value !== $custausu_missing) {
          update_option($custausu_new_key, $custausu_old_value, false);
        }
      }

      delete_option($custausu_old_key);
    }

    update_option($custausu_marker_key, '20260817_ci2b', false);
  }
}

custausu_migrate_legacy_local_option_prefixes();


}

// Plugin constants
if (!defined('CUSTAUSU_PLUGIN_FILE')) {
  define('CUSTAUSU_PLUGIN_FILE', __FILE__);
}

if (!defined('CUSTAUSU_PLUGIN_BASENAME')) {
  define('CUSTAUSU_PLUGIN_BASENAME', plugin_basename(__FILE__));
}

if (!defined('CUSTAUSU_PLUGIN_DIR')) {
  define('CUSTAUSU_PLUGIN_DIR', plugin_dir_path(__FILE__));
}

if (!defined('CUSTAUSU_PLUGIN_URL')) {
  define('CUSTAUSU_PLUGIN_URL', plugin_dir_url(__FILE__));
}


// CAS legacy core plugin-constant compatibility aliases.
// Stable Free-safe placement immediately after the core target definitions.
// CUSTAUSU_* is canonical; CAS_* remains read-only backward compatibility.

if (file_exists(CUSTAUSU_PLUGIN_DIR . 'cas-build.php')) {
  require_once CUSTAUSU_PLUGIN_DIR . 'cas-build.php';
}

// Core
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/edition.php';

if (function_exists('custausu_edition_bootstrap')) {
  custausu_edition_bootstrap();
}

require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/assets.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/doctor-warning-ack.php';

// Shared core
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/free-package-context.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/support-diagnostics-core.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/support-diagnostics-client-revoke.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/remote-messages.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/remote-messages-placements.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/auth-pages.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/config.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/settings.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/safety.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/admin-i18n.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/i18n-helpers.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/routes-helpers.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/translations.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/native-reset-skin.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/shared/debug.php';

// DB layer
require_once CUSTAUSU_PLUGIN_DIR . 'inc/db/db-schema.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/db/db-install.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/db/db-migrate.php';

// Free modules
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/db-email-verifications.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/access-control.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/login-redirects.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/menu-login.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/subscriber-ux.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/export-subscribers.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/email-helpers.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/user-admin-columns.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/lostpassword-handler.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/modules/freemium/email-verification.php';

// Doctor Report handoff REST bridge
require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/doctor-report-handoff.php';

// Installation Doctor / Compatibility & Safety Layer core
if (is_admin() || (defined('WP_CLI') && WP_CLI)) {
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/compatibility.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/core/support-report.php';
}

// Admin settings page
if (is_admin()) {
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-gates.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-free-services.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-community-feedback.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/installation-doctor.php';

  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/wizard.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-assets.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/health-check.php';
  if (function_exists('custausu_require_optional_module')) {
  }
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-render-auth-sections.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-page-notices.php';
require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-rm-notices.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-render-tools.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-render-system.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-render-security.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-settings-sanitize.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-settings-actions.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-email-tools.php';
  require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/custausu-admin.php';


  CUSTAUSU_Admin::init();
}

// ========================================
// DB install / upgrade / migrations
// ========================================
register_activation_hook(__FILE__, function() {
  if (function_exists('custausu_db_install_or_upgrade')) {
    custausu_db_install_or_upgrade();
  }
  if (function_exists('custausu_db_run_pending_migrations')) {
    custausu_db_run_pending_migrations();
  }

  add_option(
    'custausu_review_notice_started_at',
    time(),
    '',
    false
  );
});

register_deactivation_hook(__FILE__, function() {

  if (
    function_exists(
      'custausu_support_diagnostics_client_revoke_unschedule'
    )
  ) {
    custausu_support_diagnostics_client_revoke_unschedule();
  } else {
    wp_clear_scheduled_hook(
      'custausu_support_diagnostics_client_revoke_retry'
    );
  }
});

add_action('plugins_loaded', function() {
  if (function_exists('custausu_db_maybe_upgrade')) {
    custausu_db_maybe_upgrade();
  }
  if (function_exists('custausu_db_run_pending_migrations')) {
    custausu_db_run_pending_migrations();
  }
}, 5);

// ================================
// Plugin row links (Plugins list): Settings + package-aware upgrade link
// ================================
add_filter('plugin_action_links_' . CUSTAUSU_PLUGIN_BASENAME, function($links) {
  if (!current_user_can('manage_options')) return $links;

  $url = admin_url('admin.php?page=custausu-settings');
  $settings_link_escaped = '<a href="' . esc_url($url) . '">'
    . esc_html__('Settings', 'custom-auth-suite')
    . '</a>';

  // Fail closed: an unknown/non-package source context must not expose an upsell.
  $package_plan = function_exists('custausu_build_package_plan')
    ? sanitize_key((string) custausu_build_package_plan())
    : '';

  $locale = function_exists('get_user_locale')
    ? strtolower((string) get_user_locale())
    : strtolower((string) get_locale());
  $is_it = strpos($locale, 'it') === 0;

  $upsell_url = '';
  $upsell_label = '';
  $upsell_class = '';

  if ($package_plan === 'freemium') {
    $upsell_url = $is_it
      ? 'https://customauthsuite.com/it/il-plugin/'
      : 'https://customauthsuite.com/plugin/';
    $upsell_label = $is_it
      ? __('Potenzia Custom Auth Suite™', 'custom-auth-suite')
      : __('Boost Up Custom Auth Suite™', 'custom-auth-suite');
    $upsell_class = 'custausu-plugin-row-upsell custausu-plugin-row-upsell--free';
  } elseif ($package_plan === 'advanced') {
    $upsell_url = $is_it
      ? 'https://customauthsuite.com/it/licenza-premium-custom-auth-suite/'
      : 'https://customauthsuite.com/custom-auth-suite-premium/';
    $upsell_label = $is_it
      ? __('Ottieni Premium', 'custom-auth-suite')
      : __('Go Premium', 'custom-auth-suite');
    $upsell_class = 'custausu-plugin-row-upsell custausu-plugin-row-upsell--advanced';
  }

  if ($upsell_url !== '' && $upsell_label !== '' && $upsell_class !== '') {
    // Safe HTML returned to the WordPress Plugins list: all dynamic parts escaped here.
    $upsell_link_escaped = '<a class="' . esc_attr($upsell_class) . '" href="' . esc_url($upsell_url) . '" target="_blank" rel="noopener">'
      . esc_html($upsell_label)
      . '</a>';

    array_unshift($links, $upsell_link_escaped);
  }

  array_unshift($links, $settings_link_escaped);
  return $links;
});

add_action('admin_enqueue_scripts', function($hook_suffix) {
  if (!current_user_can('manage_options') || $hook_suffix !== 'plugins.php') {
    return;
  }

  $package_plan = function_exists('custausu_build_package_plan')
    ? sanitize_key((string) custausu_build_package_plan())
    : '';

  if (!in_array($package_plan, ['freemium', 'advanced'], true)) {
    return;
  }

  $css_path = CUSTAUSU_PLUGIN_DIR . 'inc/css/custausu-plugin-row-links.css';

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

  wp_enqueue_style(
    'custausu-plugin-row-links',
    CUSTAUSU_PLUGIN_URL . 'inc/css/custausu-plugin-row-links.css',
    [],
    (string) filemtime($css_path)
  );
});

// CAS auth page templates are handled by inc/core/auth-pages.php.



if (!function_exists('custausu_auth_theme_is_auth_page_context')) {
  function custausu_auth_theme_is_auth_page_context(): bool {
    return is_page_template('account-login.php')
      || is_page_template('account-register.php')
      || is_page_template('lost-password.php')
      || is_page_template('lost-password-confirm.php');
  }
}

add_filter('body_class', function($classes) {
  $classes = is_array($classes) ? $classes : [];

  if (!function_exists('custausu_auth_theme_is_auth_page_context') || !custausu_auth_theme_is_auth_page_context()) {
    return $classes;
  }

  $classes[] = 'custausu-auth-template';

  if (function_exists('wp_is_block_theme') && wp_is_block_theme()) {
    $classes[] = 'custausu-auth-template--block-theme';
  } else {
    $classes[] = 'custausu-auth-template--classic-theme';
  }

  return array_values(array_unique(array_filter(array_map('sanitize_html_class', $classes))));
}, 20);


if (!function_exists('custausu_auth_theme_saved_colors')) {
  function custausu_auth_theme_saved_colors(): array {
    $opt = get_option('custausu_global_settings', []);

    if (!is_array($opt)) {
      return [];
    }

    $raw = isset($opt['auth_theme']) && is_array($opt['auth_theme'])
      ? $opt['auth_theme']
      : [];

    $allowed = [
      'page_bg',
      'box_bg',
      'box_border',
      'title_color',
      'text_color',
      'link_color',
      'button_bg',
      'button_text',
      'input_border',
    ];

    $out = [];

    foreach ($allowed as $key) {
      $val = isset($raw[$key]) ? trim((string) $raw[$key]) : '';

      if ($val !== '' && $val[0] !== '#' && preg_match('/^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', $val)) {
        $val = '#' . $val;
      }

      $hex = sanitize_hex_color($val);

      if ($hex) {
        $out[$key] = $hex;
      }
    }

    return $out;
  }
}


if (!function_exists('custausu_auth_theme_saved_sizes')) {
  function custausu_auth_theme_saved_sizes(): array {
    $opt = get_option('custausu_global_settings', []);

    if (!is_array($opt)) {
      return [];
    }

    $raw = isset($opt['auth_theme']) && is_array($opt['auth_theme'])
      ? $opt['auth_theme']
      : [];

    $allowed = [
      'title_font_size',
      'field_label_font_size',
      'body_font_size',
      'button_font_size',
    ];

    $out = [];

    foreach ($allowed as $key) {
      $val = isset($raw[$key]) ? trim((string) $raw[$key]) : '';

      if ($val === '') {
        continue;
      }

      $px = absint($val);

      if ($px < 10) {
        $px = 10;
      }

      if ($px > 96) {
        $px = 96;
      }

      $out[$key] = $px;
    }

    return $out;
  }
}


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

    if (empty($colors) && empty($sizes)) {
      return '';
    }

    $css = [];
    $scope = 'body.custausu-auth-template';

    if (!empty($colors['page_bg'])) {
      $css[] = $scope . ' { background-color:' . $colors['page_bg'] . ' !important; }';
      $css[] = $scope . ' .wp-site-blocks { background-color:' . $colors['page_bg'] . ' !important; }';
    }

    $box_selectors = $scope . ' .login-container, ' .
      $scope . ' .register-container, ' .
      $scope . ' .lostpassword-container, ' .
      $scope . ' .reset-confirm-wrapper';

    $box_rules = [];

    if (!empty($colors['box_bg'])) {
      $box_rules[] = 'background:' . $colors['box_bg'] . ' !important';
    }

    if (!empty($colors['box_border'])) {
      $box_rules[] = 'border-color:' . $colors['box_border'] . ' !important';
    }

    if (!empty($colors['text_color'])) {
      $box_rules[] = 'color:' . $colors['text_color'] . ' !important';
    }

    if (!empty($box_rules)) {
      $css[] = $box_selectors . ' { ' . implode(';', $box_rules) . '; }';
    }

    if (!empty($colors['title_color'])) {
      $css[] = $scope . ' :where(.login-container h1,.login-container h2,.login-container h3,.login-container h4,.register-container h1,.register-container h2,.register-container h3,.register-container h4,.lostpassword-container h1,.lostpassword-container h2,.lostpassword-container h3,.lostpassword-container h4,.reset-confirm-wrapper h1,.reset-confirm-wrapper h2,.reset-confirm-wrapper h3,.reset-confirm-wrapper h4) { color:' . $colors['title_color'] . ' !important; }';
    }

    if (!empty($colors['text_color'])) {
      $css[] = $scope . ' :where(.login-container p,.login-container label,.register-container p,.register-container label,.lostpassword-container p,.lostpassword-container label,.reset-confirm-wrapper p,.reset-confirm-wrapper label,.errors,.reset-error,.errors-resetpsw) { color:' . $colors['text_color'] . ' !important; }';
    }

    if (!empty($colors['link_color'])) {
      $css[] = $scope . ' :where(.login-container a,.register-container a,.lostpassword-container a,.reset-confirm-wrapper a) { color:' . $colors['link_color'] . ' !important; }';
    }

    if (!empty($colors['button_bg']) || !empty($colors['button_text'])) {
      $btn_rules = [];

      if (!empty($colors['button_bg'])) {
        $btn_rules[] = 'background:' . $colors['button_bg'] . ' !important';
        $btn_rules[] = 'border-color:' . $colors['button_bg'] . ' !important';
      }

      if (!empty($colors['button_text'])) {
        $btn_rules[] = 'color:' . $colors['button_text'] . ' !important';
      }

      $css[] = $scope . ' :where(.login-container button[type="submit"],.login-container input[type="submit"],.register-container button[type="submit"],.register-container input[type="submit"],.lostpassword-container button[type="submit"],.lostpassword-container input[type="submit"],.reset-confirm-wrapper button[type="submit"],.reset-confirm-wrapper input[type="submit"],.reset-confirm-wrapper .back-login) { ' . implode(';', $btn_rules) . '; }';
    }

    if (!empty($colors['input_border'])) {
      $css[] = $scope . ' :where(.login-container input,.register-container input,.lostpassword-container input,.reset-confirm-wrapper input) { border-color:' . $colors['input_border'] . ' !important; }';
    }

    // Auth Customizer typography sizes.
    // Selectors support both legacy direct markup and the .custom-auth-anim wrapper.
    // Title/body remain separated so links and labels are not accidentally resized.
    $auth_title_selectors = implode(',', [
      $scope . ' .login-container > h2',
      $scope . ' .login-container > .custom-auth-anim > h2',
      $scope . ' .register-container > h2',
      $scope . ' .register-container > .custom-auth-anim > h2',
      $scope . ' .lostpassword-container > h2',
      $scope . ' .lostpassword-container > .custom-auth-anim > h2',
      $scope . ' .lost-password-container > h2',
      $scope . ' .lost-password-container > .custom-auth-anim > h2',
      $scope . ' .reset-confirm-wrapper > h2',
      $scope . ' .reset-confirm-wrapper > .custom-auth-anim > h2',
    ]);

    if (!empty($sizes['title_font_size'])) {
      $css[] = $auth_title_selectors . ' { font-size:' . absint($sizes['title_font_size']) . 'px !important; line-height:1.12 !important; }';
    }

    if (!empty($sizes['field_label_font_size'])) {
      $css[] = $scope . ' :where(.login-container form label,.register-container form label,.lostpassword-container form label,.lost-password-container form label,.reset-confirm-wrapper form label) { font-size:' . absint($sizes['field_label_font_size']) . 'px !important; }';
    }

    $auth_body_selectors = implode(',', [
      $scope . ' .login-container > h4',
      $scope . ' .login-container > .custom-auth-anim > h4',
      $scope . ' .lostpassword-container > p.custausu-auth-description',
      $scope . ' .lostpassword-container > .custom-auth-anim > p.custausu-auth-description',
      $scope . ' .lost-password-container > p.custausu-auth-description',
      $scope . ' .lost-password-container > .custom-auth-anim > p.custausu-auth-description',
      $scope . ' .reset-confirm-wrapper > p',
      $scope . ' .reset-confirm-wrapper > .custom-auth-anim > p',
      $scope . ' .register-container .errors',
      $scope . ' .errors',
      $scope . ' .reset-error',
      $scope . ' .errors-resetpsw',
      $scope . ' .login-error',
    ]);

    if (!empty($sizes['body_font_size'])) {
      $css[] = $auth_body_selectors . ' { font-size:' . absint($sizes['body_font_size']) . 'px !important; }';
    }

    if (!empty($sizes['button_font_size'])) {
      $css[] = $scope . ' :where(.login-container button[type="submit"],.login-container input[type="submit"],.register-container button[type="submit"],.register-container input[type="submit"],.lostpassword-container button[type="submit"],.lostpassword-container input[type="submit"],.lost-password-container button[type="submit"],.lost-password-container input[type="submit"],.reset-confirm-wrapper button[type="submit"],.reset-confirm-wrapper input[type="submit"],.reset-confirm-wrapper .back-login) { font-size:' . absint($sizes['button_font_size']) . 'px !important; }';
    }

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


// Enqueue frontend JS per popup e localizzazione lingua
add_action('wp_enqueue_scripts', function() {

    $custausu_email_verified_flag = filter_has_var(INPUT_GET, 'email_verificata');
    $custausu_registration_done_flag = filter_has_var(INPUT_GET, 'registration_done');

    $custausu_should_load_popup = (
        $custausu_email_verified_flag ||
        $custausu_registration_done_flag ||
        is_page_template('account-login.php') ||
        is_page_template('account-register.php') ||
        is_page_template('lost-password.php') ||
        is_page_template('lost-password-confirm.php')
    );

    if ($custausu_should_load_popup) {
        wp_enqueue_script(
            'custausu-popup',
            CUSTAUSU_PLUGIN_URL . 'inc/js/custausu-popup.js',
            [],
            defined('CUSTAUSU_VERSION') ? constant('CUSTAUSU_VERSION') : '1.0.0',
            true
        );
    }

    if (is_page_template('account-login.php')) {
        $custausu_login_toggle_js = CUSTAUSU_PLUGIN_DIR . 'inc/js/custausu-login-password-toggle.js';

        wp_enqueue_script(
            'custausu-login-password-toggle',
            CUSTAUSU_PLUGIN_URL . 'inc/js/custausu-login-password-toggle.js',
            [],
            is_readable($custausu_login_toggle_js) ? (string) filemtime($custausu_login_toggle_js) : CUSTAUSU_VERSION,
            true
        );
    }

    if (is_page_template('lost-password.php')) {
        $custausu_lost_password_notice_js = CUSTAUSU_PLUGIN_DIR . 'inc/js/custausu-lost-password-notice.js';

        wp_enqueue_script(
            'custausu-lost-password-notice',
            CUSTAUSU_PLUGIN_URL . 'inc/js/custausu-lost-password-notice.js',
            [],
            is_readable($custausu_lost_password_notice_js) ? (string) filemtime($custausu_lost_password_notice_js) : CUSTAUSU_VERSION,
            true
        );
    }
    $ctx = function_exists('custausu_popup_lang_context') ? custausu_popup_lang_context() : [
      'current_lang' => (string) custausu_config('routes.policy.default_lang', 'en'),
      'user_lang' => '',
    ];
    $current_lang = (string) ($ctx['current_lang'] ?? 'en');
    $user_lang    = (string) ($ctx['user_lang'] ?? '');


if ($custausu_should_load_popup) {
    wp_localize_script('custausu-popup', 'CUSTAUSU_POPUP', custausu_popup_js_cfg($current_lang, (string)($user_lang ?? '')));
}

    
    // --- CSS template ---
    wp_enqueue_style(
        'custausu-templates',
        CUSTAUSU_PLUGIN_URL . 'inc/css/custom-auth-suite.css',
        [],
        defined('CUSTAUSU_VERSION') ? constant('CUSTAUSU_VERSION') : '1.0.0'
    );

    if (function_exists('custausu_auth_theme_inline_css')) {
        // CSS-safe string: dynamic colors/sizes are validated by the construction helpers.
        $custausu_auth_theme_css_safe = custausu_auth_theme_inline_css();

        if ($custausu_auth_theme_css_safe !== '') {
            wp_add_inline_style('custausu-templates', $custausu_auth_theme_css_safe);
        }
    }
});


/* 📩 Admin notification on new user registration (portable) */
if (!function_exists('custausu_admin_new_user_notification_logo_url')) {
  function custausu_admin_new_user_notification_logo_url(): string {
    $logo_url = function_exists('get_site_icon_url') ? (string) get_site_icon_url(96) : '';

    if ($logo_url !== '') {
      return esc_url_raw($logo_url);
    }

    $custom_logo_id = function_exists('get_theme_mod') ? (int) get_theme_mod('custom_logo') : 0;

    if ($custom_logo_id > 0 && function_exists('wp_get_attachment_image_url')) {
      $custom_logo_url = (string) wp_get_attachment_image_url($custom_logo_id, 'full');

      if ($custom_logo_url !== '') {
        return esc_url_raw($custom_logo_url);
      }
    }

    return '';
  }
}

if (!function_exists('custausu_admin_new_user_notification_ip')) {
  function custausu_admin_new_user_notification_ip(): string {
    if (!isset($_SERVER['REMOTE_ADDR'])) {
      return 'N/A';
    }

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- IP is read-only notification context and is unslashed/sanitized immediately below.
    $remote_addr = wp_unslash($_SERVER['REMOTE_ADDR']);

    if (is_array($remote_addr)) {
      return 'N/A';
    }

    $ip = sanitize_text_field((string) $remote_addr);

    return $ip !== '' ? $ip : 'N/A';
  }
}

if (!function_exists('custausu_admin_new_user_notification_row')) {
  function custausu_admin_new_user_notification_row(string $label, string $value): string {
    return '<tr>'
      . '<td style="padding:10px 0;color:#6b7280;font-size:13px;line-height:1.45;width:38%;">' . esc_html($label) . '</td>'
      . '<td style="padding:10px 0;color:#111827;font-size:14px;line-height:1.45;font-weight:600;">' . esc_html($value) . '</td>'
      . '</tr>';
  }
}


if (!function_exists('custausu_admin_new_user_notification_brand_html')) {
  function custausu_admin_new_user_notification_brand_html(string $tm_color = '#24182f'): string {
    $tm_color = sanitize_hex_color($tm_color);

    if (!$tm_color) {
      $tm_color = '#24182f';
    }

    return 'Custom Auth Suite'
      . '<span style="display:inline-block;font-size:50%;line-height:1;vertical-align:super;color:' . esc_attr($tm_color) . ' !important;-webkit-text-fill-color:' . esc_attr($tm_color) . ' !important;font-weight:800;letter-spacing:0;text-transform:none;margin-left:2px;">TM</span>';
  }
}

if (!function_exists('custausu_admin_new_user_notification_html')) {
  function custausu_admin_new_user_notification_html(WP_User $user, string $ip, string $edit_url): string {
    $site_name = (string) get_bloginfo('name');
    $site_url  = home_url('/');

    $email = sanitize_email((string) ($user->user_email ?? ''));
    $name  = sanitize_text_field((string) ($user->first_name ?: $user->display_name ?: $user->user_login));
    $login = sanitize_user((string) $user->user_login, true);

    $roles = (!empty($user->roles) && is_array($user->roles))
      ? implode(', ', array_map('sanitize_key', $user->roles))
      : 'subscriber';

    $registered_at = !empty($user->user_registered)
      ? get_date_from_gmt((string) $user->user_registered, 'Y-m-d H:i:s')
      : current_time('mysql');

    $logo_url = custausu_admin_new_user_notification_logo_url();

    $logo_html = $logo_url !== ''
      ? '<img src="' . esc_url($logo_url) . '" width="54" height="54" alt="' . esc_attr($site_name) . '" style="display:block;width:54px;height:54px;border-radius:16px;object-fit:cover;border:1px solid #e5e7eb;background:#ffffff;">'
      : '<div style="width:54px;height:54px;border-radius:16px;background:#111827;color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:16px;font-weight:800;line-height:54px;text-align:center;letter-spacing:.04em;">CAS</div>';

    $rows = ''
      . custausu_admin_new_user_notification_row(__('Name / username', 'custom-auth-suite'), $name)
      . custausu_admin_new_user_notification_row(__('Username', 'custom-auth-suite'), $login)
      . custausu_admin_new_user_notification_row(__('Email', 'custom-auth-suite'), $email)
      . custausu_admin_new_user_notification_row(__('User ID', 'custom-auth-suite'), (string) $user->ID)
      . custausu_admin_new_user_notification_row(__('Role', 'custom-auth-suite'), $roles)
      . custausu_admin_new_user_notification_row(__('IP address', 'custom-auth-suite'), $ip)
      . custausu_admin_new_user_notification_row(__('Registered at', 'custom-auth-suite'), $registered_at);

    return '<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>' . esc_html__('New user registration', 'custom-auth-suite') . '</title>
</head>
<body style="margin:0;padding:0;background:#f4f7fb;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="width:100%;background:#f4f7fb;padding:28px 14px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="max-width:620px;background:#ffffff;border-radius:22px;overflow:hidden;border:1px solid #e5e7eb;box-shadow:0 12px 34px rgba(17,24,39,.08);font-family:Arial,Helvetica,sans-serif;">
          <tr>
            <td style="padding:28px 30px 22px 30px;background:linear-gradient(135deg,#f8fbff 0%,#eef5ff 100%);border-bottom:1px solid #e5e7eb;">
              <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0">
                <tr>
                  <td style="width:70px;vertical-align:middle;">' . $logo_html . '</td>
                  <td style="vertical-align:middle;">
                    <div style="font-size:12px;letter-spacing:.12em;text-transform:uppercase;color:#64748b;font-weight:700;">' . custausu_admin_new_user_notification_brand_html('#64748b') . '</div>
                    <div style="font-size:22px;line-height:1.25;color:#111827;font-weight:800;margin-top:4px;">' . esc_html__('New user registration', 'custom-auth-suite') . '</div>
                    <div style="font-size:13px;line-height:1.45;color:#64748b;margin-top:6px;">' . esc_html($site_name) . '</div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:26px 30px 8px 30px;">
              <p style="margin:0 0 18px 0;color:#374151;font-size:15px;line-height:1.6;">
                ' . esc_html__('A new account has just been created on your site.', 'custom-auth-suite') . '
              </p>

              <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border-collapse:collapse;border-top:1px solid #eef2f7;border-bottom:1px solid #eef2f7;">
                ' . $rows . '
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:22px 30px 30px 30px;">
              <a href="' . esc_url($edit_url) . '" style="display:inline-block;background:#6b2bbf;color:#ffffff;text-decoration:none;border-radius:999px;padding:12px 20px;font-size:14px;font-weight:800;">
                ' . esc_html__('Manage user', 'custom-auth-suite') . '
              </a>

              <p style="margin:18px 0 0 0;color:#6b7280;font-size:12px;line-height:1.55;">
                ' . esc_html__('This is an automatic admin notification generated by Custom Auth Suite™.', 'custom-auth-suite') . '<br>
                <a href="' . esc_url($site_url) . '" style="color:#2563eb;text-decoration:none;">' . esc_html($site_url) . '</a>
              </p>
            </td>
          </tr>

          <tr>
            <td style="padding:18px 30px;background:#6b2bbf;color:#efe7ff;text-align:center;font-size:12px;line-height:1.5;">
              <strong style="color:#ffffff;">' . custausu_admin_new_user_notification_brand_html('#ffffff') . '</strong><br>
              Simple. Necessary. Like water.
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>';
  }
}

add_action('user_register', function($user_id){
    $user = get_userdata($user_id);

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

    $admin_email = sanitize_email((string) get_option('admin_email'));

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

    $name = sanitize_text_field((string) ($user->first_name ?: $user->display_name ?: $user->user_login));

    $subject = sprintf(
        /* translators: %1$s: site name, %2$s: registered user name. */
        __('[%1$s] New user registration: %2$s', 'custom-auth-suite'),
        (string) get_bloginfo('name'),
        $name
    );

    $edit_url = add_query_arg(
        ['user_id' => (int) $user_id],
        admin_url('user-edit.php')
    );

    $message = custausu_admin_new_user_notification_html(
      $user,
      custausu_admin_new_user_notification_ip(),
      $edit_url
    );

    wp_mail($admin_email, $subject, $message, ['Content-Type: text/html; charset=UTF-8']);
});


/**
 * Doctor support report export bridge.
 *
 * The Doctor UI is rendered from admin modules, but admin-post.php can run in a
 * leaner admin request where the render-only module is not loaded yet. Register
 * the export actions from the main plugin file and load the Doctor module just
 * in time before delegating to the real exporter.
 */
if (!function_exists('custausu_admin_post_doctor_export_report_bridge')) {
  function custausu_admin_post_doctor_export_report_bridge(): void {
    if (!current_user_can('manage_options')) {
      wp_die(
        esc_html__('You are not allowed to export this report.', 'custom-auth-suite'),
        esc_html__('Permission denied', 'custom-auth-suite'),
        ['response' => 403]
      );
    }

    $doctor_file = plugin_dir_path(__FILE__) . 'inc/admin/installation-doctor.php';

    if (is_readable($doctor_file)) {
      require_once $doctor_file;
    }

    if (function_exists('custausu_admin_handle_export_support_report_action')) {
      custausu_admin_handle_export_support_report_action();
      exit;
    }

    wp_safe_redirect(
      add_query_arg(
        [
          'page'              => 'custausu-settings',
          'custausu_doctor_export' => 'failed',
        ],
        admin_url('admin.php')
      )
    );
    exit;
  }
}

foreach ([
  'custausu_export_support_report',
] as $custausu_doctor_export_action) {
  add_action(
    'admin_post_' . $custausu_doctor_export_action,
    'custausu_admin_post_doctor_export_report_bridge',
    1
  );
}


