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

require_once CUSTAUSU_PLUGIN_DIR . 'inc/admin/admin-auth-pages-tools.php';

class CUSTAUSU_Admin {

  public static function init(): void {
    add_action('admin_menu', [__CLASS__, 'admin_menu']);
    add_action('admin_init', [__CLASS__, 'register_settings']);

    add_action('admin_enqueue_scripts', 'custausu_admin_enqueue_assets');
    add_action('wp_ajax_custausu_send_test_email', 'custausu_admin_handle_test_email_ajax');
    add_action('wp_ajax_custausu_health_check', 'custausu_admin_ajax_health_check');
    add_action('admin_post_custausu_reset_settings', 'custausu_admin_handle_reset_settings_action');
    add_action('admin_post_custausu_enable_safe_mode', 'custausu_admin_handle_safe_mode_enable_action');
    add_action('admin_post_custausu_disable_safe_mode', 'custausu_admin_handle_safe_mode_disable_action');

  }

  public static function admin_menu(): void {
    add_menu_page(
      'Custom Auth Suite',
      'CAS || settings ||',
      'manage_options',
      'custausu-settings',
      [__CLASS__, 'page_settings'],
      'dashicons-shield-alt'
    );
  }

public static function sanitize_global_settings($val): array {
  $val  = is_array($val) ? $val : [];
  $prev = get_option('custausu_global_settings', []);
  $prev = is_array($prev) ? $prev : [];

  if (function_exists('custausu_admin_sanitize_global_settings_array')) {
    return custausu_admin_sanitize_global_settings_array($val, $prev);
  }

  return $prev;
}

public static function register_settings(): void {
    register_setting('custausu_settings_group', 'custausu_global_settings', [
      'type' => 'array',
      'sanitize_callback' => [__CLASS__, 'sanitize_global_settings'],
    ]);
  }

