<?php
// inc/shared/config.php
if (!defined('ABSPATH')) exit;

/**
 * Central config for Custom Auth Suite™.
 * No site-specific logic here: only reading sources + defaults + filters.
 */

function custausu_env() {
  if (defined('WP_ENV') && WP_ENV) return (string) WP_ENV;
  return 'production';
}

function custausu_config_all() {
  static $cfg = null;

  // Refresh cached config in non-production environments.
  $env = custausu_env();
  if ($env === 'local' || $env === 'development') {
    $cfg = null;
  }

  if ($cfg !== null) return $cfg;

  $site_locale = function_exists('determine_locale')
    ? determine_locale()
    : get_locale();
  $site_lang = strtolower(substr(str_replace('_', '-', (string) $site_locale), 0, 2));
  if (!in_array($site_lang, ['en', 'it'], true)) {
    $site_lang = 'en';
  }

  $cfg = [
    // Debug
    'debug' => [
      'enabled' => false, // master

      // livelli (severità scritte)
      'levels' => [
        'error' => true,
        'warn'  => true,
        'info'  => true,
        'debug' => true, // verbose
      ],

      // Feature channels used to scope CAS debug logging.
      'channels' => [
        'lostpassword' => true,
        'recaptcha'    => true,
        'login'        => true,
        'register'     => true,
        'email'        => true,
        'redirect'     => true,
      ],

      // Cartella log relativa a wp-content
      'dir' => 'custom-auth-suite/logs',

      // Rotazione semplice
      'max_bytes' => 2 * 1024 * 1024,
    ],
    // reCAPTCHA Enterprise is not available in the public Free package.
    // Keep the shared configuration shape stable without loading stored
    // Advanced credentials, wp-config constants or enablement flags.
    'recaptcha' => [
      'enabled' => false,
      'auth_enabled' => false,
      'cf7_enabled' => false,
      'cf7' => [
        'include_page_ids' => [],
        'include_paths' => [],
      ],
      'site_key' => '',
      'api_key' => '',
      'project' => '',
      'allowed_hosts' => [],
      'thresholds' => [
        'login' => 0.5,
        'register' => 0.6,
        'lostpassword' => 0.7,
        'cf7' => 0.5,
      ],
    ],
    // CF7 Math Check is not registered by the public Free package.
    'cf7_human_check' => [
      'enabled' => false,
      'min' => 1,
      'max' => 9,
      'ttl' => 600,
    ],
    'assets' => [
      'spinner_url' => '',
      'logingif_url' => '',
      'logingif_enabled' => true,
      'checkgif_url' => '',
      'email_logo_url' => '',
      'support_url' => home_url('/'),
    ],
    // i18n / routing defaults.
  'i18n' => [
    'enabled' => false,
    'langs' => [$site_lang],
  ],

  'routes' => [
    'templates' => [
      'login'        => 'account-login.php',
      'register'     => 'account-register.php',
      'lostpassword' => 'lost-password.php',
      'lostpassword_confirm'=> 'lost-password-confirm.php',
    ],
    'menu' => [
      'theme_locations' => [],
      'menus' => [],
    ],
    'logout_redirect' => [
      'default' => '/',
    ],

    'page_ids' => [
      $site_lang => [
        'login'                => 0,
        'register'             => 0,
        'lostpassword'         => 0,
        'lostpassword_confirm' => 0,
        'landing'              => 0,
      ],
    ],

    'paths' => [
      $site_lang => [
        'login'                => '',
        'register'             => '',
        'lostpassword'         => '',
        'lostpassword_confirm' => '',
        'landing'              => '',
      ],
    ],

    'policy' => [
      'default_lang' => $site_lang,
      'force_lang_on_auth_pages' => true,
      'preserve_redirect_to'     => true,
   ],
  ],
    'protected' => [
    'paths' => [],
    ],
  ];

    /**
     * Allow site-specific overrides without editing plugin core.
     * Use add_filter('custausu_config', function($cfg){ ...; return $cfg; });
    */
    // Optional: allow a full config override array via constant (advanced)
    if ((defined('CUSTAUSU_CONFIG') || defined('CAS_CONFIG'))) {
        $custausu_config_const = (defined('CUSTAUSU_CONFIG') ? constant('CUSTAUSU_CONFIG') : constant('CAS_CONFIG'));
        if (is_array($custausu_config_const)) {
            $cfg = array_replace_recursive($cfg, $custausu_config_const);
        }
    }
    // Admin settings override defaults.
    if (function_exists('custausu_settings_get')) {
      $opt = custausu_settings_get();

      if (is_array($opt) && !empty($opt)) {

        $default_lang = isset($opt['routes_default_lang']) && is_scalar($opt['routes_default_lang'])
          ? sanitize_key((string) $opt['routes_default_lang'])
          : $site_lang;
        if (!in_array($default_lang, ['en', 'it'], true)) {
          $default_lang = $site_lang;
        }

        $cfg['routes']['policy']['default_lang'] = $default_lang;
        $cfg['i18n']['enabled'] = false;
        $cfg['i18n']['langs'] = [$default_lang];

        if (array_key_exists('routes_logout_redirect', $opt) && is_array($opt['routes_logout_redirect'])) {
          $path = $opt['routes_logout_redirect'][$default_lang]
            ?? $opt['routes_logout_redirect']['default']
            ?? '';
          $path = trim((string) $path);

          if ($path === '') {
            $cfg['routes']['logout_redirect'][$default_lang] = '';
          } else {
            if ($path[0] !== '/') {
              $path = '/' . $path;
            }
            $cfg['routes']['logout_redirect'][$default_lang] = rtrim($path, '/') . '/';
          }
        }

        // Normal Premium Debug settings are deliberately inactive in non-Premium packages.
        $cfg['debug']['enabled'] = false;
        $cfg['debug']['levels'] = [];
        $cfg['debug']['channels'] = [];

        // protected paths (stored as textarea string)
        if (array_key_exists('protected_paths', $opt)) {
          $lines = preg_split('/\r\n|\r|\n/', (string)$opt['protected_paths']);
          $pp = [];
          foreach ((array)$lines as $p) {
            $p = trim((string)$p);
            if ($p === '') continue;
            if ($p[0] !== '/') $p = '/' . $p;
            $pp[] = rtrim($p, '/') . '/';
          }
          $pp = array_values(array_unique($pp));
          if ($pp) $cfg['protected']['paths'] = $pp;
        }

        // Load only the active Free language route map.
        if (!empty($opt['routes_paths'][$default_lang]) && is_array($opt['routes_paths'][$default_lang])) {
          foreach ($opt['routes_paths'][$default_lang] as $key => $value) {
            $cfg['routes']['paths'][$default_lang][$key] = (string) $value;
          }
        }
        if (!empty($opt['routes_page_ids'][$default_lang]) && is_array($opt['routes_page_ids'][$default_lang])) {
          foreach ($opt['routes_page_ids'][$default_lang] as $key => $value) {
            $cfg['routes']['page_ids'][$default_lang][$key] = (int) $value;
          }
        }



      }
    } 
    
    $cfg = apply_filters('custausu_config', $cfg);

    $default_lang = sanitize_key((string)($cfg['routes']['policy']['default_lang'] ?? $site_lang));
    if (!in_array($default_lang, ['en', 'it'], true)) {
      $default_lang = $site_lang;
    }
    $cfg['routes']['policy']['default_lang'] = $default_lang;
    $cfg['i18n'] = [
      'enabled' => false,
      'langs' => [$default_lang],
    ];

  return $cfg;
}

