<?php
/**
 * Settings Page Class
 * 
 * Centralized settings page with tabs for all plugin settings.
 *
 * @package Polanger_Dashboard_Tools
 */

if ( ! defined( 'ABSPATH' ) ) {
  exit;
}

class PDT_Settings_Page {

  /**
   * Option name for general settings
   */
  private $option_name = 'pdt_general_settings';

  /**
   * Default settings
   */
  private $default_settings = array(
    'allowed_users'          => array(),
    'user_access_levels'     => array(), // user_id => 'full', 'readonly' or 'hidden'
    'restrict_access'        => false,
    'content_visibility_enabled'                 => false,
    'content_visibility_default_denied_behavior' => 'message',
    'content_visibility_default_compatibility'   => 'hard',
    'content_visibility_default_redirect_url'    => '',
    'content_visibility_default_message'         => '',
    'content_visibility_hide_from_archives'      => true,
    'content_visibility_hide_from_rest'          => true,
    'content_visibility_hide_from_sitemaps'      => true,
    'two_factor_enabled'     => false,
    'two_factor_method'      => 'email', // 'email' or 'authenticator'
    'two_factor_include_super_admin' => false,
    'two_factor_roles'       => array( 'administrator' ),
    'two_factor_code_expiry' => 10,
    'two_factor_max_attempts' => 3,
    'two_factor_lockout_minutes' => 30,
    'log_visibility'         => 'all',
    'email_alert_threshold'  => 'disabled',
    'admin_footer_text'      => '',
    'admin_footer_version'   => true,
  );

  /**
   * Constructor
   */
  public function __construct() {
    add_action( 'admin_init', array( $this, 'check_access_restriction' ), 1 );
    add_action( 'admin_init', array( $this, 'apply_admin_footer_customizations' ) );
    add_action( 'admin_init', array( $this, 'handle_log_export' ), 5 );
    add_action( 'admin_menu', array( $this, 'enforce_hidden_user_menu_visibility' ), 999999 );
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_settings_scripts' ) );
  }

  /**
   * Get settings
   */
  public function get_settings() {
    $settings = get_option( $this->option_name, array() );
    $settings = wp_parse_args( $settings, $this->default_settings );

    /**
     * Filter effective settings before runtime use.
     *
     * @param array  $settings    Parsed settings.
     * @param string $option_name Option key.
     * @param array  $defaults    Option defaults.
     * @param string $context     Consumer context.
     */
    return apply_filters( 'polanger_effective_settings', $settings, $this->option_name, $this->default_settings, 'settings-page' );
  }

  /**
   * Update settings
   */
  public function update_settings( $settings ) {
    return update_option( $this->option_name, $settings );
  }

  /**
   * Determine whether a user should be treated as protected admin.
   *
   * On multisite, this maps to network Super Admin. On single-site, this
   * falls back to users with manage_options capability.
   *
   * @param int $user_id User ID.
   * @return bool
   */
  private function is_protected_admin_user( $user_id ) {
    $user_id = absint( $user_id );
    if ( ! $user_id ) {
      return false;
    }

    if ( is_multisite() ) {
      return is_super_admin( $user_id );
    }

    // On single-site, protect only one fallback admin account to avoid lockout.
    return $user_id === $this->get_fallback_protected_admin_id();
  }

  /**
   * Get the fallback protected admin user ID to prevent lockout.
   *
   * @return int
   */
  private function get_fallback_protected_admin_id() {
    if ( is_multisite() ) {
      $super_admins = get_super_admins();
      if ( ! empty( $super_admins ) ) {
        $super_admin = get_user_by( 'login', $super_admins[0] );
        if ( $super_admin ) {
          return (int) $super_admin->ID;
        }
      }
    }

    $admins = get_users(
      array(
        'role'    => 'administrator',
        'orderby' => 'ID',
        'order'   => 'ASC',
        'number'  => 1,
        'fields'  => array( 'ID' ),
      )
    );

    if ( ! empty( $admins ) && isset( $admins[0]->ID ) ) {
      return (int) $admins[0]->ID;
    }

    return (int) get_current_user_id();
  }

  /**
   * Get 2FA coverage statistics
   */
  private function get_2fa_coverage_stats( $required_roles ) {
    $stats = array(
      'total'     => 0,
      'protected' => 0,
      'excluded'  => 0,
    );
    $settings = $this->get_settings();
    $exclude_protected_admin = empty( $settings['two_factor_include_super_admin'] );
    
    if ( empty( $required_roles ) ) {
      return $stats;
    }
    
    // Get users in required roles
    foreach ( $required_roles as $role ) {
      $users = get_users( array( 'role' => $role ) );
      
      foreach ( $users as $user ) {
        $stats['total']++;
        
        // Exclude protected admin users unless Super Admin inclusion is enabled.
        if ( $exclude_protected_admin && $this->is_protected_admin_user( $user->ID ) ) {
          $stats['excluded']++;
        } else {
          $stats['protected']++;
        }
      }
    }
    
    return $stats;
  }

  /**
   * Check if current user has access to plugin
   */
  public function check_access_restriction() {
    $settings = $this->get_settings();

    $current_user_id = get_current_user_id();
    
    if ( ! $current_user_id ) {
      return;
    }

    // Hidden access level: always hide menu and block direct URL access,
    // even if global restrict_access toggle is disabled.
    if ( $this->get_user_access_level( $current_user_id ) === 'hidden' ) {
      add_action( 'admin_menu', array( $this, 'remove_plugin_menus' ), 99999 );
      add_action( 'admin_init', array( $this, 'block_direct_access' ), 10 );
      return;
    }

    if ( empty( $settings['restrict_access'] ) ) {
      return;
    }

    $allowed_users = $settings['allowed_users'];
    
    if ( empty( $allowed_users ) ) {
      return;
    }

    // Check if user is in allowed list
    if ( ! in_array( $current_user_id, $allowed_users ) ) {
      // Remove plugin menus for this user
      add_action( 'admin_menu', array( $this, 'remove_plugin_menus' ), 99999 );
      
      // Block direct URL access
      add_action( 'admin_init', array( $this, 'block_direct_access' ), 10 );
    }
  }

  /**
   * Remove plugin menus for restricted users
   */
  public function remove_plugin_menus() {
    global $menu, $submenu;

    remove_menu_page( 'polanger-dashboard' );

    // Fallback: aggressively remove all known plugin pages.
    $plugin_pages = array(
      'polanger-dashboard',
      'polanger-admin-bar',
      'polanger-login-page',
      'polanger-activity-log',
      'polanger-dashboard-widgets',
      'polanger-addons',
      'polanger-settings',
    );

    foreach ( $plugin_pages as $page_slug ) {
      remove_submenu_page( 'polanger-dashboard', $page_slug );
    }

    if ( is_array( $menu ) ) {
      foreach ( $menu as $key => $item ) {
        if ( isset( $item[2] ) && ( $item[2] === 'polanger-dashboard' || strpos( (string) $item[2], 'polanger-' ) === 0 ) ) {
          unset( $menu[ $key ] );
        }
      }
    }

    if ( isset( $submenu['polanger-dashboard'] ) && is_array( $submenu['polanger-dashboard'] ) ) {
      unset( $submenu['polanger-dashboard'] );
    }
  }

  /**
   * Force-hide plugin menus for users with hidden access level.
   *
   * Runs very late on admin_menu to avoid hook order/timing issues.
   *
   * @return void
   */
  public function enforce_hidden_user_menu_visibility() {
    if ( $this->get_user_access_level() !== 'hidden' ) {
      return;
    }

    $this->remove_plugin_menus();
  }

  /**
   * Block direct URL access for restricted users
   */
  public function block_direct_access() {
    // phpcs:disable WordPress.Security.NonceVerification.Recommended
    if ( ! isset( $_GET['page'] ) ) {
      return;
    }
    $page = sanitize_text_field( wp_unslash( $_GET['page'] ) );
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    $restricted_pages = array(
      'polanger-dashboard',
      'polanger-menu-manager',
      'polanger-admin-bar',
      'polanger-login-page',
      'polanger-activity-log',
      'polanger-dashboard-widgets',
      'polanger-addons',
      'polanger-settings',
    );

    if ( in_array( $page, $restricted_pages, true ) ) {
      wp_die( 
        esc_html__( 'You do not have permission to access this page.', 'polanger-admin-menu-manager' ),
        esc_html__( 'Access Denied', 'polanger-admin-menu-manager' ),
        array( 'response' => 403 )
      );
    }
  }