  public static function page_settings(): void {
    if (!current_user_can('manage_options')) wp_die('Forbidden');

    $opt = get_option('custausu_global_settings', []);
    $opt = is_array($opt) ? $opt : [];

    $polylang_active  = false;
    $polylang_enabled = false;

    $debug_enabled = false;
    $keep_data_on_uninstall = !empty($opt['keep_data_on_uninstall']);

$T = 'custausu_admin_t';

$field_alert_ctx = function_exists('custausu_admin_build_field_alert_context')
  ? custausu_admin_build_field_alert_context($T)
  : [
      'get_field_box_class' => function(string $target): string {
        return 'custausu-field-alert';
      },
      'get_field_note_html' => function(string $target): string {
        return '';
      },
      'route_lang_has_alert' => function(string $lang): bool {
        return false;
      },
    ];

$get_field_box_class = $field_alert_ctx['get_field_box_class'];
$get_field_note_html = $field_alert_ctx['get_field_note_html'];
$route_lang_has_alert = $field_alert_ctx['route_lang_has_alert'];

echo '<div class="wrap">';
echo '<h1><span class="dashicons dashicons-shield-alt"></span> <b>Custom Auth Suite</b> || ' . esc_html($T('Settings','Impostazioni')) . ' ||</h1>';

if (function_exists('custausu_admin_render_procasvisuallock')) {
  echo wp_kses( custausu_admin_render_procasvisuallock($T), custausu_admin_allowed_output_html() );
}


echo wp_kses( custausu_admin_render_page_notices($T), custausu_admin_allowed_output_html() );

$custausu_plan_banner_html = function_exists('custausu_admin_render_plan_banner')
  ? custausu_admin_render_plan_banner($T)
  : '';

$custausu_doctor_html = function_exists('custausu_admin_render_installation_doctor_section')
  ? custausu_admin_render_installation_doctor_section($T)
  : '';

if ($custausu_plan_banner_html !== '' || $custausu_doctor_html !== '') {
  echo '<div class="custausu-plan-doctor-stage">';
  echo wp_kses( $custausu_plan_banner_html, custausu_admin_allowed_output_html() );
  echo wp_kses( $custausu_doctor_html, custausu_admin_allowed_output_html() );
  echo '</div>';
}

// Health Check / Wizard top panel
echo wp_kses( custausu_admin_render_top_panel($T), custausu_admin_allowed_output_html() );

    echo '<div class="custausu-settings-page">';

    // ===== Free upgrade information and optional support diagnostics =====
    if (function_exists('custausu_admin_render_free_services_section')) {
      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Internal renderer returns controlled admin HTML.
      echo wp_kses( custausu_admin_render_free_services_section($T), custausu_admin_allowed_output_html() );
    }

    echo '<form method="post" action="options.php">';
    $sw = function(string $name, bool $checked, string $label, bool $disabled = false) {
      $id  = 'cas_' . md5($name);

      echo '<label class="custausu-switch'.(!empty($GLOBALS["__custausu_sw_sm"]) ? ' custausu-switch--sm' : '').'" for="'.esc_attr($id).'">';

      // Important:
      // When not disabled, always submit 0 when the checkbox is off (standard WP pattern).
      if (!$disabled) {
        echo '<input type="hidden" name="'.esc_attr($name).'" value="0">';
      }

      echo '<input id="'.esc_attr($id).'" type="checkbox" name="'.esc_attr($name).'" value="1" ' . checked($checked, true, false) . ($disabled ? disabled(true, true, false) . ' aria-disabled="true"' : '') . '>';
      echo '<span class="custausu-slider" aria-hidden="true"></span>';
      echo '<span class="custausu-label">'.esc_html($label).'</span>';
      echo '</label>';
    };

    settings_fields('custausu_settings_group');


    // ===== CAS communications and privacy =====
    if (function_exists('custausu_admin_render_cas_communications_section')) {
      echo wp_kses( custausu_admin_render_cas_communications_section(
        $T,
        $sw
      ), custausu_admin_allowed_output_html() );
    }

    // ===== Polylang =====
    echo wp_kses( custausu_admin_render_polylang_section(
      $polylang_active,
      $polylang_enabled,
      $T,
      $sw
    ), custausu_admin_allowed_output_html() );

    // ===== Debug (master + channels) =====
    echo wp_kses( custausu_admin_render_debug_section(
      $opt,
      $debug_enabled,
      $T,
      $sw
    ), custausu_admin_allowed_output_html() );

    // ===== Protected paths =====
    echo wp_kses( custausu_admin_render_protected_paths_section(
      $T,
      $opt,
      $get_field_box_class,
      $get_field_note_html
    ), custausu_admin_allowed_output_html() );

    $site_locale = (string) get_option('WPLANG');
    if ($site_locale === '') $site_locale = 'en_US';
    $site_slug = sanitize_key(strtolower(explode('_', $site_locale)[0] ?? 'en'));
    if ($site_slug === '') $site_slug = 'en';

    $default_lang = (string)($opt['routes_default_lang'] ?? $site_slug);

    // ===== Routes: page ids + paths =====
    echo wp_kses( custausu_admin_render_routes_section(
      $opt,
      $polylang_active,
      $polylang_enabled,
      $site_slug,
      $default_lang,
      $T,
      $route_lang_has_alert,
      $get_field_box_class,
      $get_field_note_html
    ), custausu_admin_allowed_output_html() );

    // ===== Assets (media picker like CCF) =====
    echo wp_kses( custausu_admin_render_assets_section(
      $T,
      $opt,
      $get_field_box_class,
      $get_field_note_html
    ), custausu_admin_allowed_output_html() );

    // ===== Auth Customizer (base palette for login/register/lost/reset pages) =====
    echo wp_kses( custausu_admin_render_auth_customizer_section(
      $opt,
      $T
    ), custausu_admin_allowed_output_html() );

    // ===== Email Customizer (palette + subjects/bodies per lingua) =====
    echo wp_kses( custausu_admin_render_email_customizer_section(
      $opt,
      $polylang_active,
      $polylang_enabled,
      $site_slug,
      $default_lang,
      $T
    ), custausu_admin_allowed_output_html() );

    // ===== WebAuthn / Passkeys =====
    echo wp_kses( custausu_admin_render_webauthn_section(
      $opt,
      $T,
      $get_field_box_class,
      $get_field_note_html
    ), custausu_admin_allowed_output_html() );

    // ===== reCAPTCHA Enterprise =====
    echo wp_kses( custausu_admin_render_recaptcha_section($opt, $T, $sw), custausu_admin_allowed_output_html() );

    // ===== CF7 Math Check (default OFF) =====
    echo wp_kses( custausu_admin_render_cf7_section($opt, $T, $sw), custausu_admin_allowed_output_html() );

    // ===== Uninstall / data retention =====
    echo wp_kses( custausu_admin_render_uninstall_section(
      $T,
      (bool)$keep_data_on_uninstall,
      $sw
    ), custausu_admin_allowed_output_html() );

    echo '<div class="custausu-save-settings-anchor">';
    submit_button($T('Save settings','Salva impostazioni'), 'primary custausu-save-settings-btn', 'submit', false);
    echo '</div>';

    echo '<div id="custausu-save-settings-float" class="custausu-save-settings-float">';
    echo '<button type="button" class="button button-primary custausu-save-settings-btn custausu-save-settings-btn--floating">'
      . esc_html($T('Save settings','Salva impostazioni'))
      . '</button>';
    echo '</div>';
    echo '</form>';

    // ===== Settings Export / Import =====
    echo wp_kses( custausu_admin_render_settings_transfer_section($T), custausu_admin_allowed_output_html() );

    // ===== Logs tools =====
    echo wp_kses( custausu_admin_render_logs_tools_section($T), custausu_admin_allowed_output_html() );

    // ===== Reset settings =====
    echo wp_kses( custausu_admin_render_reset_section($T), custausu_admin_allowed_output_html() );
    echo '</div></div>';
  }

}