/**
 * Get config value by path: custausu_config('webauthn.rp_id')
 */
function custausu_config($path, $default = null) {
  $cfg = custausu_config_all();
  $parts = explode('.', (string)$path);
  foreach ($parts as $p) {
    if (!is_array($cfg) || !array_key_exists($p, $cfg)) return $default;
    $cfg = $cfg[$p];
  }
  return $cfg;
}
/**
 * Allowed HTML for CAS-generated administration UI fragments at the final output boundary.
 *
 * Dynamic values inside renderers must still be escaped for their own context. This
 * allow-list is the final KSES boundary used when a renderer intentionally returns HTML.
 *
 * @return array<string,array<string,bool>>
 */
function custausu_admin_allowed_output_html(): array {
    $allowed = wp_kses_allowed_html( 'post' );

    $global = [
        'id'                                  => true,
        'class'                               => true,
        'style'                               => true,
        'title'                               => true,
        'role'                                => true,
        'aria-label'                          => true,
        'aria-hidden'                         => true,
        'aria-disabled'                       => true,
        'aria-describedby'                    => true,
        'aria-controls'                       => true,
        'aria-expanded'                       => true,
        'aria-live'                           => true,
        'aria-atomic'                         => true,
        'aria-current'                        => true,
        'aria-selected'                       => true,
        'data-custausu-field'                 => true,
        'data-custausu-gate-feature'          => true,
        'data-custausu-doctor-warning-confirm'=> true,
        'data-custausu-health-run'            => true,
        'data-editor-id'                      => true,
        'data-email-lang'                     => true,
        'data-health'                         => true,
        'data-lang'                           => true,
        'data-route-alert'                    => true,
        'data-default-color'                  => true,
        'data-role'                           => true,
        'data-type'                           => true,
        'data-var'                            => true,
        'data-target'                         => true,
        'data-copy'                           => true,
        'data-copy-label'                     => true,
        'data-copied-label'                   => true,
        'data-action'                         => true,
        'data-status'                         => true,
        'data-section'                        => true,
        'data-source'                         => true,
        'data-placement'                      => true,
        'data-message-id'                     => true,
        'data-dismiss-hash'                   => true,
        'data-scenario'                       => true,
        'data-priority'                       => true,
    ];

    $extra = [
        'form' => [
            'action' => true, 'method' => true, 'class' => true, 'id' => true,
            'name' => true, 'target' => true, 'enctype' => true, 'accept-charset' => true,
        ],
        'input' => [
            'type' => true, 'name' => true, 'value' => true, 'id' => true, 'class' => true,
            'placeholder' => true, 'autocomplete' => true, 'spellcheck' => true,
            'min' => true, 'max' => true, 'step' => true, 'pattern' => true,
            'checked' => true, 'disabled' => true, 'readonly' => true, 'required' => true,
            'multiple' => true, 'accept' => true,
        ],
        'select' => [
            'name' => true, 'id' => true, 'class' => true, 'disabled' => true,
            'required' => true, 'multiple' => true,
        ],
        'option' => [
            'value' => true, 'selected' => true, 'disabled' => true,
        ],
        'textarea' => [
            'name' => true, 'id' => true, 'class' => true, 'placeholder' => true,
            'rows' => true, 'cols' => true, 'readonly' => true, 'disabled' => true,
            'required' => true,
        ],
        'button' => [
            'type' => true, 'name' => true, 'value' => true, 'id' => true, 'class' => true,
            'disabled' => true,
        ],
        'label' => [ 'for' => true, 'class' => true ],
        'fieldset' => [ 'class' => true, 'disabled' => true ],
        'legend' => [ 'class' => true ],
        'details' => [ 'class' => true, 'id' => true, 'open' => true ],
        'summary' => [ 'class' => true ],
        'table' => [ 'class' => true, 'id' => true ],
        'thead' => [ 'class' => true ],
        'tbody' => [ 'class' => true ],
        'tr' => [ 'class' => true ],
        'th' => [ 'class' => true, 'scope' => true, 'colspan' => true, 'rowspan' => true ],
        'td' => [ 'class' => true, 'colspan' => true, 'rowspan' => true, 'data-label' => true ],
        'colgroup' => [ 'class' => true ],
        'col' => [ 'class' => true, 'span' => true ],
        'video' => [
            'id' => true, 'class' => true, 'src' => true, 'poster' => true, 'preload' => true,
            'controls' => true, 'autoplay' => true, 'muted' => true, 'loop' => true,
            'playsinline' => true, 'width' => true, 'height' => true,
        ],
        'source' => [ 'src' => true, 'type' => true, 'media' => true ],
        'svg' => [
            'class' => true, 'role' => true, 'focusable' => true, 'viewbox' => true,
            'width' => true, 'height' => true, 'xmlns' => true,
        ],
        'defs' => [],
        'g' => [ 'class' => true, 'transform' => true ],
        'path' => [ 'd' => true, 'id' => true, 'class' => true, 'fill' => true ],
        'circle' => [
            'class' => true, 'cx' => true, 'cy' => true, 'r' => true, 'fill' => true,
        ],
        'text' => [
            'class' => true, 'textlength' => true, 'lengthadjust' => true,
            'x' => true, 'y' => true, 'fill' => true,
        ],
        'textpath' => [
            'href' => true, 'startoffset' => true, 'text-anchor' => true,
        ],
        'article' => [ 'id' => true, 'class' => true ],
        'section' => [ 'id' => true, 'class' => true ],
        'aside' => [ 'id' => true, 'class' => true ],
    ];

    foreach ( $extra as $tag => $attributes ) {
        $allowed[ $tag ] = array_merge( $allowed[ $tag ] ?? [], $attributes );
    }

    foreach ( $allowed as $tag => $attributes ) {
        $allowed[ $tag ] = array_merge( $attributes, $global );
    }

    return $allowed;
}

/**
 * Language helpers for the active Free language context.
 */
function custausu_i18n_enabled(): bool {
  return false;
}

function custausu_current_lang(): string {
  $lang = sanitize_key((string) custausu_config('routes.policy.default_lang', ''));

  if ($lang === '') {
    $locale = function_exists('determine_locale')
      ? determine_locale()
      : get_locale();
    $locale = strtolower(str_replace('_', '-', (string) $locale));
    $parts = explode('-', $locale);
    $lang = sanitize_key((string) ($parts[0] ?? ''));
  }

  return in_array($lang, ['en', 'it'], true) ? $lang : 'en';
}

function custausu_supported_langs(): array {
  return [custausu_current_lang()];
}

function custausu_is_lang(string $lang): bool {
  $lang = sanitize_key(strtolower(trim($lang)));
  return $lang !== '' && $lang === custausu_current_lang();
}
