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

if (!function_exists('custausu_admin_settings_site_slug')) {
  function custausu_admin_settings_site_slug(): string {
    $site_locale = (string) get_option('WPLANG');
    if ($site_locale === '') $site_locale = 'en_US';

    $site_slug = sanitize_key(strtolower(explode('_', $site_locale)[0] ?? 'en'));
    return $site_slug !== '' ? $site_slug : 'en';
  }
}

if (!function_exists('custausu_admin_settings_normalize_path')) {
  function custausu_admin_settings_normalize_path($path): string {
    $path = trim((string)$path);
    if ($path === '') return '';

    $parsed = wp_parse_url($path, PHP_URL_PATH);
    if (is_string($parsed) && $parsed !== '') {
      $path = $parsed;
    }

    $path = trim($path);
    if ($path === '') return '';

    if ($path[0] !== '/') {
      $path = '/' . $path;
    }

    $path = preg_replace('#/+#', '/', $path);
    $path = function_exists('mb_strtolower')
      ? mb_strtolower($path, 'UTF-8')
      : strtolower($path);

    return rtrim($path, '/') . '/';
  }
}

if (!function_exists('custausu_admin_settings_normalize_logout_redirect_path')) {
  function custausu_admin_settings_normalize_logout_redirect_path($path): string {
    $path = trim((string)$path);

    if ($path === '' || $path === '/') {
      return '';
    }

    $parsed = wp_parse_url($path, PHP_URL_PATH);
    if (is_string($parsed) && $parsed !== '') {
      $path = $parsed;
    }

    $path = trim($path);

    if ($path === '' || $path === '/') {
      return '';
    }

    if ($path[0] !== '/') {
      $path = '/' . $path;
    }

    $path = preg_replace('#/+#', '/', $path);
    $path = function_exists('mb_strtolower')
      ? mb_strtolower($path, 'UTF-8')
      : strtolower($path);

    $path = rtrim($path, '/') . '/';

    return $path === '/' ? '' : $path;
  }
}

if (!function_exists('custausu_admin_settings_split_paths_list')) {
  function custausu_admin_settings_split_paths_list(string $raw): array {
    $raw = trim($raw);
    if ($raw === '') return [];

    $parts = preg_split('/[\s,;]+/', $raw);
    $parts = array_values(array_filter(array_map('trim', (array)$parts)));

    return $parts;
  }
}