  /**
   * Get current tab
   */
  private function get_current_tab() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    return isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'general';
  }

  /**
   * Render settings page
   */
  public function render_page() {
    $current_tab = $this->get_current_tab();
    $is_readonly = $this->is_user_readonly();
    $tabs = array(
      'general'       => __( 'General', 'polanger-admin-menu-manager' ),
      'security'      => __( '2FA', 'polanger-admin-menu-manager' ),
      'activity-log'  => __( 'Activity Log', 'polanger-admin-menu-manager' ),
      'content-visibility' => __( 'Frontend Content Visibility', 'polanger-admin-menu-manager' ),
      'miscellaneous' => __( 'Miscellaneous', 'polanger-admin-menu-manager' ),
    );

    /**
     * Filter the list of Settings page tabs.
     *
     * Addons can register additional tabs without modifying core. Tab IDs
     * must be slugs (a-z, 0-9, underscores, hyphens). The associated label
     * should be a translation-ready string.
     *
     * @param array $tabs Map of tab_id => label.
     */
    $tabs = apply_filters( 'pdt_settings_tabs', $tabs );
    if ( ! is_array( $tabs ) || empty( $tabs ) ) {
      $tabs = array( 'general' => __( 'General', 'polanger-admin-menu-manager' ) );
    }
    $tabs = $this->reorder_settings_tabs( $tabs );

    /**
     * Filter the icon class for a given tab.
     *
     * @param array $icons Map of tab_id => dashicons class name (without the
     *                     leading "dashicons" token, e.g. "dashicons-admin-generic").
     */
    $tab_icons = apply_filters(
      'pdt_settings_tab_icons',
      array(
        'general'       => 'dashicons-admin-generic',
        'security'      => 'dashicons-shield',
        'activity-log'  => 'dashicons-list-view',
        'content-visibility' => 'dashicons-visibility',
        'miscellaneous' => 'dashicons-admin-tools',
      )
    );

    if ( ! isset( $tabs[ $current_tab ] ) ) {
      $current_tab = 'general';
    }

    ?>
    <div class="wrap pdt-settings-wrap <?php echo $is_readonly ? 'pdt-readonly-mode' : ''; ?>">
      <div class="pdt-page-header">
        <span class="dashicons dashicons-admin-settings"></span>
        <h1><?php esc_html_e( 'Settings', 'polanger-admin-menu-manager' ); ?></h1>
        <p><?php esc_html_e( 'Configure plugin settings and security options.', 'polanger-admin-menu-manager' ); ?></p>
      </div>
      
      <?php if ( $is_readonly ) : ?>
        <div class="pdt-readonly-banner">
          <span class="dashicons dashicons-visibility"></span>
          <div>
            <strong><?php esc_html_e( 'Read-only Mode', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'You can view settings but cannot make changes. Contact your administrator for full access.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php endif; ?>

      <div class="pdt-settings-container">
        <nav class="pdt-settings-tabs">
          <?php foreach ( $tabs as $tab_id => $tab_label ) :
            $icon_class = isset( $tab_icons[ $tab_id ] ) ? $tab_icons[ $tab_id ] : 'dashicons-admin-generic';
            ?>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=polanger-settings&tab=' . $tab_id ) ); ?>"
               class="pdt-tab-link <?php echo $current_tab === $tab_id ? 'active' : ''; ?>">
              <span class="dashicons <?php echo esc_attr( $icon_class ); ?>"></span>
              <?php echo esc_html( $tab_label ); ?>
            </a>
          <?php endforeach; ?>
        </nav>

        <div class="pdt-settings-content">
          <?php
          switch ( $current_tab ) {
            case 'general':
              $this->render_general_tab();
              break;
            case 'security':
              $this->render_security_tab();
              break;
            case 'activity-log':
              $this->render_activity_log_tab();
              break;
            case 'content-visibility':
              $this->render_content_visibility_tab();
              break;
            case 'miscellaneous':
              $this->render_miscellaneous_tab();
              break;
            default:
              /**
               * Fires for addon-registered Settings tabs.
               *
               * Addons that register a tab via the `pdt_settings_tabs` filter
               * should hook into this action to render the tab body. The tab
               * id is passed so a single handler can dispatch multiple tabs.
               *
               * @param string $current_tab Active tab id.
               * @param bool   $is_readonly Whether read-only mode is active.
               */
              do_action( 'pdt_settings_render_tab', $current_tab, $is_readonly );

              /**
               * Fires for a specific addon-registered Settings tab.
               *
               * Useful when an addon owns exactly one tab and wants a clean,
               * per-tab callback name.
               *
               * @param bool $is_readonly Whether read-only mode is active.
               */
              do_action( 'pdt_settings_render_tab_' . $current_tab, $is_readonly );
              break;
          }
          ?>
        </div>
      </div>
    </div>
    <?php
  }

  /**
   * Enforce a stable Settings tab order.
   *
   * @param array $tabs Tabs map.
   * @return array
   */
  private function reorder_settings_tabs( $tabs ) {
    $tabs = is_array( $tabs ) ? $tabs : array();
    $ordered = array();
    $preferred = array(
      'general',
      'security',
      'activity-log',
      'comments',
      'woocommerce',
      'maintenance',
      'recaptcha',
      'firewall',
      'authenticator',
      'content-visibility',
      'shield',
      'miscellaneous',
    );

    foreach ( $preferred as $tab_id ) {
      if ( isset( $tabs[ $tab_id ] ) ) {
        $ordered[ $tab_id ] = $tabs[ $tab_id ];
      }
    }

    foreach ( $tabs as $tab_id => $label ) {
      if ( ! isset( $ordered[ $tab_id ] ) ) {
        $ordered[ $tab_id ] = $label;
      }
    }

    return $ordered;
  }

  /**
   * Render General tab
   */
  private function render_general_tab() {
    $settings = $this->get_settings();
    $is_readonly = $this->is_user_readonly();
    
    // Handle form submission (only if user has full access)
    if ( isset( $_POST['pdt_general_save'] ) && check_admin_referer( 'pdt_general_settings' ) && ! $is_readonly ) {
      $allowed_users = array();
      if ( isset( $_POST['allowed_users'] ) && is_array( $_POST['allowed_users'] ) ) {
        $allowed_users = array_map( 'absint', wp_unslash( $_POST['allowed_users'] ) );
      }
      
      // Process access levels
      $user_access_levels = array();
      if ( isset( $_POST['user_access_level'] ) && is_array( $_POST['user_access_level'] ) ) {
        $raw_access_levels = wp_unslash( $_POST['user_access_level'] );
        $raw_access_levels = array_map( 'sanitize_text_field', (array) $raw_access_levels );
        foreach ( $raw_access_levels as $user_id => $level ) {
          $user_id = absint( $user_id );
          $level = in_array( $level, array( 'full', 'readonly', 'hidden' ), true ) ? $level : 'full';
          $user_access_levels[ $user_id ] = $level;
        }
      }
      
      // Protected admin safeguard to prevent lockout.
      $super_admin_id = $this->get_fallback_protected_admin_id();
      
      // If allowed_users is empty or only contains super admin, ensure super admin is included
      $other_admins = array_diff( $allowed_users, array( $super_admin_id ) );
      if ( empty( $other_admins ) && ! in_array( $super_admin_id, $allowed_users ) ) {
        $allowed_users[] = $super_admin_id;
      }
      
      // Super Admin always has full access
      $user_access_levels[ $super_admin_id ] = 'full';
      
      // Hidden users are stored in access levels but excluded from allowed_users.
      $effective_allowed_users = array();
      foreach ( $allowed_users as $allowed_user_id ) {
        $allowed_user_id = absint( $allowed_user_id );
        $level = isset( $user_access_levels[ $allowed_user_id ] ) ? $user_access_levels[ $allowed_user_id ] : 'full';
        if ( 'hidden' !== $level ) {
          $effective_allowed_users[] = $allowed_user_id;
        }
      }

      $new_settings = $settings;
      $new_settings['restrict_access'] = isset( $_POST['restrict_access'] );
      $new_settings['allowed_users'] = $effective_allowed_users;
      $new_settings['user_access_levels'] = $user_access_levels;
      
      $this->update_settings( $new_settings );
      $settings = $new_settings;
      
      echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'polanger-admin-menu-manager' ) . '</p></div>';
    }

    // Get all administrators
    $admins = get_users( array( 'role__in' => array( 'administrator' ) ) );
    
    ?>
    <form method="post" class="pdt-settings-form">
      <?php wp_nonce_field( 'pdt_general_settings' ); ?>
      
      <div class="pdt-settings-section">
        <h2><?php esc_html_e( 'Access Control', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="description"><?php esc_html_e( 'Control which administrators can access this plugin.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div class="pdt-form-row">
          <label class="pdt-toggle-switch">
            <input type="checkbox" name="restrict_access" value="1" <?php checked( $settings['restrict_access'] ); ?> id="restrict_access" />
            <span class="pdt-toggle-slider"></span>
            <span class="pdt-toggle-label"><?php esc_html_e( 'Enable Access Restriction', 'polanger-admin-menu-manager' ); ?></span>
          </label>
          <p class="description"><?php esc_html_e( 'When enabled, only selected users can access this plugin. Others will not see the menu or be able to access pages directly.', 'polanger-admin-menu-manager' ); ?></p>
        </div>

        <div class="pdt-form-row pdt-user-selection<?php echo ! empty( $settings['restrict_access'] ) ? ' is-visible' : ''; ?>" id="user-selection-wrapper">
          <label><?php esc_html_e( 'Allowed Users', 'polanger-admin-menu-manager' ); ?></label>
          <p class="description"><?php esc_html_e( 'Select which administrators can access this plugin.', 'polanger-admin-menu-manager' ); ?></p>
          
          <?php
          // Identify protected admin fallback user.
          $super_admin_id = $this->get_fallback_protected_admin_id();
          ?>
          
          <div class="pdt-user-checkboxes">
            <?php foreach ( $admins as $admin ) : 
              $is_super_admin = ( $admin->ID === $super_admin_id );
              $stored_level = isset( $settings['user_access_levels'][ $admin->ID ] ) ? $settings['user_access_levels'][ $admin->ID ] : '';
              $is_hidden_level = ( 'hidden' === $stored_level );
              $is_selected = in_array( $admin->ID, $settings['allowed_users'], true ) || $is_hidden_level;
              $access_level = isset( $settings['user_access_levels'][ $admin->ID ] ) ? $settings['user_access_levels'][ $admin->ID ] : 'full';
            ?>
              <div class="pdt-user-card-wrapper <?php echo $is_selected ? 'selected' : ''; ?> <?php echo $is_super_admin ? 'is-super-admin' : ''; ?>">
                <label class="pdt-user-card">
                  <input type="checkbox" name="allowed_users[]" value="<?php echo esc_attr( $admin->ID ); ?>" 
                    <?php checked( $is_selected ); ?>
                    <?php echo $is_super_admin ? 'data-super-admin="1"' : ''; ?> 
                    class="pdt-user-checkbox" />
                  <span class="pdt-user-avatar"><?php echo get_avatar( $admin->ID, 64 ); ?></span>
                  <span class="pdt-user-name"><?php echo esc_html( $admin->display_name ); ?></span>
                  <span class="pdt-user-email"><?php echo esc_html( $admin->user_email ); ?></span>
                  <?php if ( $is_super_admin ) : ?>
                    <span class="pdt-super-admin-badge"><?php esc_html_e( 'Super Admin', 'polanger-admin-menu-manager' ); ?></span>
                  <?php endif; ?>
                </label>
                
                <div class="pdt-access-level-selector <?php echo $is_selected ? 'is-visible' : ''; ?>">
                  <span class="pdt-access-label"><?php esc_html_e( 'Access:', 'polanger-admin-menu-manager' ); ?></span>
                  <select name="user_access_level[<?php echo esc_attr( $admin->ID ); ?>]" 
                          class="pdt-access-select"
                          <?php echo $is_super_admin ? 'disabled' : ''; ?>>
                    <option value="full" <?php selected( $access_level, 'full' ); ?>>
                      <?php esc_html_e( 'Full Access', 'polanger-admin-menu-manager' ); ?>
                    </option>
                    <option value="readonly" <?php selected( $access_level, 'readonly' ); ?> <?php echo $is_super_admin ? 'disabled' : ''; ?>>
                      <?php esc_html_e( 'Read-only', 'polanger-admin-menu-manager' ); ?>
                    </option>
                    <option value="hidden" <?php selected( $access_level, 'hidden' ); ?> <?php echo $is_super_admin ? 'disabled' : ''; ?>>
                      <?php esc_html_e( 'Completely Hide', 'polanger-admin-menu-manager' ); ?>
                    </option>
                  </select>
                  <?php if ( $is_super_admin ) : ?>
                    <input type="hidden" name="user_access_level[<?php echo esc_attr( $admin->ID ); ?>]" value="full" />
                  <?php endif; ?>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
          
          <div class="pdt-info-notice pdt-super-admin-notice">
            <span class="dashicons dashicons-shield"></span>
            <div>
              <strong><?php esc_html_e( 'Super Admin Protection', 'polanger-admin-menu-manager' ); ?></strong>
              <p><?php esc_html_e( 'The Super Admin must always have access to prevent lockout. To remove Super Admin access, first assign at least one other administrator as an allowed user.', 'polanger-admin-menu-manager' ); ?></p>
            </div>
          </div>
          <div class="pdt-info-notice">
            <span class="dashicons dashicons-hidden"></span>
            <div>
              <strong><?php esc_html_e( 'Completely Hide Mode', 'polanger-admin-menu-manager' ); ?></strong>
              <p><?php esc_html_e( 'Users with this level will not see the plugin menu and cannot access plugin pages via direct URL.', 'polanger-admin-menu-manager' ); ?></p>
            </div>
          </div>
        </div>
      </div>

      <p class="submit">
        <button type="submit" name="pdt_general_save" class="button button-primary">
          <?php esc_html_e( 'Save Settings', 'polanger-admin-menu-manager' ); ?>
        </button>
      </p>
    </form>

    <?php
  }

  /**
   * Render Frontend Content Visibility tab.
   *
   * @return void
   */
  private function render_content_visibility_tab() {
    $settings = $this->get_settings();
    $is_readonly = $this->is_user_readonly();

    if ( isset( $_POST['pdt_content_visibility_save'] ) && check_admin_referer( 'pdt_content_visibility_settings' ) && ! $is_readonly ) {
      $new_settings = PDT_Content_Visibility::sanitize_settings( $settings, $_POST );

      $this->update_settings( $new_settings );
      $settings = $new_settings;

      echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'polanger-admin-menu-manager' ) . '</p></div>';
    }

    ?>
    <form method="post" class="pdt-settings-form">
      <?php wp_nonce_field( 'pdt_content_visibility_settings' ); ?>

      <?php PDT_Content_Visibility::render_settings_section( $settings ); ?>

      <p class="submit">
        <button type="submit" name="pdt_content_visibility_save" class="button button-primary">
          <?php esc_html_e( 'Save Settings', 'polanger-admin-menu-manager' ); ?>
        </button>
      </p>
    </form>
    <?php
  }

  /**
   * Render Security tab
   */
  private function render_security_tab() {
    $settings = $this->get_settings();
    $current_user_id = get_current_user_id();
    $is_readonly = $this->is_user_readonly();
    $email_verified = get_option( 'pdt_2fa_email_verified', false );
    $email_test_passed = false;
    $show_recovery_keys = false;
    $recovery_keys = array();
    
    // Handle email test (only if user has full access)
    if ( isset( $_POST['pdt_test_email'] ) && check_admin_referer( 'pdt_security_settings' ) && ! $is_readonly ) {
      $test_result = $this->send_2fa_test_email( wp_get_current_user()->user_email );
      
      if ( $test_result['success'] ) {
        update_option( 'pdt_2fa_email_verified', true );
        $email_verified = true;
        $email_test_passed = true;
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Test email sent successfully! Check your inbox.', 'polanger-admin-menu-manager' ) . '</p></div>';
      } else {
        update_option( 'pdt_2fa_email_verified', false );
        $email_verified = false;
        echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Failed to send test email. Please check your email settings (SMTP).', 'polanger-admin-menu-manager' ) . '</p></div>';
        if ( ! empty( $test_result['error'] ) ) {
          echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html( $test_result['error'] ) . '</p></div>';
        }
      }
    }
    
    // Handle form submission (only if user has full access)
    if ( isset( $_POST['pdt_security_save'] ) && check_admin_referer( 'pdt_security_settings' ) && ! $is_readonly ) {
      $wants_to_enable = isset( $_POST['two_factor_enabled'] );
      $selected_method = isset( $_POST['two_factor_method'] ) ? sanitize_key( wp_unslash( $_POST['two_factor_method'] ) ) : 'email';
      
      // Email verification is only required when email method is selected
      if ( $wants_to_enable && 'email' === $selected_method && ! $email_verified ) {
        echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Please verify your email delivery by sending a test email before enabling 2FA with email verification.', 'polanger-admin-menu-manager' ) . '</p></div>';
        $wants_to_enable = false;
      }

      // Re-validate email delivery when enabling 2FA with email method to avoid stale "verified" state.
      if ( $wants_to_enable && 'email' === $selected_method && ! $email_test_passed ) {
        $enable_check_result = $this->send_2fa_test_email( wp_get_current_user()->user_email );
        if ( ! $enable_check_result['success'] ) {
          update_option( 'pdt_2fa_email_verified', false );
          $email_verified = false;
          $wants_to_enable = false;
          echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Email delivery check failed during 2FA enable. Please confirm SMTP/email configuration and try again.', 'polanger-admin-menu-manager' ) . '</p></div>';
          if ( ! empty( $enable_check_result['error'] ) ) {
            echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html( $enable_check_result['error'] ) . '</p></div>';
          }
        }
      }
      
      $was_disabled = ! $settings['two_factor_enabled'];
      
      $allowed_roles = array_keys( wp_roles()->get_names() );
      $selected_roles = array();
      if ( isset( $_POST['two_factor_roles'] ) && is_array( $_POST['two_factor_roles'] ) ) {
        $selected_roles = array_map( 'sanitize_text_field', wp_unslash( $_POST['two_factor_roles'] ) );
        $selected_roles = array_values( array_intersect( $selected_roles, $allowed_roles ) );
      }

      $code_expiry = isset( $_POST['two_factor_code_expiry'] ) ? absint( wp_unslash( $_POST['two_factor_code_expiry'] ) ) : 10;
      if ( ! in_array( $code_expiry, array( 5, 10, 15 ), true ) ) {
        $code_expiry = 10;
      }

      $max_attempts = isset( $_POST['two_factor_max_attempts'] ) ? absint( wp_unslash( $_POST['two_factor_max_attempts'] ) ) : 3;
      if ( ! in_array( $max_attempts, array( 3, 5 ), true ) ) {
        $max_attempts = 3;
      }

      $lockout_minutes = isset( $_POST['two_factor_lockout_minutes'] ) ? absint( wp_unslash( $_POST['two_factor_lockout_minutes'] ) ) : 30;
      if ( ! in_array( $lockout_minutes, array( 15, 30, 60, 1440 ), true ) ) {
        $lockout_minutes = 30;
      }

      // Get selected 2FA method
      $two_factor_method = isset( $_POST['two_factor_method'] ) ? sanitize_key( wp_unslash( $_POST['two_factor_method'] ) ) : 'email';
      if ( ! in_array( $two_factor_method, array( 'email', 'authenticator' ), true ) ) {
        $two_factor_method = 'email';
      }

      $new_settings = $settings;
      $new_settings['two_factor_enabled'] = $wants_to_enable;
      $new_settings['two_factor_method'] = $two_factor_method;
      $new_settings['two_factor_include_super_admin'] = $wants_to_enable && isset( $_POST['two_factor_include_super_admin'] );
      $new_settings['two_factor_roles'] = $selected_roles;
      $new_settings['two_factor_code_expiry'] = $code_expiry;
      $new_settings['two_factor_max_attempts'] = $max_attempts;
      $new_settings['two_factor_lockout_minutes'] = $lockout_minutes;
      
      $this->update_settings( $new_settings );
      $settings = $new_settings;
      
      // Generate recovery keys for current user if 2FA just enabled
      if ( $wants_to_enable && $was_disabled ) {
        global $pdt_two_factor;
        if ( $pdt_two_factor ) {
          $recovery_keys = $pdt_two_factor->generate_recovery_keys( $current_user_id );
          $show_recovery_keys = true;
        }
      }
      
      if ( ! $show_recovery_keys ) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'polanger-admin-menu-manager' ) . '</p></div>';
      }
    }
    
    // Handle regenerate recovery keys
    if ( isset( $_POST['pdt_regenerate_keys'] ) && check_admin_referer( 'pdt_security_settings' ) && ! $is_readonly ) {
      global $pdt_two_factor;
      if ( $pdt_two_factor ) {
        $recovery_keys = $pdt_two_factor->generate_recovery_keys( $current_user_id );
        $show_recovery_keys = true;
      }
    }
    
    // Check for recovery keys from authenticator verification
    $authenticator_recovery_keys = get_transient( 'pdt_show_recovery_keys_' . $current_user_id );
    if ( ! empty( $authenticator_recovery_keys ) && is_array( $authenticator_recovery_keys ) ) {
      delete_transient( 'pdt_show_recovery_keys_' . $current_user_id );
      $recovery_keys = $authenticator_recovery_keys;
      $show_recovery_keys = true;
    }

    $roles = wp_roles()->get_names();
    
    // Get current user's recovery keys count
    global $pdt_two_factor;
    $recovery_keys_count = 0;
    if ( $pdt_two_factor ) {
      $recovery_keys_count = $pdt_two_factor->get_recovery_keys_count( $current_user_id );
    }
    
    ?>
    
    <?php if ( $show_recovery_keys && ! empty( $recovery_keys ) ) : ?>
      <div class="pdt-recovery-keys-modal">
        <div class="pdt-recovery-keys-content">
          <button type="button" class="pdt-recovery-modal-close" aria-label="<?php esc_attr_e( 'Close', 'polanger-admin-menu-manager' ); ?>">
            <span class="dashicons dashicons-no-alt"></span>
          </button>
          <div class="pdt-recovery-keys-icon">
            <span class="dashicons dashicons-admin-network"></span>
          </div>
          <h2><?php esc_html_e( 'Save Your Recovery Keys', 'polanger-admin-menu-manager' ); ?></h2>
          <p class="pdt-recovery-keys-warning">
            <?php esc_html_e( 'These recovery keys can be used to access your account if you lose access to your email. Each key can only be used once.', 'polanger-admin-menu-manager' ); ?>
            <br><strong><?php esc_html_e( 'Save these keys now. They will not be shown again!', 'polanger-admin-menu-manager' ); ?></strong>
          </p>
          <div class="pdt-recovery-keys-list">
            <?php foreach ( $recovery_keys as $key ) : ?>
              <code><?php echo esc_html( $key ); ?></code>
            <?php endforeach; ?>
          </div>
          <div class="pdt-recovery-keys-actions">
            <button type="button" class="button pdt-copy-recovery-keys"
                    data-recovery-keys="<?php echo esc_attr( implode( "\n", $recovery_keys ) ); ?>"
                    data-copy-success="<?php echo esc_attr__( 'Copied to clipboard!', 'polanger-admin-menu-manager' ); ?>">
              <span class="dashicons dashicons-clipboard"></span>
              <?php esc_html_e( 'Copy All', 'polanger-admin-menu-manager' ); ?>
            </button>
            <button type="button" class="button button-primary pdt-close-recovery-modal">
              <?php esc_html_e( 'I have saved my keys', 'polanger-admin-menu-manager' ); ?>
            </button>
          </div>
        </div>
      </div>
    <?php endif; ?>
    
    <?php
    // Get available 2FA methods - addons can register additional methods
    $available_methods = apply_filters( 'pdt_2fa_available_methods', array( 'email' ) );
    $current_method = isset( $settings['two_factor_method'] ) ? $settings['two_factor_method'] : 'email';
    
    // Validate current method exists
    if ( ! in_array( $current_method, $available_methods, true ) ) {
      $current_method = 'email';
    }
    
    // Check if authenticator addon is active
    $authenticator_available = in_array( 'authenticator', $available_methods, true );
    ?>
    
    <form method="post" class="pdt-settings-form">
      <?php wp_nonce_field( 'pdt_security_settings' ); ?>
      
      <div class="pdt-settings-section">
        <h2><?php esc_html_e( 'Two-Factor Authentication (2FA)', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="description"><?php esc_html_e( 'Add an extra layer of security by requiring a second verification step during login.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div class="pdt-info-notice pdt-safety-notice">
          <span class="dashicons dashicons-yes-alt"></span>
          <div>
            <strong><?php esc_html_e( 'Built-in Safety Features', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'This 2FA system includes multiple safety layers to prevent lockouts: Recovery keys, trusted devices, Super Admin bypass, and graceful degradation.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>

        <div class="pdt-form-row">
          <label class="pdt-toggle-switch">
            <input type="checkbox" name="two_factor_enabled" value="1" <?php checked( $settings['two_factor_enabled'] ); ?> id="two_factor_enabled" />
            <span class="pdt-toggle-slider"></span>
            <span class="pdt-toggle-label"><?php esc_html_e( 'Enable Two-Factor Authentication', 'polanger-admin-menu-manager' ); ?></span>
          </label>
        </div>

        <div class="pdt-2fa-options<?php echo ! empty( $settings['two_factor_enabled'] ) ? ' is-visible' : ''; ?>" id="2fa-options-wrapper">
          
          <!-- 2FA Method Selector -->
          <div class="pdt-form-row pdt-2fa-method-selector">
            <label><?php esc_html_e( 'Verification Method', 'polanger-admin-menu-manager' ); ?></label>
            <p class="description"><?php esc_html_e( 'Choose how users will verify their identity after entering their password.', 'polanger-admin-menu-manager' ); ?></p>
            
            <div class="pdt-method-options">
              <!-- Email Option -->
              <label class="pdt-method-option <?php echo 'email' === $current_method ? 'is-selected' : ''; ?>">
                <input type="radio" name="two_factor_method" value="email" <?php checked( $current_method, 'email' ); ?> />
                <div class="pdt-method-card">
                  <div class="pdt-method-icon">
                    <span class="dashicons dashicons-email-alt"></span>
                  </div>
                  <div class="pdt-method-info">
                    <strong><?php esc_html_e( 'Email Verification', 'polanger-admin-menu-manager' ); ?></strong>
                    <span><?php esc_html_e( 'A 6-digit code will be sent to the user\'s email address.', 'polanger-admin-menu-manager' ); ?></span>
                  </div>
                  <span class="pdt-method-check dashicons dashicons-yes-alt"></span>
                </div>
              </label>
              
              <!-- Authenticator Option -->
              <label class="pdt-method-option <?php echo 'authenticator' === $current_method ? 'is-selected' : ''; ?> <?php echo ! $authenticator_available ? 'is-disabled' : ''; ?>">
                <input type="radio" name="two_factor_method" value="authenticator" <?php checked( $current_method, 'authenticator' ); ?> <?php echo ! $authenticator_available ? 'disabled' : ''; ?> />
                <div class="pdt-method-card">
                  <div class="pdt-method-icon">
                    <span class="dashicons dashicons-smartphone"></span>
                  </div>
                  <div class="pdt-method-info">
                    <strong><?php esc_html_e( 'Authenticator App', 'polanger-admin-menu-manager' ); ?></strong>
                    <span><?php esc_html_e( 'Use Google Authenticator or Microsoft Authenticator for TOTP codes.', 'polanger-admin-menu-manager' ); ?></span>
                    <?php if ( ! $authenticator_available ) : ?>
                      <em class="pdt-method-addon-notice"><?php esc_html_e( 'Requires Polanger Authenticator addon to be active.', 'polanger-admin-menu-manager' ); ?></em>
                    <?php endif; ?>
                  </div>
                  <span class="pdt-method-check dashicons dashicons-yes-alt"></span>
                </div>
              </label>
            </div>
          </div>
          
          <!-- Email Method: Email Test Section (shown when email is selected) -->
          <div class="pdt-2fa-method-settings pdt-method-email-settings" id="pdt-method-email-settings" style="<?php echo 'email' !== $current_method ? 'display:none;' : ''; ?>">
            <div class="pdt-form-row pdt-email-test-section">
              <label><?php esc_html_e( 'Email Delivery Test', 'polanger-admin-menu-manager' ); ?></label>
              <p class="description"><?php esc_html_e( 'Before enabling 2FA with email verification, verify that your site can send emails.', 'polanger-admin-menu-manager' ); ?></p>
              
              <div class="pdt-email-test-box <?php echo $email_verified ? 'verified' : ''; ?>">
                <?php if ( $email_verified ) : ?>
                  <span class="dashicons dashicons-yes-alt"></span>
                  <span><?php esc_html_e( 'Email delivery verified', 'polanger-admin-menu-manager' ); ?></span>
                <?php else : ?>
                  <span class="dashicons dashicons-warning"></span>
                  <span><?php esc_html_e( 'Email delivery not verified', 'polanger-admin-menu-manager' ); ?></span>
                <?php endif; ?>
                <button type="submit" name="pdt_test_email" class="button button-secondary">
                  <?php esc_html_e( 'Send Test Email', 'polanger-admin-menu-manager' ); ?>
                </button>
              </div>
              <?php if ( ! $email_verified ) : ?>
                <p class="description pdt-email-verify-warning"><?php esc_html_e( 'Please verify email delivery before saving settings with email verification method.', 'polanger-admin-menu-manager' ); ?></p>
              <?php endif; ?>
            </div>
          </div>
          
          <!-- Authenticator Method: Placeholder (actual setup rendered outside main form) -->
          <div class="pdt-2fa-method-settings pdt-method-authenticator-settings" id="pdt-method-authenticator-settings" style="<?php echo 'authenticator' !== $current_method ? 'display:none;' : ''; ?>">
            <div id="pdt-authenticator-placeholder"></div>
          </div>
          <div class="pdt-form-row">
            <label class="pdt-toggle-switch">
              <input type="checkbox" name="two_factor_include_super_admin" value="1" id="two_factor_include_super_admin" <?php checked( ! empty( $settings['two_factor_include_super_admin'] ) ); ?> />
              <span class="pdt-toggle-slider"></span>
              <span class="pdt-toggle-label"><?php esc_html_e( 'Also require 2FA for Super Admin', 'polanger-admin-menu-manager' ); ?></span>
            </label>
            <p class="description"><?php esc_html_e( 'By default, Super Admin is exempt to prevent lockout. Enable this if you also want Super Admin accounts to pass 2FA.', 'polanger-admin-menu-manager' ); ?></p>
            <div id="pdt-super-admin-2fa-warning" class="pdt-warning-notice pdt-super-admin-2fa-warning<?php echo ! empty( $settings['two_factor_include_super_admin'] ) ? ' is-visible' : ''; ?>">
              <span class="dashicons dashicons-warning"></span>
              <div>
                <p><strong><?php esc_html_e( 'Warning: If 2FA is misconfigured or email delivery fails, you may lose access to your site.', 'polanger-admin-menu-manager' ); ?></strong></p>
                <p><strong><?php esc_html_e( 'Before enabling:', 'polanger-admin-menu-manager' ); ?></strong></p>
                <ul>
                  <li><?php esc_html_e( 'Verify email delivery using the test email feature', 'polanger-admin-menu-manager' ); ?></li>
                  <li><?php esc_html_e( 'Generate and securely store recovery keys', 'polanger-admin-menu-manager' ); ?></li>
                  <li><?php esc_html_e( 'Ensure at least one administrator can receive emails', 'polanger-admin-menu-manager' ); ?></li>
                </ul>
                <p><em><?php esc_html_e( 'If you are not sure what this setting does, do not enable it.', 'polanger-admin-menu-manager' ); ?></em></p>
              </div>
            </div>
          </div>

          <div class="pdt-form-row">
            <label><?php esc_html_e( 'Required for Roles', 'polanger-admin-menu-manager' ); ?></label>
            <p class="description"><?php esc_html_e( 'Select which user roles must use 2FA when logging in.', 'polanger-admin-menu-manager' ); ?></p>
            
            <div class="pdt-role-checkboxes">
              <?php foreach ( $roles as $role_slug => $role_name ) : ?>
                <label class="pdt-role-checkbox">
                  <input type="checkbox" name="two_factor_roles[]" value="<?php echo esc_attr( $role_slug ); ?>"
                    <?php checked( in_array( $role_slug, $settings['two_factor_roles'], true ) ); ?> />
                  <?php echo esc_html( $role_name ); ?>
                </label>
              <?php endforeach; ?>
            </div>
          </div>
          
          <!-- 2FA Coverage Summary -->
          <?php
          $coverage_stats = $this->get_2fa_coverage_stats( $settings['two_factor_roles'] );
          ?>
          <div class="pdt-2fa-coverage-box">
            <div class="pdt-coverage-header">
              <span class="dashicons dashicons-chart-bar"></span>
              <strong><?php esc_html_e( '2FA Coverage', 'polanger-admin-menu-manager' ); ?></strong>
            </div>
            <div class="pdt-coverage-stats">
              <?php if ( $coverage_stats['protected'] > 0 ) : ?>
                <div class="pdt-coverage-item protected">
                  <span class="dashicons dashicons-yes-alt"></span>
                  <span>
                    <?php
                    /* translators: 1: Number of protected users, 2: Total users in selected roles. */
                    printf( esc_html__( '%1$d / %2$d users protected', 'polanger-admin-menu-manager' ), absint( $coverage_stats['protected'] ), absint( $coverage_stats['total'] ) );
                    ?>
                  </span>
                </div>
              <?php endif; ?>
              <?php if ( $coverage_stats['excluded'] > 0 ) : ?>
                <div class="pdt-coverage-item excluded">
                  <span class="dashicons dashicons-info"></span>
                  <span>
                    <?php
                    /* translators: %d: Number of excluded users because of Super Admin bypass. */
                    printf( esc_html__( '%d excluded (Super Admin bypass)', 'polanger-admin-menu-manager' ), absint( $coverage_stats['excluded'] ) );
                    ?>
                  </span>
                </div>
              <?php endif; ?>
              <?php if ( $coverage_stats['protected'] === 0 && $coverage_stats['total'] === 0 ) : ?>
                <div class="pdt-coverage-item none">
                  <span class="dashicons dashicons-minus"></span>
                  <span><?php esc_html_e( 'No roles selected', 'polanger-admin-menu-manager' ); ?></span>
                </div>
              <?php endif; ?>
            </div>
          </div>

          <div class="pdt-form-row">
            <label for="two_factor_code_expiry"><?php esc_html_e( 'Code Expiry Time (minutes)', 'polanger-admin-menu-manager' ); ?></label>
            <select name="two_factor_code_expiry" id="two_factor_code_expiry">
              <option value="5" <?php selected( $settings['two_factor_code_expiry'], 5 ); ?>>5 <?php esc_html_e( 'minutes', 'polanger-admin-menu-manager' ); ?></option>
              <option value="10" <?php selected( $settings['two_factor_code_expiry'], 10 ); ?>>10 <?php esc_html_e( 'minutes', 'polanger-admin-menu-manager' ); ?></option>
              <option value="15" <?php selected( $settings['two_factor_code_expiry'], 15 ); ?>>15 <?php esc_html_e( 'minutes', 'polanger-admin-menu-manager' ); ?></option>
            </select>
          </div>

          <div class="pdt-form-row">
            <label for="two_factor_max_attempts"><?php esc_html_e( 'Failed Attempt Limit', 'polanger-admin-menu-manager' ); ?></label>
            <p class="description"><?php esc_html_e( 'Set how many invalid verification or recovery key attempts are allowed before temporary lockout.', 'polanger-admin-menu-manager' ); ?></p>
            <select name="two_factor_max_attempts" id="two_factor_max_attempts">
              <option value="3" <?php selected( $settings['two_factor_max_attempts'], 3 ); ?>>3 <?php esc_html_e( 'attempts', 'polanger-admin-menu-manager' ); ?></option>
              <option value="5" <?php selected( $settings['two_factor_max_attempts'], 5 ); ?>>5 <?php esc_html_e( 'attempts', 'polanger-admin-menu-manager' ); ?></option>
            </select>
          </div>

          <div class="pdt-form-row">
            <label for="two_factor_lockout_minutes"><?php esc_html_e( 'Lockout Duration', 'polanger-admin-menu-manager' ); ?></label>
            <p class="description"><?php esc_html_e( 'Choose how long login is blocked after reaching the failed attempt limit.', 'polanger-admin-menu-manager' ); ?></p>
            <select name="two_factor_lockout_minutes" id="two_factor_lockout_minutes">
              <option value="15" <?php selected( $settings['two_factor_lockout_minutes'], 15 ); ?>>15 <?php esc_html_e( 'minutes', 'polanger-admin-menu-manager' ); ?></option>
              <option value="30" <?php selected( $settings['two_factor_lockout_minutes'], 30 ); ?>>30 <?php esc_html_e( 'minutes', 'polanger-admin-menu-manager' ); ?></option>
              <option value="60" <?php selected( $settings['two_factor_lockout_minutes'], 60 ); ?>>60 <?php esc_html_e( 'minutes', 'polanger-admin-menu-manager' ); ?></option>
              <option value="1440" <?php selected( $settings['two_factor_lockout_minutes'], 1440 ); ?>>24 <?php esc_html_e( 'hours', 'polanger-admin-menu-manager' ); ?></option>
            </select>
          </div>
          
          <!-- Recovery Keys Section -->
          <div class="pdt-form-row pdt-recovery-section">
            <label><?php esc_html_e( 'Recovery Keys', 'polanger-admin-menu-manager' ); ?></label>
            <p class="description"><?php esc_html_e( 'Recovery keys allow you to access your account if you lose access to your email.', 'polanger-admin-menu-manager' ); ?></p>
            
            <?php
            $keys_generated_time = get_user_meta( $current_user_id, 'pdt_2fa_recovery_keys_generated', true );
            ?>
            <div class="pdt-recovery-status">
              <?php if ( $recovery_keys_count > 0 ) : ?>
                <span class="dashicons dashicons-yes-alt"></span>
                <div class="pdt-recovery-info">
                  <span>
                    <?php
                    /* translators: %d: Remaining recovery key count. */
                    printf( esc_html__( '%d recovery keys remaining', 'polanger-admin-menu-manager' ), absint( $recovery_keys_count ) );
                    ?>
                  </span>
                  <?php if ( $keys_generated_time ) : ?>
                    <small class="pdt-recovery-date">
                      <?php
                      /* translators: %s: Date when recovery keys were generated. */
                      printf( esc_html__( 'Generated: %s', 'polanger-admin-menu-manager' ), esc_html( date_i18n( get_option( 'date_format' ), $keys_generated_time ) ) );
                      ?>
                    </small>
                  <?php endif; ?>
                </div>
              <?php else : ?>
                <span class="dashicons dashicons-warning"></span>
                <span><?php esc_html_e( 'No recovery keys available', 'polanger-admin-menu-manager' ); ?></span>
              <?php endif; ?>
              <button type="submit" name="pdt_regenerate_keys" class="button button-secondary">
                <?php esc_html_e( 'Generate New Keys', 'polanger-admin-menu-manager' ); ?>
              </button>
            </div>
          </div>
        </div>
      </div>

      <p class="submit">
        <button type="submit" name="pdt_security_save" class="button button-primary">
          <?php esc_html_e( 'Save Settings', 'polanger-admin-menu-manager' ); ?>
        </button>
      </p>
    </form>
    
    <!-- Authenticator Setup Section (outside main form to avoid nested forms) -->
    <div id="pdt-authenticator-setup-container" style="display:none;">
      <?php
      /**
       * Render authenticator setup UI when authenticator method is selected.
       * Rendered outside the main form to avoid nested form issues.
       *
       * @param int  $current_user_id Current user ID for personal setup.
       * @param bool $is_readonly     Whether read-only mode is active.
       */
      do_action( 'pdt_2fa_render_method_authenticator', $current_user_id, $is_readonly );
      ?>
    </div>
    
    <script>
    (function() {
      // Move authenticator setup into the placeholder to avoid nested forms
      var container = document.getElementById('pdt-authenticator-setup-container');
      var placeholder = document.getElementById('pdt-authenticator-placeholder');
      if (container && placeholder) {
        while (container.firstChild) {
          placeholder.appendChild(container.firstChild);
        }
        container.remove();
      }
    })();
    </script>
    <?php
  }

  /**
   * Send a safe 2FA test email and catch runtime mailer fatals.
   *
   * @param string $recipient_email Recipient email address.
   * @return array{success:bool,error:string}
   */
  private function send_2fa_test_email( $recipient_email ) {
    $subject = sprintf(
      /* translators: %s: Site name. */
      __( '[%s] 2FA Email Test', 'polanger-admin-menu-manager' ),
      get_bloginfo( 'name' )
    );
    $message = __( "This is a test email to verify your email delivery is working correctly.\n\nIf you received this email, your site can send 2FA verification codes.", 'polanger-admin-menu-manager' );

    try {
      $sent = wp_mail( $recipient_email, $subject, $message );
    } catch ( Throwable $exception ) {
      return array(
        'success' => false,
        'error'   => sprintf(
          /* translators: %s: Error message from mail transport. */
          __( 'Mailer runtime error: %s', 'polanger-admin-menu-manager' ),
          $exception->getMessage()
        ),
      );
    }

    return array(
      'success' => (bool) $sent,
      'error'   => '',
    );
  }

  /**
   * Render Activity Log tab
   */
  private function render_activity_log_tab() {
    $settings = $this->get_settings();
    $current_user_id = get_current_user_id();
    $is_super_admin = $this->is_protected_admin_user( $current_user_id );
    $is_readonly = $this->is_user_readonly();

    if ( isset( $_POST['pdt_activity_log_access_save'] ) && check_admin_referer( 'pdt_activity_log_access_settings' ) && ! $is_readonly ) {
      $log_visibility = isset( $_POST['log_visibility'] ) ? sanitize_text_field( wp_unslash( $_POST['log_visibility'] ) ) : 'all';
      if ( ! in_array( $log_visibility, array( 'all', 'super_admin' ), true ) ) {
        $log_visibility = 'all';
      }

      $email_alert_threshold = isset( $_POST['email_alert_threshold'] ) ? sanitize_text_field( wp_unslash( $_POST['email_alert_threshold'] ) ) : 'disabled';
      if ( ! in_array( $email_alert_threshold, array( 'disabled', 'critical', 'warning' ), true ) ) {
        $email_alert_threshold = 'disabled';
      }

      $new_settings = $settings;
      $new_settings['log_visibility'] = $log_visibility;
      $new_settings['email_alert_threshold'] = $email_alert_threshold;

      $this->update_settings( $new_settings );
      $settings = $new_settings;

      echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'polanger-admin-menu-manager' ) . '</p></div>';
    }
    
    // Check log visibility settings
    if ( $settings['log_visibility'] === 'super_admin' && ! $is_super_admin ) {
      ?>
      <div class="pdt-access-denied-notice">
        <span class="dashicons dashicons-lock"></span>
        <div>
          <strong><?php esc_html_e( 'Access Restricted', 'polanger-admin-menu-manager' ); ?></strong>
          <p><?php esc_html_e( 'Activity logs are only visible to Super Admin. Contact your administrator for access.', 'polanger-admin-menu-manager' ); ?></p>
        </div>
      </div>
      <?php
      return;
    }
    
    // Export functionality (Super Admin only)
    if ( $is_super_admin ) {
      ?>
      <div class="pdt-export-section">
        <h3><?php esc_html_e( 'Export Activity Logs', 'polanger-admin-menu-manager' ); ?></h3>
        <p class="description"><?php esc_html_e( 'Download activity logs for compliance and auditing purposes. Only metadata is exported (no sensitive content).', 'polanger-admin-menu-manager' ); ?></p>
        <p class="pdt-export-notice"><span class="dashicons dashicons-info-outline"></span> <?php esc_html_e( 'Exports may contain IP addresses if IP logging is enabled in Privacy settings.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div class="pdt-export-options">
          <div class="pdt-export-range">
            <label for="export_range"><?php esc_html_e( 'Date Range:', 'polanger-admin-menu-manager' ); ?></label>
            <select id="export_range" name="export_range" class="pdt-export-select"
                    data-csv-base="<?php echo esc_attr( wp_nonce_url( admin_url( 'admin.php?page=polanger-settings&tab=activity-log&export=csv' ), 'pdt_export_logs' ) ); ?>"
                    data-json-base="<?php echo esc_attr( wp_nonce_url( admin_url( 'admin.php?page=polanger-settings&tab=activity-log&export=json' ), 'pdt_export_logs' ) ); ?>">
              <option value="30"><?php esc_html_e( 'Last 30 days', 'polanger-admin-menu-manager' ); ?></option>
              <option value="90"><?php esc_html_e( 'Last 90 days', 'polanger-admin-menu-manager' ); ?></option>
              <option value="all"><?php esc_html_e( 'All time', 'polanger-admin-menu-manager' ); ?></option>
            </select>
          </div>
          
          <div class="pdt-export-buttons">
            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=polanger-settings&tab=activity-log&export=csv&range=30' ), 'pdt_export_logs' ) ); ?>" 
               class="button pdt-export-btn" id="export-csv-btn">
              <span class="dashicons dashicons-media-spreadsheet"></span>
              <?php esc_html_e( 'Export CSV', 'polanger-admin-menu-manager' ); ?>
            </a>
            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=polanger-settings&tab=activity-log&export=json&range=30' ), 'pdt_export_logs' ) ); ?>" 
               class="button pdt-export-btn" id="export-json-btn">
              <span class="dashicons dashicons-editor-code"></span>
              <?php esc_html_e( 'Export JSON', 'polanger-admin-menu-manager' ); ?>
            </a>
          </div>
        </div>
        
      </div>
      <hr class="pdt-section-divider" />
      <?php
    }
    
    global $pdt_activity_log;
    
    if ( $pdt_activity_log && method_exists( $pdt_activity_log, 'render_settings_page' ) ) {
      $pdt_activity_log->render_settings_page();
    } else {
      // Show 2FA security logs if activity log addon not available
      $this->render_security_logs();
    }

    ?>
    <form method="post" class="pdt-settings-form pdt-activity-log-footer-form">
      <?php wp_nonce_field( 'pdt_activity_log_access_settings' ); ?>

      <div class="pdt-settings-section pdt-activity-log-settings-footer">
        <h2><?php esc_html_e( 'Activity Log Settings', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="description"><?php esc_html_e( 'Configure who can view logs and which events should trigger email notifications.', 'polanger-admin-menu-manager' ); ?></p>

        <div class="pdt-activity-log-settings-layout">
          <div class="pdt-activity-log-setting-card">
            <label class="pdt-activity-log-setting-title"><?php esc_html_e( 'Log Visibility', 'polanger-admin-menu-manager' ); ?></label>
            <p class="description"><?php esc_html_e( 'Control who can view the activity logs.', 'polanger-admin-menu-manager' ); ?></p>

            <div class="pdt-radio-group">
              <label class="pdt-radio-option">
                <input type="radio" name="log_visibility" value="all" <?php checked( $settings['log_visibility'] ?? 'all', 'all' ); ?> />
                <span class="pdt-radio-label">
                  <strong><?php esc_html_e( 'All Allowed Users', 'polanger-admin-menu-manager' ); ?></strong>
                  <small><?php esc_html_e( 'Any user with plugin access can view logs', 'polanger-admin-menu-manager' ); ?></small>
                </span>
              </label>
              <label class="pdt-radio-option">
                <input type="radio" name="log_visibility" value="super_admin" <?php checked( $settings['log_visibility'] ?? 'all', 'super_admin' ); ?> />
                <span class="pdt-radio-label">
                  <strong><?php esc_html_e( 'Super Admin Only', 'polanger-admin-menu-manager' ); ?></strong>
                  <small><?php esc_html_e( 'Only Super Admin can view sensitive logs', 'polanger-admin-menu-manager' ); ?></small>
                </span>
              </label>
            </div>
          </div>

          <div class="pdt-activity-log-setting-card">
            <label class="pdt-activity-log-setting-title"><?php esc_html_e( 'Email Alert Threshold', 'polanger-admin-menu-manager' ); ?></label>
            <p class="description"><?php esc_html_e( 'Choose which events trigger email notifications.', 'polanger-admin-menu-manager' ); ?></p>

            <div class="pdt-radio-group">
              <label class="pdt-radio-option">
                <input type="radio" name="email_alert_threshold" value="disabled" <?php checked( $settings['email_alert_threshold'] ?? 'disabled', 'disabled' ); ?> />
                <span class="pdt-radio-label">
                  <strong><?php esc_html_e( 'Disabled', 'polanger-admin-menu-manager' ); ?></strong>
                  <small><?php esc_html_e( 'No email notifications will be sent', 'polanger-admin-menu-manager' ); ?></small>
                </span>
              </label>
              <label class="pdt-radio-option">
                <input type="radio" name="email_alert_threshold" value="critical" <?php checked( $settings['email_alert_threshold'] ?? 'disabled', 'critical' ); ?> />
                <span class="pdt-radio-label">
                  <strong><?php esc_html_e( 'Critical Only', 'polanger-admin-menu-manager' ); ?></strong>
                  <small><?php esc_html_e( 'Security breaches, failed logins, bypass events', 'polanger-admin-menu-manager' ); ?></small>
                </span>
              </label>
              <label class="pdt-radio-option">
                <input type="radio" name="email_alert_threshold" value="warning" <?php checked( $settings['email_alert_threshold'] ?? 'disabled', 'warning' ); ?> />
                <span class="pdt-radio-label">
                  <strong><?php esc_html_e( 'Critical + Warning', 'polanger-admin-menu-manager' ); ?></strong>
                  <small><?php esc_html_e( 'Includes recovery key usage, resend attempts', 'polanger-admin-menu-manager' ); ?></small>
                </span>
              </label>
            </div>
          </div>
        </div>

        <p class="submit">
          <button type="submit" name="pdt_activity_log_access_save" class="button button-primary">
            <?php esc_html_e( 'Save Settings', 'polanger-admin-menu-manager' ); ?>
          </button>
        </p>
      </div>
    </form>
    <?php
  }

  /**
   * Handle log export
   */
  public function handle_log_export() {
    if ( ! isset( $_GET['export'] ) || ! isset( $_GET['_wpnonce'] ) ) {
      return;
    }

    // Only process export requests from Settings > Activity Log tab.
    // phpcs:disable WordPress.Security.NonceVerification.Recommended
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    $tab  = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';
    // phpcs:enable WordPress.Security.NonceVerification.Recommended
    if ( 'polanger-settings' !== $page || 'activity-log' !== $tab ) {
      return;
    }
    
    if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'pdt_export_logs' ) ) {
      return;
    }
    
    $current_user_id = get_current_user_id();
    $is_super_admin = $this->is_protected_admin_user( $current_user_id );
    
    if ( ! $is_super_admin ) {
      return;
    }
    
    $format = sanitize_text_field( wp_unslash( $_GET['export'] ) );
    $range = isset( $_GET['range'] ) ? sanitize_text_field( wp_unslash( $_GET['range'] ) ) : '30';
    if ( ! in_array( $range, array( '30', '90', 'all' ), true ) ) {
      $range = '30';
    }
    
    // Get logs
    $logs = $this->get_exportable_logs( $range );
    
    if ( $format === 'csv' ) {
      $this->export_csv( $logs );
    } elseif ( $format === 'json' ) {
      $this->export_json( $logs );
    }
  }

  /**
   * Get exportable logs (metadata only)
   */
  private function get_exportable_logs( $range ) {
    $export_logs = array();
    global $pdt_activity_log;

    // Prefer real Activity Log data when addon is active.
    if ( $pdt_activity_log && method_exists( $pdt_activity_log, 'get_logs' ) ) {
      $query_args = array(
        'per_page' => 99999,
        'page'     => 1,
      );

      if ( 'all' !== $range ) {
        $days = absint( $range );
        $query_args['date_from'] = gmdate( 'Y-m-d', strtotime( '-' . $days . ' days' ) );
      }

      $result = $pdt_activity_log->get_logs( $query_args );
      $rows = isset( $result['logs'] ) && is_array( $result['logs'] ) ? $result['logs'] : array();

      foreach ( $rows as $row ) {
        $action = isset( $row->action ) ? sanitize_text_field( $row->action ) : '';
        $severity = method_exists( $pdt_activity_log, 'get_action_severity' ) ? $pdt_activity_log->get_action_severity( $action ) : 'info';
        $export_logs[] = array(
          'timestamp' => isset( $row->created_at ) ? sanitize_text_field( $row->created_at ) : '',
          'action'    => $action,
          'severity'  => sanitize_text_field( $severity ),
          'user_id'   => isset( $row->user_id ) ? absint( $row->user_id ) : 0,
          'ip'        => isset( $row->ip_address ) ? sanitize_text_field( $row->ip_address ) : '',
        );
      }

      return $export_logs;
    }

    // Fallback to local 2FA security logs option if addon is unavailable.
    $logs = get_option( 'pdt_2fa_security_logs', array() );
    if ( ! is_array( $logs ) ) {
      return $export_logs;
    }

    if ( 'all' !== $range ) {
      $days = absint( $range );
      $cutoff = strtotime( '-' . $days . ' days' );
      $logs = array_filter(
        $logs,
        function( $log ) use ( $cutoff ) {
          $log_time = isset( $log['timestamp'] ) ? strtotime( (string) $log['timestamp'] ) : false;
          return $log_time && $log_time >= $cutoff;
        }
      );
    }

    foreach ( $logs as $log ) {
      if ( ! is_array( $log ) ) {
        continue;
      }
      $metadata = isset( $log['metadata'] ) && is_array( $log['metadata'] ) ? $log['metadata'] : array();
      $export_logs[] = array(
        'timestamp' => isset( $log['timestamp'] ) ? sanitize_text_field( $log['timestamp'] ) : '',
        'action'    => isset( $log['action'] ) ? sanitize_text_field( $log['action'] ) : '',
        'severity'  => isset( $log['severity'] ) ? sanitize_text_field( $log['severity'] ) : 'info',
        'user_id'   => isset( $metadata['user_id'] ) ? absint( $metadata['user_id'] ) : 0,
        'ip'        => isset( $log['ip'] ) ? sanitize_text_field( $log['ip'] ) : '',
      );
    }
    
    return $export_logs;
  }

  /**
   * Export logs as CSV
   */
  private function export_csv( $logs ) {
    $filename = 'activity-logs-' . gmdate( 'Y-m-d' ) . '.csv';
    
    header( 'Content-Type: text/csv; charset=utf-8' );
    header( 'Content-Disposition: attachment; filename=' . $filename );
    header( 'Pragma: no-cache' );
    header( 'Expires: 0' );
    
    $output = fopen( 'php://output', 'w' );
    
    // Header row
    fputcsv(
      $output,
      array(
        __( 'Timestamp', 'polanger-admin-menu-manager' ),
        __( 'Action', 'polanger-admin-menu-manager' ),
        __( 'Severity', 'polanger-admin-menu-manager' ),
        __( 'User ID', 'polanger-admin-menu-manager' ),
        __( 'IP Address', 'polanger-admin-menu-manager' ),
      )
    );
    
    // Data rows
    foreach ( $logs as $log ) {
      fputcsv( $output, array(
        $log['timestamp'],
        $log['action'],
        $log['severity'],
        $log['user_id'],
        $log['ip'],
      ) );
    }
    
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Closing php://output stream after CSV response.
    fclose( $output );
    exit;
  }

  /**
   * Export logs as JSON
   */
  private function export_json( $logs ) {
    $filename = 'activity-logs-' . gmdate( 'Y-m-d' ) . '.json';
    
    header( 'Content-Type: application/json; charset=utf-8' );
    header( 'Content-Disposition: attachment; filename=' . $filename );
    header( 'Pragma: no-cache' );
    header( 'Expires: 0' );
    
    echo wp_json_encode( array(
      'exported_at' => current_time( 'mysql' ),
      'site'        => get_bloginfo( 'name' ),
      'total_logs'  => count( $logs ),
      'logs'        => $logs,
    ), JSON_PRETTY_PRINT );
    
    exit;
  }

  /**
   * Render security logs (fallback if activity log addon not available)
   */
  private function render_security_logs() {
    $logs = get_option( 'pdt_2fa_security_logs', array() );
    $logs = array_reverse( $logs ); // Most recent first
    
    ?>
    <div class="pdt-security-logs">
      <h3><?php esc_html_e( '2FA Security Events', 'polanger-admin-menu-manager' ); ?></h3>
      
      <?php if ( empty( $logs ) ) : ?>
        <p class="pdt-no-logs"><?php esc_html_e( 'No security events recorded yet.', 'polanger-admin-menu-manager' ); ?></p>
      <?php else : ?>
        <table class="pdt-logs-table">
          <thead>
            <tr>
              <th><?php esc_html_e( 'Time', 'polanger-admin-menu-manager' ); ?></th>
              <th><?php esc_html_e( 'Event', 'polanger-admin-menu-manager' ); ?></th>
              <th><?php esc_html_e( 'Severity', 'polanger-admin-menu-manager' ); ?></th>
              <th><?php esc_html_e( 'IP', 'polanger-admin-menu-manager' ); ?></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ( array_slice( $logs, 0, 50 ) as $log ) : ?>
              <tr class="severity-<?php echo esc_attr( $log['severity'] ); ?>">
                <td><?php echo esc_html( $log['timestamp'] ); ?></td>
                <td><?php echo esc_html( $this->format_action_name( $log['action'] ) ); ?></td>
                <td><span class="pdt-severity-badge <?php echo esc_attr( $log['severity'] ); ?>"><?php echo esc_html( ucfirst( $log['severity'] ) ); ?></span></td>
                <td><?php echo esc_html( $log['ip'] ?? '-' ); ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
    <?php
  }

  /**
   * Format action name for display
   */
  private function format_action_name( $action ) {
    $actions = array(
      '2fa_bypass_active'        => __( '2FA Bypass Active (wp-config)', 'polanger-admin-menu-manager' ),
      '2fa_email_failed'         => __( '2FA Email Failed - Login Allowed', 'polanger-admin-menu-manager' ),
      '2fa_recovery_key_used'    => __( 'Recovery Key Used', 'polanger-admin-menu-manager' ),
      '2fa_code_resent'          => __( 'Verification Code Resent', 'polanger-admin-menu-manager' ),
      '2fa_login_success'        => __( '2FA Login Successful', 'polanger-admin-menu-manager' ),
      '2fa_recovery_keys_generated' => __( 'Recovery Keys Generated', 'polanger-admin-menu-manager' ),
    );
    
    return isset( $actions[ $action ] ) ? $actions[ $action ] : $action;
  }

  /**
   * Check if 2FA is enabled for a user role
   */
  public function is_2fa_required_for_user( $user ) {
    $settings = $this->get_settings();
    
    if ( empty( $settings['two_factor_enabled'] ) ) {
      return false;
    }

    $user_roles = $user->roles;
    $required_roles = $settings['two_factor_roles'];

    return ! empty( array_intersect( $user_roles, $required_roles ) );
  }

  /**
   * Get 2FA code expiry time in minutes
   */
  public function get_2fa_code_expiry() {
    $settings = $this->get_settings();
    return absint( $settings['two_factor_code_expiry'] );
  }

  /**
   * Get maximum allowed 2FA failed attempts.
   *
   * @return int
   */
  public function get_2fa_max_attempts() {
    $settings = $this->get_settings();
    $max_attempts = isset( $settings['two_factor_max_attempts'] ) ? absint( $settings['two_factor_max_attempts'] ) : 3;
    return in_array( $max_attempts, array( 3, 5 ), true ) ? $max_attempts : 3;
  }

  /**
   * Get 2FA lockout duration in minutes.
   *
   * @return int
   */
  public function get_2fa_lockout_minutes() {
    $settings = $this->get_settings();
    $lockout_minutes = isset( $settings['two_factor_lockout_minutes'] ) ? absint( $settings['two_factor_lockout_minutes'] ) : 30;
    return in_array( $lockout_minutes, array( 15, 30, 60, 1440 ), true ) ? $lockout_minutes : 30;
  }

  /**
   * Get configured 2FA verification method.
   *
   * @return string 'email' or 'authenticator'
   */
  public function get_2fa_method() {
    $settings = $this->get_settings();
    $method = isset( $settings['two_factor_method'] ) ? $settings['two_factor_method'] : 'email';
    return in_array( $method, array( 'email', 'authenticator' ), true ) ? $method : 'email';
  }

  /**
   * Get user's access level
   * 
   * @param int $user_id User ID
   * @return string 'full', 'readonly' or 'hidden'
   */
  public function get_user_access_level( $user_id = null ) {
    if ( null === $user_id ) {
      $user_id = get_current_user_id();
    }
    
    // Super Admin always has full access
    if ( $this->is_protected_admin_user( $user_id ) ) {
      return 'full';
    }
    
    $settings = $this->get_settings();

    // Hidden level must always be respected (even if global restriction toggle is off).
    if ( isset( $settings['user_access_levels'][ $user_id ] ) && $settings['user_access_levels'][ $user_id ] === 'hidden' ) {
      return 'hidden';
    }
    
    // If access restriction is not enabled, everyone has full access
    if ( empty( $settings['restrict_access'] ) ) {
      return 'full';
    }
    
    // Check user's access level
    if ( isset( $settings['user_access_levels'][ $user_id ] ) ) {
      return $settings['user_access_levels'][ $user_id ];
    }
    
    // Default to full access
    return 'full';
  }

  /**
   * Check if current user has read-only access
   * 
   * @param int $user_id User ID (optional, defaults to current user)
   * @return bool True if user has read-only access
   */
  public function is_user_readonly( $user_id = null ) {
    return $this->get_user_access_level( $user_id ) === 'readonly';
  }

  /**
   * Check if current user can modify settings
   * 
   * @return bool True if user can modify settings
   */
  public function current_user_can_modify() {
    return ! $this->is_user_readonly();
  }

  /**
   * Render Miscellaneous tab
   */
  private function render_miscellaneous_tab() {
    $settings = $this->get_settings();
    $is_readonly = $this->is_user_readonly();
    
    // Handle form submission
    if ( isset( $_POST['pdt_misc_save'] ) && check_admin_referer( 'pdt_misc_settings' ) && ! $is_readonly ) {
      $new_settings = $settings;
      $new_settings['admin_footer_text']    = isset( $_POST['admin_footer_text'] ) ? wp_kses_post( wp_unslash( $_POST['admin_footer_text'] ) ) : '';
      $new_settings['admin_footer_version'] = isset( $_POST['admin_footer_version'] );
      
      $this->update_settings( $new_settings );

      wp_safe_redirect(
        add_query_arg(
          array(
            'page'              => 'polanger-settings',
            'tab'               => 'miscellaneous',
            'pdt_misc_settings' => 'saved',
          ),
          admin_url( 'admin.php' )
        )
      );
      exit;
    }
    
    ?>
    <form method="post" class="pdt-settings-form">
      <?php wp_nonce_field( 'pdt_misc_settings' ); ?>
      
      <div class="pdt-settings-section">
        <?php
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( isset( $_GET['pdt_misc_settings'] ) && 'saved' === sanitize_text_field( wp_unslash( $_GET['pdt_misc_settings'] ) ) ) :
        ?>
          <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e( 'Settings saved.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        <?php endif; ?>

        <h2><?php esc_html_e( 'Admin Footer', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="description"><?php esc_html_e( 'Customize or hide the default WordPress footer text in the admin area.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div class="pdt-form-row">
          <label for="admin_footer_text"><?php esc_html_e( 'Custom Footer Text', 'polanger-admin-menu-manager' ); ?></label>
          <p class="description"><?php esc_html_e( 'Replace the default "Thank you for creating with WordPress" text. Leave empty to hide it completely.', 'polanger-admin-menu-manager' ); ?></p>
          <textarea name="admin_footer_text"
                    id="admin_footer_text"
                    class="large-text"
                    rows="3"
                    placeholder="<?php esc_attr_e( 'e.g., Powered by Your Agency Name', 'polanger-admin-menu-manager' ); ?>"><?php echo esc_textarea( $settings['admin_footer_text'] ?? '' ); ?></textarea>
          <p class="description"><small><?php esc_html_e( 'Supports safe HTML (links and basic formatting).', 'polanger-admin-menu-manager' ); ?></small></p>
        </div>
        
        <div class="pdt-form-row">
          <label class="pdt-toggle-switch">
            <input type="checkbox" name="admin_footer_version" value="1" <?php checked( $settings['admin_footer_version'] ?? true ); ?> />
            <span class="pdt-toggle-slider"></span>
            <span class="pdt-toggle-label"><?php esc_html_e( 'Show WordPress Version', 'polanger-admin-menu-manager' ); ?></span>
          </label>
          <p class="description"><?php esc_html_e( 'Display the WordPress version number in the admin footer (e.g., "Version 6.9").', 'polanger-admin-menu-manager' ); ?></p>
        </div>
        
        <div class="pdt-info-notice">
          <span class="dashicons dashicons-visibility"></span>
          <div>
            <strong><?php esc_html_e( 'Preview', 'polanger-admin-menu-manager' ); ?></strong>
            <p id="pdt-footer-preview" class="pdt-footer-preview">
              <?php 
              $preview_text = ! empty( $settings['admin_footer_text'] ) ? $settings['admin_footer_text'] : '<em>' . esc_html__( '(Footer text hidden)', 'polanger-admin-menu-manager' ) . '</em>';
              $preview_version = ! empty( $settings['admin_footer_version'] ) ? ' &mdash; ' . sprintf(
                /* translators: %s: Current WordPress version. */
                __( 'Version %s', 'polanger-admin-menu-manager' ),
                get_bloginfo( 'version' )
              ) : '';
              echo wp_kses_post( $preview_text . $preview_version );
              ?>
            </p>
          </div>
        </div>
      </div>

      <p class="submit">
        <button type="submit" name="pdt_misc_save" class="button button-primary">
          <?php esc_html_e( 'Save Settings', 'polanger-admin-menu-manager' ); ?>
        </button>
      </p>
    </form>

    <?php
  }

  /**
   * Enqueue settings page scripts.
   *
   * @param string $hook Current admin page hook.
   * @return void
   */
  public function enqueue_settings_scripts( $hook ) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $current_page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    $allowed_hooks = array(
      'toplevel_page_polanger-settings',
      'polanger-dashboard_page_polanger-settings',
    );

    if ( ! in_array( $hook, $allowed_hooks, true ) && 'polanger-settings' !== $current_page ) {
      return;
    }

    wp_enqueue_script(
      'pdt-settings-page',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/settings-page.js',
      array( 'jquery' ),
      PDT_VERSION,
      true
    );

    wp_localize_script(
      'pdt-settings-page',
      'pdtSettingsPageI18n',
      array(
        'versionLabel'     => sprintf(
          /* translators: %s: Current WordPress version. */
          __( 'Version %s', 'polanger-admin-menu-manager' ),
          get_bloginfo( 'version' )
        ),
        'footerHiddenLabel'=> __( '(Footer text hidden)', 'polanger-admin-menu-manager' ),
      )
    );
  }

  /**
   * Apply admin footer customizations
   */
  public function apply_admin_footer_customizations() {
    $settings = $this->get_settings();
    
    // Custom footer text
    add_filter( 'admin_footer_text', function( $text ) use ( $settings ) {
      if ( isset( $settings['admin_footer_text'] ) ) {
        if ( empty( $settings['admin_footer_text'] ) ) {
          return ''; // Hide footer text
        }
        return wp_kses_post( $settings['admin_footer_text'] );
      }
      return $text;
    }, 999 );
    
    // WordPress version
    add_filter( 'update_footer', function( $text ) use ( $settings ) {
      if ( isset( $settings['admin_footer_version'] ) && ! $settings['admin_footer_version'] ) {
        return ''; // Hide version
      }
      return $text;
    }, 999 );
  }
}