if (!function_exists('custausu_admin_sanitize_global_settings_array')) {
  function custausu_admin_sanitize_global_settings_array(array $val, array $prev): array {
    $val  = is_array($val) ? $val : [];
    $prev = is_array($prev) ? $prev : [];

    $keep = function(string $k, $fallback = null) use ($val, $prev) {
      return array_key_exists($k, $val) ? $val[$k] : ($prev[$k] ?? $fallback);
    };
    // ===== i18n =====
    $site_slug = custausu_admin_settings_site_slug();

    $default_lang = strtolower(trim((string)($keep('routes_default_lang', $site_slug))));
    if (!preg_match('/^[a-z0-9_-]+$/', $default_lang)) $default_lang = $site_slug;

    $polylang_enabled = !empty($prev['polylang_enabled']) ? 1 : 0;
    $langs_raw = $prev['i18n_langs'] ?? [$site_slug];

    if (is_string($langs_raw)) {
      $langs_raw = array_map('trim', explode(',', $langs_raw));
    }

    $langs_i18n = [];
    foreach ((array)$langs_raw as $l) {
      $l = sanitize_key(strtolower(trim((string)$l)));
      if ($l !== '') $langs_i18n[] = $l;
    }

    $langs_i18n = array_values(array_unique($langs_i18n));

    if (!$langs_i18n) {
      $langs_i18n = [$site_slug];
    }

    if (!in_array($default_lang, $langs_i18n, true)) {
      array_unshift($langs_i18n, $default_lang);
      $langs_i18n = array_values(array_unique($langs_i18n));
    }

    $allowed_langs = $langs_i18n;


    // ===== debug =====
    // Non-Premium packages ignore submitted Debug controls and normalize the
    // unavailable Premium Debug settings to an inert OFF state.
    $debug_enabled = 0;
    $debug_levels = [];
    $debug_channels = [];


    // ===== protected paths =====
    $prot_raw = (string)($keep('protected_paths', ''));
    $protected_paths = [];

    foreach (custausu_admin_settings_split_paths_list($prot_raw) as $p) {
      $p = wp_strip_all_tags((string) $p);
      $p = trim($p);

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

      // Protected paths are site-relative. Prefix before URL sanitization so
      // relative entries are not interpreted as URL schemes/hosts.
      if ($p[0] !== '/') {
        $p = '/' . $p;
      }

      $p = esc_url_raw($p);

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

      $p = custausu_admin_settings_normalize_path($p);
      if ($p !== '') {
        $protected_paths[] = $p;
      }
    }

    $protected_paths = array_values(array_unique($protected_paths));
    // ===== Advanced Assets downgrade-safe dormant state =====
    // The Free package ignores submitted Assets controls. Existing Advanced
    // values are retained only so replacing Free with Advanced later does not
    // erase prior branding configuration.
    $assets_spinner_url = esc_url_raw((string)($prev['assets_spinner_url'] ?? ''));
    $assets_logingif_url = esc_url_raw((string)($prev['assets_logingif_url'] ?? ''));
    $assets_logingif_enabled = array_key_exists('assets_logingif_enabled', $prev)
      ? (!empty($prev['assets_logingif_enabled']) ? 1 : 0)
      : 1;
    $assets_checkgif_url = esc_url_raw((string)($prev['assets_checkgif_url'] ?? ''));
    $assets_email_logo_url = esc_url_raw((string)($prev['assets_email_logo_url'] ?? ''));
    $assets_email_logo_width = (int)($prev['assets_email_logo_width'] ?? 180);
    if ($assets_email_logo_width < 30) $assets_email_logo_width = 30;
    if ($assets_email_logo_width > 600) $assets_email_logo_width = 600;
    $assets_support_url = esc_url_raw((string)($prev['assets_support_url'] ?? ''));


    // ===== Color helpers =====
    $hex = function($x, $fallback){
      $x = is_string($x) ? trim($x) : '';
      $v = sanitize_hex_color($x);
      return $v ? $v : $fallback;
    };

    $hex_optional = function($x): string {
      $x = is_string($x) ? trim($x) : '';

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

      $v = sanitize_hex_color($x);
      return $v ? $v : '';
    };


    $px_optional = function($x): string {
      $x = is_string($x) || is_numeric($x) ? trim((string) $x) : '';

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

      $px = absint($x);

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

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

      return (string) $px;
    };

    // ===== Auth Theme =====
    $auth_theme_raw = (array)($keep('auth_theme', []));
    $auth_theme = [];

    foreach ([
      'page_bg',
      'box_bg',
      'box_border',
      'title_color',
      'text_color',
      'link_color',
      'button_bg',
      'button_text',
      'input_border',
    ] as $auth_theme_key) {
      $auth_theme_val = $hex_optional($auth_theme_raw[$auth_theme_key] ?? '');

      if ($auth_theme_val !== '') {
        $auth_theme[$auth_theme_key] = $auth_theme_val;
      }
    }


    foreach ([
      'title_font_size',
      'field_label_font_size',
      'body_font_size',
      'button_font_size',
    ] as $auth_theme_size_key) {
      $auth_theme_size_val = $px_optional($auth_theme_raw[$auth_theme_size_key] ?? '');

      if ($auth_theme_size_val !== '') {
        $auth_theme[$auth_theme_size_key] = $auth_theme_size_val;
      }
    }

    // ===== Email Theme =====

    $def_email_theme = [
      'wrap_bg'     => '#f7f7f7',
      'wrap_border' => '#222222',
      'wrap_text'   => '#222222',
      'h2_color'    => '#222222',
      'btn_bg'      => '#222222',
      'btn_text'    => '#ffffff',
    ];

    $prev_email_theme = (array)($prev['email_theme'] ?? []);
    $raw_email_theme  = (array)($keep('email_theme', $prev_email_theme ?: $def_email_theme));

    $email_theme = [
      'wrap_bg'     => $hex($raw_email_theme['wrap_bg'] ?? '',     $def_email_theme['wrap_bg']),
      'wrap_border' => $hex($raw_email_theme['wrap_border'] ?? '', $def_email_theme['wrap_border']),
      'wrap_text'   => $hex($raw_email_theme['wrap_text'] ?? '',   $def_email_theme['wrap_text']),
      'h2_color'    => $hex($raw_email_theme['h2_color'] ?? '',    $def_email_theme['h2_color']),
      'btn_bg'      => $hex($raw_email_theme['btn_bg'] ?? '',      $def_email_theme['btn_bg']),
      'btn_text'    => $hex($raw_email_theme['btn_text'] ?? '',    $def_email_theme['btn_text']),
    ];

    // ===== Email Templates =====
    $prev_email_tpl = (array)($prev['email_tpl'] ?? []);
    $email_tpl_in   = $keep('email_tpl', $prev_email_tpl);
    $email_tpl      = is_array($email_tpl_in) ? $email_tpl_in : $prev_email_tpl;

    $email_tpl = array_intersect_key($email_tpl, array_flip($allowed_langs));

    $san_subj = function($x){
      return sanitize_text_field((string)$x);
    };

    $san_html = function($x){
      $raw = (string)$x;
      $raw = custausu_email_preserve_tokens($raw, 'encode');
      $raw = wp_kses_post($raw);
      $raw = custausu_email_preserve_tokens($raw, 'decode');
      return $raw;
    };

    $email_types = [
      'verify_register' => 'Verify eMail (after register)',
      'verify_resend'   => 'Verify eMail (admin resend)',
      'welcome'         => 'Welcome eMail',
    ];
    $allowed_type_keys = array_keys($email_types);

    foreach ($langs_i18n as $lng) {
      $lng = sanitize_key((string)$lng);
      if ($lng === '') continue;

      if (!isset($email_tpl[$lng]) || !is_array($email_tpl[$lng])) {
        $email_tpl[$lng] = [];
      }

      $email_tpl[$lng] = array_intersect_key($email_tpl[$lng], array_flip($allowed_type_keys));

      foreach ($allowed_type_keys as $type) {
        if (!isset($email_tpl[$lng][$type]) || !is_array($email_tpl[$lng][$type])) {
          $email_tpl[$lng][$type] = [];
        }

        $sk = "email_subject_{$lng}_{$type}";
        $bk = "email_body_{$lng}_{$type}";

        if (array_key_exists($sk, $val)) {
          $email_tpl[$lng][$type]['subject'] = $san_subj($val[$sk] ?? '');
        } else {
          if (!isset($email_tpl[$lng][$type]['subject'])) {
            $email_tpl[$lng][$type]['subject'] = (string)($prev_email_tpl[$lng][$type]['subject'] ?? '');
          }
        }

        if (array_key_exists($bk, $val)) {
          $email_tpl[$lng][$type]['body'] = $san_html($val[$bk] ?? '');
        } else {
          if (!isset($email_tpl[$lng][$type]['body'])) {
            $email_tpl[$lng][$type]['body'] = (string)($prev_email_tpl[$lng][$type]['body'] ?? '');
          }
        }
      }
    }
    // ===== webauthn =====
    // Non-Premium packages ignore submitted WebAuthn controls. Existing
    // Premium values are preserved only as dormant downgrade-safe state so a
    // later Premium reinstall does not destroy the site's prior RP settings.
    $webauthn_rp_id = sanitize_text_field((string)($prev['webauthn_rp_id'] ?? ''));
    $webauthn_origin = esc_url_raw((string)($prev['webauthn_origin'] ?? ''));
    $webauthn_rp_name = sanitize_text_field((string)($prev['webauthn_rp_name'] ?? ''));

    $max_dev_alias = (int)($prev['webauthn_max_device_aliases'] ?? 3);
    $max_dev_alias = max(1, min(10, $max_dev_alias));

    $max_label_alias = (int)($prev['webauthn_max_label_aliases'] ?? 3);
    $max_label_alias = max(1, min(10, $max_label_alias));
    // ===== reCAPTCHA / CF7 Advanced downgrade-safe state =====
    // The Free package ignores all submitted Advanced anti-bot controls.
    // Existing Advanced values are retained only as dormant state so replacing
    // Free with Advanced later does not erase a previously configured site.
    $recaptcha_enabled = !empty($prev['recaptcha_enabled']) ? 1 : 0;
    $recaptcha_auth_enabled = !empty($prev['recaptcha_auth_enabled']) ? 1 : 0;
    $recaptcha_cf7_enabled = !empty($prev['recaptcha_cf7_enabled']) ? 1 : 0;
    $recaptcha_prefer_wp_config = !empty($prev['recaptcha_prefer_wp_config']) ? 1 : 0;

    $recaptcha_project_id = sanitize_text_field((string)($prev['recaptcha_project_id'] ?? ''));
    $recaptcha_site_key = sanitize_text_field((string)($prev['recaptcha_site_key'] ?? ''));
    $recaptcha_api_key = sanitize_text_field((string)($prev['recaptcha_api_key'] ?? ''));

    $thr = static function($value, float $default): float {
      if (!is_numeric($value)) return $default;
      $number = (float)$value;
      if ($number < 0.0) return 0.0;
      if ($number > 1.0) return 1.0;
      return $number;
    };

    $thr_login = $thr($prev['recaptcha_threshold_login'] ?? 0.5, 0.5);
    $thr_register = $thr($prev['recaptcha_threshold_register'] ?? 0.6, 0.6);
    $thr_lost = $thr($prev['recaptcha_threshold_lostpassword'] ?? 0.7, 0.7);
    $thr_cf7 = $thr($prev['recaptcha_threshold_cf7'] ?? 0.5, 0.5);
    $cf7_mathcheck_enabled = !empty($prev['cf7_mathcheck_enabled']) ? 1 : 0;


    // ===== uninstall / data retention =====
    $keep_data_on_uninstall = array_key_exists('keep_data_on_uninstall', $val)
      ? (!empty($val['keep_data_on_uninstall']) ? 1 : 0)
      : (array_key_exists('keep_data_on_uninstall', $prev) ? (!empty($prev['keep_data_on_uninstall']) ? 1 : 0) : 0);

    // ===== routes =====
    $routes_paths_in    = $keep('routes_paths', $prev['routes_paths'] ?? []);
    $routes_page_ids_in = $keep('routes_page_ids', $prev['routes_page_ids'] ?? []);

    $logout_redirect_prev = isset($prev['routes_logout_redirect']) && is_array($prev['routes_logout_redirect'])
      ? $prev['routes_logout_redirect']
      : [];

    $logout_redirect_post = array_key_exists('routes_logout_redirect', $val) && is_array($val['routes_logout_redirect'])
      ? $val['routes_logout_redirect']
      : [];

    $routes_paths    = is_array($routes_paths_in) ? $routes_paths_in : (array)($prev['routes_paths'] ?? []);
    $routes_page_ids = is_array($routes_page_ids_in) ? $routes_page_ids_in : (array)($prev['routes_page_ids'] ?? []);
    $logout_redirect = array_replace($logout_redirect_prev, $logout_redirect_post);

    $route_keys = ['login','register','lostpassword','lostpassword_confirm','landing'];
    $langs_routes = $allowed_langs ?: [$site_slug];

    $allowed_logout_keys = array_merge(['default'], $langs_routes);
    $logout_redirect = array_intersect_key($logout_redirect, array_flip($allowed_logout_keys));

    $logout_redirect['default'] = custausu_admin_settings_normalize_logout_redirect_path($logout_redirect['default'] ?? '');

    foreach ($langs_routes as $lng) {
      $raw = array_key_exists($lng, $logout_redirect) ? $logout_redirect[$lng] : '';
      $logout_redirect[$lng] = custausu_admin_settings_normalize_logout_redirect_path($raw);
    }

    $routes_paths    = array_intersect_key($routes_paths, array_flip($langs_routes));
    $routes_page_ids = array_intersect_key($routes_page_ids, array_flip($langs_routes));

    foreach ($langs_routes as $lng) {
      $routes_paths[$lng]    = (isset($routes_paths[$lng]) && is_array($routes_paths[$lng])) ? $routes_paths[$lng] : [];
      $routes_page_ids[$lng] = (isset($routes_page_ids[$lng]) && is_array($routes_page_ids[$lng])) ? $routes_page_ids[$lng] : [];

      foreach (array_keys($routes_paths[$lng]) as $k) {
        if (!in_array($k, $route_keys, true)) unset($routes_paths[$lng][$k]);
      }
      foreach (array_keys($routes_page_ids[$lng]) as $k) {
        if (!in_array($k, $route_keys, true)) unset($routes_page_ids[$lng][$k]);
      }
    }

    $allowed_route_keys = [
      'login',
      'register',
      'lostpassword',
      'lostpassword_confirm',
      'landing',
    ];

    if (!is_array($allowed_route_keys) || empty($allowed_route_keys)) {
      $allowed_route_keys = ['login','register','lostpassword','lostpassword_confirm','landing'];
    }

    $allowed_route_keys = array_values(array_unique(array_filter(array_map('strval', $allowed_route_keys))));
    $allowed_route_flip = array_flip($allowed_route_keys);

    foreach ($langs_routes as $lng) {
      $routes_paths[$lng]    = is_array($routes_paths[$lng] ?? null)    ? $routes_paths[$lng]    : [];
      $routes_page_ids[$lng] = is_array($routes_page_ids[$lng] ?? null) ? $routes_page_ids[$lng] : [];

      $routes_paths[$lng]    = array_intersect_key($routes_paths[$lng], $allowed_route_flip);
      $routes_page_ids[$lng] = array_intersect_key($routes_page_ids[$lng], $allowed_route_flip);
    }

    foreach ($langs_routes as $lng) {
      foreach (['login','register','lostpassword','lostpassword_confirm','landing'] as $k) {
        $pk = "routes_path_{$lng}_{$k}";
        if (array_key_exists($pk, $val)) {
          $p = custausu_admin_settings_normalize_path($val[$pk] ?? '');
          $routes_paths[$lng][$k] = ($p !== '') ? $p : '';
        }

        $ik = "routes_page_id_{$lng}_{$k}";
        if (array_key_exists($ik, $val)) {
          $routes_page_ids[$lng][$k] = (int)($val[$ik] ?? 0);
        }
      }
    }

    /*
     * CAS legal links per language.
     *
     * Stored as:
     * legal_links[lang][privacy_cookies][page_id]
     * legal_links[lang][privacy_cookies][url]
     */
    $legal_links_in = $keep('legal_links', $prev['legal_links'] ?? []);
    $legal_links = is_array($legal_links_in) ? $legal_links_in : [];

    $legal_links = array_intersect_key($legal_links, array_flip($langs_routes));

    foreach ($langs_routes as $lng) {
      $lng = sanitize_key((string) $lng);
      if ($lng === '') {
        continue;
      }

      $legal_links[$lng] = isset($legal_links[$lng]) && is_array($legal_links[$lng])
        ? $legal_links[$lng]
        : [];

      $prev_privacy = isset($legal_links[$lng]['privacy_cookies']) && is_array($legal_links[$lng]['privacy_cookies'])
        ? $legal_links[$lng]['privacy_cookies']
        : [];

      $page_id = absint($prev_privacy['page_id'] ?? 0);
      $url = isset($prev_privacy['url']) && is_scalar($prev_privacy['url'])
        ? trim((string) $prev_privacy['url'])
        : '';

      $page_key = "legal_privacy_cookies_page_id_{$lng}";
      $url_key  = "legal_privacy_cookies_url_{$lng}";

      if (array_key_exists($page_key, $val)) {
        $page_id = absint($val[$page_key] ?? 0);
      }

      if (array_key_exists($url_key, $val)) {
        $raw_url = is_scalar($val[$url_key] ?? null)
          ? trim(sanitize_text_field(wp_unslash((string) $val[$url_key])))
          : '';

        $url = '';

        if ($raw_url !== '') {
          if (preg_match('#^https?://#i', $raw_url)) {
            $url = esc_url_raw($raw_url);
          } else {
            $path = '/' . ltrim($raw_url, '/');
            $path = strtok($path, '#') ?: $path;
            $path = strtok($path, '?') ?: $path;

            $path = '/' . trim($path, '/');

            if ($path !== '/') {
              $url = $path . '/';
            }
          }
        }
      }

      $legal_links[$lng]['privacy_cookies'] = [
        'page_id' => $page_id,
        'url'     => $url,
      ];
    }


    return [
      'polylang_enabled' => $polylang_enabled,
      'routes_default_lang' => $default_lang,
      'i18n_langs' => $langs_i18n,

      'debug_enabled'  => $debug_enabled,
      'debug_levels'   => $debug_levels,
      'debug_channels' => $debug_channels,

      'protected_paths' => implode("\n", $protected_paths),

      'assets_spinner_url' => $assets_spinner_url,
      'assets_logingif_url' => $assets_logingif_url,
      'assets_logingif_enabled' => $assets_logingif_enabled,
      'assets_checkgif_url' => $assets_checkgif_url,
      'assets_email_logo_url' => $assets_email_logo_url,
      'assets_email_logo_width' => $assets_email_logo_width,
      'assets_support_url' => $assets_support_url,

      'auth_theme' => $auth_theme,
      'email_theme' => $email_theme,
      'email_tpl'   => $email_tpl,

      'webauthn_rp_id' => $webauthn_rp_id,
      'webauthn_origin' => $webauthn_origin,
      'webauthn_rp_name' => $webauthn_rp_name,
      'webauthn_max_device_aliases' => $max_dev_alias,
      'webauthn_max_label_aliases' => $max_label_alias,

      'recaptcha_enabled' => $recaptcha_enabled,
      'recaptcha_auth_enabled' => $recaptcha_auth_enabled,
      'recaptcha_cf7_enabled' => $recaptcha_cf7_enabled,
      'recaptcha_prefer_wp_config' => $recaptcha_prefer_wp_config,

      'recaptcha_project_id' => $recaptcha_project_id,
      'recaptcha_site_key' => $recaptcha_site_key,
      'recaptcha_api_key' => $recaptcha_api_key,

      'recaptcha_threshold_login' => $thr_login,
      'recaptcha_threshold_register' => $thr_register,
      'recaptcha_threshold_lostpassword' => $thr_lost,
      'recaptcha_threshold_cf7' => $thr_cf7,

      'cf7_mathcheck_enabled' => $cf7_mathcheck_enabled,
      'keep_data_on_uninstall' => $keep_data_on_uninstall,


'routes_paths' => $routes_paths,
      'routes_page_ids' => $routes_page_ids,
      'legal_links' => $legal_links,
      'routes_logout_redirect' => $logout_redirect,
    ];
  }
}