<?php
/**
* Plugin Name:        Polanger Admin Suite
* Description:        All-in-one toolkit to customize WordPress admin menus, admin bar, login page, and dashboard experience.
 * Version:            1.5.8
* Requires at least:  4.7
* Requires PHP:       7.0
* Author:             Polanger
* Author URI:         https://polanger.com
* License:            GPLv3 or later
* License URI:        https://www.gnu.org/licenses/gpl-3.0.html
* Text Domain:        polanger-admin-menu-manager
* Domain Path:        /languages
*/

/*
Polanger Admin Suite is a software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.

Polanger Admin Suite is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Polanger Admin Suite. If not, see https://www.gnu.org/licenses/gpl-3.0.html.
*/

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

// Define plugin constants
define( 'PDT_VERSION', '1.5.8' );
define( 'PDT_PLUGIN_FILE', __FILE__ );
define( 'PDT_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );

/**
 * Load suite translations from the shared plugin languages directory.
 *
 * @return void
 */
function pdt_load_textdomains() {
  $language_path = dirname( plugin_basename( PDT_PLUGIN_FILE ) ) . '/languages';
  load_plugin_textdomain( 'polanger-admin-menu-manager', false, $language_path );
}
add_action( 'init', 'pdt_load_textdomains' );

// Include modules
require_once PDT_PLUGIN_DIR . 'includes/class-admin-bar.php';
require_once PDT_PLUGIN_DIR . 'includes/class-login-page.php';
require_once PDT_PLUGIN_DIR . 'includes/class-content-visibility.php';
require_once PDT_PLUGIN_DIR . 'includes/class-settings-page.php';
require_once PDT_PLUGIN_DIR . 'includes/class-two-factor-auth.php';
require_once PDT_PLUGIN_DIR . 'includes/class-addons-page.php';
require_once PDT_PLUGIN_DIR . 'includes/class-help-page.php';
require_once PDT_PLUGIN_DIR . 'includes/class-extension-loader.php';
require_once PDT_PLUGIN_DIR . 'includes/class-optional-addon-loader.php';

// Include core addons
require_once PDT_PLUGIN_DIR . 'addons/admin-activity-log/class-admin-activity-log.php';
require_once PDT_PLUGIN_DIR . 'addons/dashboard-widgets/class-dashboard-widgets.php';

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Legacy public API/hook names kept for backward compatibility.

/**
 * Get active addon slugs.
 *
 * @return array
 */
function pdt_get_active_addons() {
  $active_addons = get_option( 'pdt_active_addons', null );
  $defaults = array( 'admin-activity-log', 'dashboard-widgets' );

  if ( null === $active_addons ) {
    update_option( 'pdt_active_addons', $defaults );
    $active_addons = $defaults;
  } elseif ( ! is_array( $active_addons ) ) {
    $active_addons = $defaults;
  } else {
    $active_addons = array_values( array_unique( array_map( 'sanitize_key', $active_addons ) ) );
  }

  if ( is_multisite() ) {
    $network_active_addons = get_site_option( 'pdt_network_active_addons', array() );
    if ( is_array( $network_active_addons ) ) {
      $active_addons = array_values( array_unique( array_merge( $active_addons, array_map( 'sanitize_key', $network_active_addons ) ) ) );
    }
  }

  return apply_filters( 'pdt_active_addons', $active_addons );
}

/**
 * Check if an addon is active.
 *
 * @param string $addon_slug Addon slug.
 * @return bool
 */
function pdt_is_addon_active( $addon_slug ) {
  $addon_slug = sanitize_key( $addon_slug );

  return in_array( $addon_slug, pdt_get_active_addons(), true );
}

/**
 * Return the former standalone plugin basenames that are now internal addons.
 *
 * @return array<string,string>
 */
function pdt_get_internalized_addon_plugin_map() {
  return array(
    'polanger-shield/polanger-shield.php'                  => 'polanger-shield',
    'polanger-maintenance-center/polanger-maintenance-center.php' => 'maintenance-center',
    'woocommerce-security/polanger-woocommerce-security.php'      => 'woocommerce-security',
  );
}

/**
 * Migrate former standalone addons into the internal addon registry.
 *
 * @return void
 */
function pdt_migrate_internalized_addon_state() {
  $migration_flag = 'pdt_internalized_addons_migrated_155';

  if ( get_option( $migration_flag ) ) {
    return;
  }

  $plugin_map = pdt_get_internalized_addon_plugin_map();

  if ( empty( $plugin_map ) ) {
    update_option( $migration_flag, current_time( 'mysql' ), false );
    return;
  }

  $default_active_addons = array( 'admin-activity-log', 'dashboard-widgets' );
  $active_addons         = get_option( 'pdt_active_addons', $default_active_addons );
  $active_addons         = is_array( $active_addons ) ? array_values( array_unique( array_map( 'sanitize_key', $active_addons ) ) ) : $default_active_addons;
  $active_plugins        = get_option( 'active_plugins', array() );
  $active_plugins        = is_array( $active_plugins ) ? array_values( array_unique( array_map( 'strval', $active_plugins ) ) ) : array();

  $network_active_addons = is_multisite() ? get_site_option( 'pdt_network_active_addons', array() ) : array();
  $network_active_addons = is_array( $network_active_addons ) ? array_values( array_unique( array_map( 'sanitize_key', $network_active_addons ) ) ) : array();
  $network_plugins       = is_multisite() ? get_site_option( 'active_sitewide_plugins', array() ) : array();
  $network_plugins       = is_array( $network_plugins ) ? $network_plugins : array();

  foreach ( $plugin_map as $plugin_file => $addon_slug ) {
    $was_site_active    = in_array( $plugin_file, $active_plugins, true );
    $was_network_active = is_multisite() && isset( $network_plugins[ $plugin_file ] );

    if ( $was_site_active || $was_network_active ) {
      $active_addons[] = $addon_slug;
    }

    if ( $was_network_active ) {
      $network_active_addons[] = $addon_slug;
      unset( $network_plugins[ $plugin_file ] );
    }

    if ( $was_site_active ) {
      $active_plugins = array_values( array_diff( $active_plugins, array( $plugin_file ) ) );
    }
  }

  update_option( 'pdt_active_addons', array_values( array_unique( array_map( 'sanitize_key', $active_addons ) ) ) );
  update_option( 'active_plugins', array_values( array_unique( array_map( 'strval', $active_plugins ) ) ) );

  if ( is_multisite() ) {
    update_site_option( 'pdt_network_active_addons', array_values( array_unique( array_map( 'sanitize_key', $network_active_addons ) ) ) );
    update_site_option( 'active_sitewide_plugins', $network_plugins );
  }

  delete_option( 'psh_license_data' );
  delete_option( 'psh_license_unlicensed_started' );
  delete_transient( 'psh_license_unlicensed_report_sent' );
  delete_option( 'pwcs_license_data' );
  delete_option( 'pwcs_license_unlicensed_started' );
  delete_transient( 'pwcs_license_unlicensed_report_sent' );

  update_option( $migration_flag, current_time( 'mysql' ), false );
}

pdt_migrate_internalized_addon_state();

/**
 * Return optional built-in addons that may be safely auto-disabled.
 *
 * These are suite-managed modules that appear as optional on the Addons page.
 * Core-always-on modules and true third-party plugins are intentionally
 * excluded from this list.
 *
 * @return array<string,array<string,mixed>>
 */
function pdt_get_optional_internal_addon_definitions() {
  return array(
    'custom-admin-menu' => array(
      'title' => 'Custom Admin Menu Builder',
      'file'  => PDT_PLUGIN_DIR . 'addons/custom-admin-menu/class-custom-admin-menu.php',
      'class' => 'PDT_Custom_Admin_Menu',
    ),
    'comment-security' => array(
      'title' => 'Comment Security Layer',
      'file'  => PDT_PLUGIN_DIR . 'addons/comment-security/class-comment-security.php',
      'class' => 'PDT_Comment_Security',
    ),
    'design-system' => array(
      'title' => 'Design System',
      'file'  => PDT_PLUGIN_DIR . 'addons/design-system/class-design-system.php',
      'class' => 'PDT_Design_System',
    ),
    'multisite-control' => array(
      'title' => 'Multisite Control',
      'file'  => PDT_PLUGIN_DIR . 'addons/multisite-control/class-multisite-control.php',
      'class' => 'PDT_Multisite_Control',
    ),
    'polanger-authenticator' => array(
      'title' => 'Polanger Authenticator',
      'file'  => PDT_PLUGIN_DIR . 'addons/polanger-authenticator/class-polanger-authenticator.php',
      'class' => 'PDT_Polanger_Authenticator',
    ),
    'polanger-shield' => array(
      'title' => 'Polanger Shield',
      'file'  => PDT_PLUGIN_DIR . 'addons/polanger-shield/class-polanger-shield-addon.php',
      'class' => 'PDT_Polanger_Shield_Addon',
    ),
    'recaptcha' => array(
      'title' => 'reCAPTCHA',
      'file'  => PDT_PLUGIN_DIR . 'addons/recaptcha/class-recaptcha.php',
      'class' => 'PDT_Recaptcha',
    ),
    'woocommerce-security' => array(
      'title' => 'WooCommerce Security',
      'file'  => PDT_PLUGIN_DIR . 'addons/woocommerce-security/class-woocommerce-security-addon.php',
      'class' => 'PDT_WooCommerce_Security_Addon',
    ),
    'maintenance-center' => array(
      'title' => 'Maintenance Center',
      'file'  => PDT_PLUGIN_DIR . 'addons/maintenance-center/class-maintenance-center-addon.php',
      'class' => 'PDT_Maintenance_Center_Addon',
    ),
    'firewall' => array(
      'title' => 'Polanger Firewall',
      'file'  => PDT_PLUGIN_DIR . 'addons/firewall/class-firewall-addon.php',
      'class' => 'PDT_Firewall_Addon',
    ),
  );
}

/**
 * Boot one optional built-in addon through the safe loader.
 *
 * @param string $addon_slug Optional addon slug.
 * @return object|null
 */
function pdt_boot_optional_internal_addon( $addon_slug ) {
  global $pdt_optional_addon_loader;

  if ( ! ( $pdt_optional_addon_loader instanceof PDT_Optional_Addon_Loader ) ) {
    return null;
  }

  return $pdt_optional_addon_loader->boot_addon( $addon_slug );
}
/**
 * Build the URL used for 2FA challenge screens and actions.
 *
 * Defaults to `wp-login.php` and can be overridden by addons that provide
 * a dedicated frontend challenge experience.
 *
 * @param array $pending_context Pending 2FA context.
 * @param array $args            Query arguments to append.
 * @return string
 */
function pdt_get_2fa_challenge_url( $pending_context = array(), $args = array() ) {
  $url = wp_login_url();

  if ( ! empty( $args ) ) {
    $url = add_query_arg( $args, $url );
  }

  return apply_filters( 'pdt_2fa_challenge_url', $url, $pending_context, $args );
}

/**
 * Build the URL used for "back to login" links during 2FA flows.
 *
 * @param array $pending_context Pending 2FA context.
 * @param array $args            Optional query arguments to append.
 * @return string
 */
function pdt_get_2fa_back_to_login_url( $pending_context = array(), $args = array() ) {
  $url = wp_login_url();

  if ( ! empty( $args ) ) {
    $url = add_query_arg( $args, $url );
  }

  return apply_filters( 'pdt_2fa_back_to_login_url', $url, $pending_context, $args );
}

/**
 * Resolve the post-verification redirect URL for a completed 2FA flow.
 *
 * @param array        $pending_context Pending 2FA context.
 * @param WP_User|null $user            Verified user object when available.
 * @return string
 */
function pdt_get_2fa_success_redirect_url( $pending_context = array(), $user = null ) {
  return apply_filters( 'pdt_2fa_success_redirect_url', admin_url(), $pending_context, $user );
}

/**
 * Resolve the central Polanger access level for a user.
 *
 * Exposes the Settings > Access Control decision ("who can use this plugin")
 * as a stable, addon-facing API so third-party addons do not need to reach
 * into core globals or hard-code capabilities.
 *
 * @param int|null $user_id Optional user ID. Defaults to the current user.
 * @return string One of 'full', 'readonly', 'hidden'.
 */
function pdt_get_user_access_level( $user_id = null ) {
  global $pdt_settings_page;

  $level = 'full';
  if ( $pdt_settings_page instanceof PDT_Settings_Page ) {
    $level = $pdt_settings_page->get_user_access_level( $user_id );
  }

  /**
   * Filter the resolved Polanger access level for a user.
   *
   * @param string   $level   Access level: 'full', 'readonly' or 'hidden'.
   * @param int|null $user_id User ID being evaluated (null for current user).
   */
  return apply_filters( 'polanger_user_access_level', $level, $user_id );
}

/**
 * Whether a user may manage Polanger features.
 *
 * Addons should gate management UI and privileged actions through this helper
 * so the central Settings > Access Control list remains the single source of
 * truth for who can operate the suite.
 *
 * @param int|null $user_id Optional user ID. Defaults to the current user.
 * @return bool
 */
function pdt_current_user_can_manage( $user_id = null ) {
  if ( null === $user_id ) {
    $user_id = get_current_user_id();
  }

  $user_id = absint( $user_id );

  if ( ! $user_id ) {
    return false;
  }

  $can = ( 'full' === pdt_get_user_access_level( $user_id ) ) && user_can( $user_id, 'manage_options' );

  /**
   * Filter whether a user may manage Polanger features.
   *
   * @param bool $can     Whether management is allowed.
   * @param int  $user_id User ID being evaluated.
   */
  return (bool) apply_filters( 'polanger_current_user_can_manage', $can, $user_id );
}

/**
 * Deactivate free version if legacy slug is active.
 */
function pdt_deactivate_legacy_free_version() {
  // Check if FREE version is active
  $free_plugin = 'polanger-wp-admin-menu-manager/polanger-wp-admin-menu-manager.php';
  
  if ( is_plugin_active( $free_plugin ) ) {
    deactivate_plugins( $free_plugin );
    
    // Add admin notice
    add_action( 'admin_notices', function() {
      ?>
      <div class="notice notice-info is-dismissible">
        <p><?php esc_html_e( 'Legacy free version has been deactivated. Your settings have been preserved.', 'polanger-admin-menu-manager' ); ?></p>
      </div>
      <?php
    });
  }
}
register_activation_hook( __FILE__, 'pdt_deactivate_legacy_free_version' );

/**
 * Check on admin init if legacy free version is still active.
 */
function pdt_check_legacy_free_version() {
  if ( ! function_exists( 'is_plugin_active' ) ) {
    include_once ABSPATH . 'wp-admin/includes/plugin.php';
  }
  
  $free_plugin = 'polanger-wp-admin-menu-manager/polanger-wp-admin-menu-manager.php';
  
  if ( is_plugin_active( $free_plugin ) ) {
    deactivate_plugins( $free_plugin );
  }
}
add_action( 'admin_init', 'pdt_check_legacy_free_version', 1 );

/**
 * Boot extension hooks after all plugins are loaded.
 *
 * @return void
 */
function pdt_boot_extension_api() {
  global $pdt_extension_loader;

  if ( ! ( $pdt_extension_loader instanceof PDT_Extension_Loader ) ) {
    return;
  }

  /**
   * Fires when the Polanger extension API is ready.
   *
   * Third-party addons should hook into this action to register modules.
   */
  do_action( 'polanger_init', $pdt_extension_loader );
}
add_action( 'plugins_loaded', 'pdt_boot_extension_api', 20 );

if ( ! class_exists( 'PolangerDashboardTools' ) ) {

  class PolangerDashboardTools
  {

    public function __construct() {
      add_action( 'admin_menu', array( $this, 'pdt_add_settings_menu' ) );
      add_action( 'admin_init', array( $this, 'pdt_register_settings' ) );
      add_action( 'admin_init', array( $this, 'pdt_migrate_settings' ) );
      add_action( 'admin_menu', array( $this, 'pdt_get_menu_items' ), 99998 );
      add_action( 'admin_init', array( $this, 'pdt_handle_reset' ) );
      add_action( 'admin_menu', array( $this, 'pdt_hide_menu_items' ), 99999 );
      add_action( 'admin_menu', array( $this, 'pdt_rename_menu_items' ), 99999 );
      add_action( 'admin_init', array( $this, 'pdt_block_menu_access' ), 1 );
      add_filter( 'custom_menu_order', '__return_true' );
      add_filter( 'menu_order', array( $this, 'pdt_custom_menu_order' ), 9999 );
      add_action( 'admin_menu', array( $this, 'pdt_reorder_submenus' ), 99999 );
      add_action( 'admin_notices', array( $this, 'pdt_blocked_notice' ) );
      add_action( 'admin_enqueue_scripts', array( $this, 'pdt_admin_enqueue_style') );
    }

    /**
     * Encode a menu slug for safe use in HTML form input names.
     * Uses base64 and replaces +/= with form-safe chars that don't appear in base64.
     */
    private function pdt_encode_slug( $slug ) {
      return str_replace( array( '+', '/', '=' ), array( '.', '~', '' ), base64_encode( $slug ) );
    }

    /**
     * Decode an encoded menu slug back to original.
     */
    private function pdt_decode_slug( $encoded ) {
      $encoded = str_replace( array( '.', '~' ), array( '+', '/' ), $encoded );
      return base64_decode( $encoded );
    }

    /**
     * Get effective Menu Manager settings.
     *
     * Addons can filter this value without owning core Menu Manager logic.
     *
     * @return array
     */
    private function pdt_get_effective_settings() {
      $settings = get_option( 'pdt_settings', array() );
      $settings = is_array( $settings ) ? $settings : array();

      return apply_filters( 'polanger_effective_settings', $settings, 'pdt_settings', array(), 'menu-manager' );
    }

    /**
     * Migrate old plain-slug settings to new base64-encoded format.
     * Runs once and sets a flag so it doesn't run again.
     */
    public function pdt_migrate_settings() {
      if ( get_option( 'pdt_settings_v2_migrated' ) ) {
        return;
      }
      
      $old_settings = get_option( 'pdt_settings' );
      if ( empty( $old_settings ) || ! is_array( $old_settings ) ) {
        update_option( 'pdt_settings_v2_migrated', true );
        return;
      }
      
      // Check if settings are already in new format
      $already_migrated = false;
      foreach ( $old_settings as $key => $value ) {
        if ( strpos( $key, 'hide-all-' ) === 0 && strpos( $key, 'hide-all-sub-' ) === false ) {
          $encoded_part = substr( $key, 9 );
          $decoded = $this->pdt_decode_slug( $encoded_part );
          if ( ! empty( $decoded ) && ( strpos( $decoded, '.' ) !== false || strpos( $decoded, '-' ) !== false ) ) {
            $already_migrated = true;
          }
          break;
        }
      }
      
      if ( $already_migrated ) {
        update_option( 'pdt_settings_v2_migrated', true );
        return;
      }
      
      // Old format detected - clear settings so user can re-save with new format
      delete_option( 'pdt_settings' );
      delete_option( 'pdt_menu_items' );
      delete_option( 'pdt_original_menu_order' );
      update_option( 'pdt_settings_v2_migrated', true );
    }

    /**
     * Show notice when access is blocked
     */
    public function pdt_blocked_notice() {
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended
      if ( isset( $_GET['pdt_blocked'] ) && $_GET['pdt_blocked'] === '1' ) {
        ?>
        <div class="notice notice-error is-dismissible">
          <p><strong><?php esc_html_e( 'Access Denied', 'polanger-admin-menu-manager' ); ?></strong></p>
          <p><?php esc_html_e( 'You do not have permission to access that page. This restriction has been set by your administrator.', 'polanger-admin-menu-manager' ); ?></p>
        </div>
        <?php
      }
    }

    /**
     * Get all admin users (users who can access admin panel)
     */
    private function pdt_get_admin_users() {
      $users = get_users( array(
        'role__in' => array( 'administrator', 'editor', 'shop_manager' ),
        'orderby' => 'display_name',
        'order' => 'ASC',
      ) );
      
      $admin_users = array();
      foreach ( $users as $user ) {
        $admin_users[ $user->ID ] = $user->display_name . ' (' . $user->user_login . ')';
      }
      
      return $admin_users;
    }


    /**
     * Add top-level menu and submenus
     */
    public function pdt_add_settings_menu() {
      // Main menu
      add_menu_page(
        __( 'Polanger Admin Suite', 'polanger-admin-menu-manager' ),
        __( 'PG Suite', 'polanger-admin-menu-manager' ),
        'manage_options',
        'polanger-dashboard',
        array( $this, 'pdt_menu_manager_page' ),
        'dashicons-admin-settings',
        80
      );

      // Menu Manager submenu
      add_submenu_page(
        'polanger-dashboard',
        __( 'Menu Manager', 'polanger-admin-menu-manager' ),
        __( 'Menu Manager', 'polanger-admin-menu-manager' ),
        'manage_options',
        'polanger-dashboard',
        array( $this, 'pdt_menu_manager_page' )
      );

      // Admin Bar submenu
      add_submenu_page(
        'polanger-dashboard',
        __( 'Admin Bar', 'polanger-admin-menu-manager' ),
        __( 'Admin Bar', 'polanger-admin-menu-manager' ),
        'manage_options',
        'polanger-admin-bar',
        array( $this, 'pdt_admin_bar_page' )
      );

      // Login Page submenu
      add_submenu_page(
        'polanger-dashboard',
        __( 'Login Page', 'polanger-admin-menu-manager' ),
        __( 'Login Page', 'polanger-admin-menu-manager' ),
        'manage_options',
        'polanger-login-page',
        array( $this, 'pdt_login_page' )
      );

      if ( pdt_is_addon_active( 'admin-activity-log' ) ) {
        // Activity Log submenu
        add_submenu_page(
          'polanger-dashboard',
          __( 'Activity Log', 'polanger-admin-menu-manager' ),
          __( 'Activity Log', 'polanger-admin-menu-manager' ),
          'manage_options',
          'polanger-activity-log',
          array( $this, 'pdt_activity_log_page' )
        );
      }

      if ( pdt_is_addon_active( 'dashboard-widgets' ) ) {
        // Dashboard Widgets submenu
        add_submenu_page(
          'polanger-dashboard',
          __( 'Dashboard Center', 'polanger-admin-menu-manager' ),
          __( 'Dashboard Center', 'polanger-admin-menu-manager' ),
          'manage_options',
          'polanger-dashboard-widgets',
          array( $this, 'pdt_dashboard_widgets_page' )
        );
      }

      /**
       * Fires after Dashboard Center and before Settings submenu registration.
       *
       * Addons can use this hook to place their submenu in the main Polanger
       * navigation without hard-coding addon-specific menu entries in core.
       *
       * @param PolangerDashboardTools $this Main plugin instance.
       */
      do_action( 'pdt_admin_menu_after_dashboard_center', $this );

      // Settings submenu (with tabs)
      add_submenu_page(
        'polanger-dashboard',
        __( 'Settings', 'polanger-admin-menu-manager' ),
        __( 'Settings', 'polanger-admin-menu-manager' ),
        'manage_options',
        'polanger-settings',
        array( $this, 'pdt_settings_page' )
      );

      // Addons submenu
      add_submenu_page(
        'polanger-dashboard',
        __( 'Addons', 'polanger-admin-menu-manager' ),
        __( 'Addons', 'polanger-admin-menu-manager' ),
        'manage_options',
        'polanger-addons',
        array( $this, 'pdt_addons_page' )
      );

      // Help submenu (always last).
      add_submenu_page(
        'polanger-dashboard',
        __( 'Help', 'polanger-admin-menu-manager' ),
        __( 'Help', 'polanger-admin-menu-manager' ),
        'manage_options',
        'polanger-help',
        array( $this, 'pdt_help_page' )
      );
    }

    /**
     * Menu Manager page callback
     */
    public function pdt_menu_manager_page() {
      ?>
      <div id="pdt-wrap">
        <?php $this->render_menu_manager_tab(); ?>
      </div>
      <?php
    }

    /**
     * Admin Bar page callback
     */
    public function pdt_admin_bar_page() {
      ?>
      <div id="pdt-wrap">
        <?php $this->render_admin_bar_tab(); ?>
      </div>
      <?php
    }

    /**
     * Login Page callback
     */
    public function pdt_login_page() {
      ?>
      <div id="pdt-wrap">
        <?php $this->render_login_page_tab(); ?>
      </div>
      <?php
    }

    /**
     * Activity Log page callback
     */
    public function pdt_activity_log_page() {
      global $pdt_activity_log;
      ?>
      <div id="pdt-wrap">
        <div class="pdt-header">
          <h2 class="pdt-title"><?php esc_html_e( 'Activity Log', 'polanger-admin-menu-manager' ); ?></h2>
          <p class="pdt-subtitle"><?php esc_html_e( 'Monitor administrative actions on your site.', 'polanger-admin-menu-manager' ); ?></p>
        </div>
        <?php 
        if ( ! $pdt_activity_log->is_enabled() ) {
          ?>
          <div class="notice notice-warning pdt-notice-spaced">
            <p>
              <?php esc_html_e( 'Activity logging is currently disabled.', 'polanger-admin-menu-manager' ); ?>
              <a href="<?php echo esc_url( admin_url( 'admin.php?page=polanger-settings&tab=activity-log' ) ); ?>"><?php esc_html_e( 'Enable it in settings', 'polanger-admin-menu-manager' ); ?></a>
            </p>
          </div>
          <?php
        }
        $pdt_activity_log->render_logs_page(); 
        ?>
      </div>
      <?php
    }

    /**
     * Settings page callback
     */
    public function pdt_settings_page() {
      global $pdt_settings_page;
      $pdt_settings_page->render_page();
    }

    /**
     * Dashboard Widgets page callback
     */
    public function pdt_dashboard_widgets_page() {
      global $pdt_dashboard_widgets;
      ?>
      <div id="pdt-wrap">
        <div class="pdt-header">
          <h2 class="pdt-title"><?php esc_html_e( 'Dashboard Widgets', 'polanger-admin-menu-manager' ); ?></h2>
          <p class="pdt-subtitle"><?php esc_html_e( 'Manage dashboard widgets and admin notices.', 'polanger-admin-menu-manager' ); ?></p>
        </div>
        <?php
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( isset( $_GET['settings-updated'] ) && sanitize_text_field( wp_unslash( $_GET['settings-updated'] ) ) === 'true' ) :
        ?>
        <div class="pdt-notice pdt-notice-success">
          <span class="dashicons dashicons-yes-alt"></span>
          <?php esc_html_e( 'Settings saved.', 'polanger-admin-menu-manager' ); ?>
        </div>
        <?php endif; ?>
        <?php $pdt_dashboard_widgets->render_settings_page(); ?>
      </div>
      <?php
    }

    /**
     * Addons page callback
     */
    public function pdt_addons_page() {
      global $pdt_addons_page;
      $pdt_addons_page->render_page();
    }

    /**
     * Help page callback.
     *
     * @return void
     */
    public function pdt_help_page() {
      global $pdt_help_page;
      $pdt_help_page->render_page();
    }

    /**
     * Render Menu Manager tab content
     */
    private function render_menu_manager_tab() {
      $reset_url = wp_nonce_url( 
        admin_url( 'admin.php?page=polanger-dashboard&pdt_reset=1' ), 
        'pdt_reset_settings' 
      );
      ?>
      <div class="pdt-header">
        <h2 class="pdt-title"><?php esc_html_e( 'Menu Editor', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="pdt-subtitle"><?php esc_html_e( 'Hide or rename admin menu items easily.', 'polanger-admin-menu-manager' ); ?></p>
      </div>
      <?php do_action( 'pdt_menu_manager_after_header' ); ?>
      
      <?php
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a read-only display of success message after redirect
      if ( isset( $_GET['pdt_reset_success'] ) && sanitize_text_field( wp_unslash( $_GET['pdt_reset_success'] ) ) === '1' ) :
      ?>
      <div class="pdt-notice pdt-notice-success">
        <span class="dashicons dashicons-yes-alt"></span>
        <?php esc_html_e( 'All settings have been reset to defaults.', 'polanger-admin-menu-manager' ); ?>
      </div>
      <?php endif; ?>
      
      <form method="POST" action="options.php">
        <?php
          settings_fields( 'pdt_settings_group' );
          do_settings_sections( 'polanger-dashboard' );
        ?>
        <div class="pdt-buttons">
          <?php submit_button( __( 'Save Changes', 'polanger-admin-menu-manager' ), 'primary', 'submit', false ); ?>
          <a href="<?php echo esc_url( $reset_url ); ?>" class="pdt-reset-btn" id="pdt-reset-btn" data-confirm="<?php esc_attr_e( 'Are you sure you want to reset all settings? This action cannot be undone.', 'polanger-admin-menu-manager' ); ?>">
            <span class="dashicons dashicons-image-rotate"></span>
            <?php esc_html_e( 'Reset All Settings', 'polanger-admin-menu-manager' ); ?>
          </a>
        </div>
      </form>
      <?php do_action( 'pdt_menu_manager_after_form' ); ?>
      
      <?php
    }

    /**
     * Render Admin Bar tab content
     */
    private function render_admin_bar_tab() {
      ?>
      <div class="pdt-header">
        <h2 class="pdt-title"><?php esc_html_e( 'Admin Bar', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="pdt-subtitle"><?php esc_html_e( 'Customize the WordPress admin bar.', 'polanger-admin-menu-manager' ); ?></p>
      </div>
      
      <?php
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended
      if ( isset( $_GET['settings-updated'] ) && sanitize_text_field( wp_unslash( $_GET['settings-updated'] ) ) === 'true' ) :
      ?>
      <div class="pdt-notice pdt-notice-success">
        <span class="dashicons dashicons-yes-alt"></span>
        <?php esc_html_e( 'Settings saved.', 'polanger-admin-menu-manager' ); ?>
      </div>
      <?php endif; ?>
      
      <?php
      global $pdt_admin_bar;
      $pdt_admin_bar->render_settings_page();
    }

    /**
     * Render Login Page tab content
     */
    private function render_login_page_tab() {
      ?>
      <div class="pdt-header">
        <h2 class="pdt-title"><?php esc_html_e( 'Login Page', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="pdt-subtitle"><?php esc_html_e( 'Customize and secure your WordPress login page.', 'polanger-admin-menu-manager' ); ?></p>
      </div>
      
      <?php
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended
      if ( isset( $_GET['settings-updated'] ) && sanitize_text_field( wp_unslash( $_GET['settings-updated'] ) ) === 'true' ) :
      ?>
      <div class="pdt-notice pdt-notice-success">
        <span class="dashicons dashicons-yes-alt"></span>
        <?php esc_html_e( 'Settings saved.', 'polanger-admin-menu-manager' ); ?>
      </div>
      <?php endif; ?>
      
      <?php
      global $pdt_login_page;
      $pdt_login_page->render_settings_page();
    }

    /**
     * Register settings and sections.
     */
    public function pdt_register_settings() {

      register_setting( 'pdt_settings_group', 'pdt_settings', array(
        'type' => 'array',
        'sanitize_callback' => array( $this, 'pdt_sanitize_settings' ),
      ) );

      add_settings_section(
        'pdt_settings',
        __( 'General Settings', 'polanger-admin-menu-manager' ),
        array( $this, 'pdt_settings_section_callback' ),
        'polanger-dashboard'
      );

      add_settings_field(
        'pdt_hidden_items',
        __( 'Check the items to hide.', 'polanger-admin-menu-manager' ),
        array( $this, 'pdt_hidden_items_setting_callback' ),
        'polanger-dashboard',
        'pdt_settings'
      );

    }

    /**
     * Not needed at the moment.
     */
    public function pdt_settings_section_callback() {}

    /**
     * Sanitize settings before saving
     */
    public function pdt_sanitize_settings( $input ) {
      $sanitized = array();
      
      if ( ! is_array( $input ) ) {
        return $sanitized;
      }
      
      foreach ( $input as $key => $value ) {
        // Keys are now base64-encoded slugs, only allow safe chars (a-z, 0-9, -, _, ., ~)
        $clean_key = preg_replace( '/[^a-zA-Z0-9_\-\.~]/', '', $key );
        
        // PRO: Block access from specific users (array of user IDs)
        if ( strpos( $key, 'block-users-' ) === 0 ) {
          if ( is_array( $value ) ) {
            $sanitized[ $clean_key ] = array_map( 'absint', $value );
          } else {
            $sanitized[ $clean_key ] = array();
          }
        } elseif ( strpos( $key, 'block-all-' ) === 0 ) {
          // PRO: Block access from everyone
          $sanitized[ $clean_key ] = ( $value === 'on' ) ? 'on' : '';
        } elseif ( strpos( $key, 'hide-users-' ) === 0 ) {
          // PRO: Hide from specific users (array of user IDs)
          if ( is_array( $value ) ) {
            $sanitized[ $clean_key ] = array_map( 'absint', $value );
          } else {
            $sanitized[ $clean_key ] = array();
          }
        } elseif ( strpos( $key, 'hide-all-' ) === 0 ) {
          // PRO: Hide from everyone
          $sanitized[ $clean_key ] = ( $value === 'on' ) ? 'on' : '';
        } elseif ( strpos( $key, 'hide-' ) === 0 ) {
          // Legacy: simple on/off hide (for backwards compatibility)
          $sanitized[ $clean_key ] = ( $value === 'on' ) ? 'on' : '';
        } elseif ( strpos( $key, 'rename-' ) === 0 ) {
          $sanitized[ $clean_key ] = sanitize_text_field( $value );
        } elseif ( strpos( $key, 'icon-' ) === 0 ) {
          $sanitized[ $clean_key ] = sanitize_text_field( $value );
        } elseif ( $key === 'menu-order' ) {
          // PRO: Menu order (array of menu slugs)
          if ( is_array( $value ) ) {
            $sanitized[ $clean_key ] = array_map( 'sanitize_text_field', $value );
          }
        } elseif ( strpos( $key, 'submenu-order-' ) === 0 ) {
          // PRO: Submenu order (array of submenu slugs)
          if ( is_array( $value ) ) {
            $sanitized[ $clean_key ] = array_map( 'sanitize_text_field', $value );
          }
        }
      }
      
      return $sanitized;
    }

    /**
     * Handle reset settings request
     */
    public function pdt_handle_reset() {
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified below
      if ( ! isset( $_GET['pdt_reset'] ) || sanitize_text_field( wp_unslash( $_GET['pdt_reset'] ) ) !== '1' ) {
        return;
      }
      
      if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'pdt_reset_settings' ) ) {
        return;
      }
      
      if ( ! current_user_can( 'manage_options' ) ) {
        return;
      }
      
      // Delete all plugin settings
      delete_option( 'pdt_settings' );
      delete_option( 'pdt_menu_items' );
      delete_option( 'pdt_original_menu_order' );
      
      // Redirect back to settings page with success message
      wp_safe_redirect( admin_url( 'admin.php?page=polanger-dashboard&pdt_reset_success=1' ) );
      exit;
    }

    /**
     * Show the menu items settings field.
     */
    public function pdt_hidden_items_setting_callback() {

      $menu_items = get_option( 'pdt_menu_items' );
      $pdt_settings = $this->pdt_get_effective_settings();
      if ( ! is_array( $pdt_settings ) ) {
        $pdt_settings = array();
      }
      $nbr_of_items = 0;

      if ( empty( $menu_items ) || ! is_array( $menu_items ) ) {
        echo '<p>' . esc_html__( 'No menu items found. Please refresh the page.', 'polanger-admin-menu-manager' ) . '</p>';
        return;
      }

      // Apply saved custom order when it exists. Otherwise, use the latest
      // captured effective WordPress menu order so plugins that reshuffle
      // themselves via menu_order filters appear in the same place here.
      $menu_order = isset( $pdt_settings['menu-order'] ) ? $pdt_settings['menu-order'] : array();
      $live_menu_order = get_option( 'pdt_original_menu_order', array() );

      if ( ! empty( $menu_order ) ) {
        $ordered_items = array();
        foreach ( $menu_order as $slug ) {
          if ( isset( $menu_items[ $slug ] ) ) {
            $ordered_items[ $slug ] = $menu_items[ $slug ];
          }
        }
        // Add any new items that weren't in the saved order (at the end)
        foreach ( $menu_items as $slug => $item ) {
          if ( ! isset( $ordered_items[ $slug ] ) ) {
            $ordered_items[ $slug ] = $item;
          }
        }
        $menu_items = $ordered_items;
      } else {
        $menu_items = $this->pdt_sort_menu_items_by_slug_order( $menu_items, $live_menu_order );
      }

        echo '<div id="pdt-list">';
        echo '<table class="pdt-table">';
        echo '<thead><tr>';
        echo '<th class="pdt-drag-header"></th>';
        echo '<th>' . esc_html__( 'Visibility', 'polanger-admin-menu-manager' ) . '</th>';
        echo '<th>' . esc_html__( 'Icon', 'polanger-admin-menu-manager' ) . '</th>';
        echo '<th>' . esc_html__( 'Original Name', 'polanger-admin-menu-manager' ) . '</th>';
        echo '<th>' . esc_html__( 'Custom Name', 'polanger-admin-menu-manager' ) . '</th>';
        echo '</tr></thead>';
        echo '<tbody>';

          foreach ( $menu_items as $slug => $item ) {
            // Handle both old format (string) and new format (array)
            if ( is_array( $item ) ) {
              $name = $item['name'];
              $icon = isset( $item['icon'] ) ? $item['icon'] : '';
              $submenus = isset( $item['submenu'] ) ? $item['submenu'] : array();
            } else {
              $name = $item;
              $icon = '';
              $submenus = array();
            }
            
            $filtered_name = preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $name );
            $redable_name = wp_strip_all_tags( $filtered_name );
            $nbr_of_items++;
            
            // Encode slug for safe use in form input names
            $encoded_slug = $this->pdt_encode_slug( $slug );
            
            $hide_all_input_name = 'pdt_settings[hide-all-' . $encoded_slug . ']';
            $hide_users_input_name = 'pdt_settings[hide-users-' . $encoded_slug . ']';
            $block_all_input_name = 'pdt_settings[block-all-' . $encoded_slug . ']';
            $block_users_input_name = 'pdt_settings[block-users-' . $encoded_slug . ']';
            $rename_input_name = 'pdt_settings[rename-' . $encoded_slug . ']';
            $icon_input_name = 'pdt_settings[icon-' . $encoded_slug . ']';
            
            // PRO: Get hide settings for this menu
            $hide_all = isset( $pdt_settings['hide-all-' . $encoded_slug] ) && $pdt_settings['hide-all-' . $encoded_slug] === 'on';
            $hide_users = isset( $pdt_settings['hide-users-' . $encoded_slug] ) ? $pdt_settings['hide-users-' . $encoded_slug] : array();
            if ( ! is_array( $hide_users ) ) {
              $hide_users = array();
            }
            
            // PRO: Get block settings for this menu
            $block_all = isset( $pdt_settings['block-all-' . $encoded_slug] ) && $pdt_settings['block-all-' . $encoded_slug] === 'on';
            $block_users = isset( $pdt_settings['block-users-' . $encoded_slug] ) ? $pdt_settings['block-users-' . $encoded_slug] : array();
            if ( ! is_array( $block_users ) ) {
              $block_users = array();
            }
            
            $rename_value = isset( $pdt_settings['rename-' . $encoded_slug] ) ? $pdt_settings['rename-' . $encoded_slug] : '';
            $icon_value = isset( $pdt_settings['icon-' . $encoded_slug] ) ? $pdt_settings['icon-' . $encoded_slug] : '';
            
            // Determine current icon
            $current_icon = ! empty( $icon_value ) ? $icon_value : $icon;
            
            // Check if this menu is hidden
            $is_hidden = $hide_all || ! empty( $hide_users );
            
            // Check if this menu is renamed
            $is_renamed = ! empty( $rename_value );
            
            // Check if icon is changed
            $is_icon_changed = ! empty( $icon_value );
            
            // Check if any submenu is hidden or renamed
            $has_hidden_submenu = false;
            $has_renamed_submenu = false;
            if ( ! empty( $submenus ) ) {
              foreach ( $submenus as $sub_slug => $sub_name ) {
                $encoded_sub_key = $this->pdt_encode_slug( $slug . '|' . $sub_slug );
                // PRO: Check hide-all or hide-users
                $sub_hide_all = isset( $pdt_settings['hide-all-sub-' . $encoded_sub_key] ) && $pdt_settings['hide-all-sub-' . $encoded_sub_key] === 'on';
                $sub_hide_users = isset( $pdt_settings['hide-users-sub-' . $encoded_sub_key] ) ? $pdt_settings['hide-users-sub-' . $encoded_sub_key] : array();
                if ( $sub_hide_all || ! empty( $sub_hide_users ) ) {
                  $has_hidden_submenu = true;
                }
                if ( isset( $pdt_settings['rename-sub-' . $encoded_sub_key] ) && ! empty( $pdt_settings['rename-sub-' . $encoded_sub_key] ) ) {
                  $has_renamed_submenu = true;
                }
              }
            }
            
            // Build row classes
            $row_classes = array( 'pdt-menu-row' );
            if ( $is_hidden ) {
              $row_classes[] = 'is-hidden';
            }
            if ( $is_renamed || $is_icon_changed ) {
              $row_classes[] = 'is-renamed';
            }
            if ( $has_hidden_submenu ) {
              $row_classes[] = 'has-hidden-submenu';
            }
            if ( $has_renamed_submenu && ! $has_hidden_submenu ) {
              $row_classes[] = 'has-renamed-submenu';
            }
            ?>
            <tr class="<?php echo esc_attr( implode( ' ', $row_classes ) ); ?>" data-has-submenu="<?php echo ! empty( $submenus ) ? 'yes' : 'no'; ?>" data-slug="<?php echo esc_attr( $slug ); ?>">
              <td class="pdt-drag-cell" data-label="<?php esc_attr_e( 'Order', 'polanger-admin-menu-manager' ); ?>">
                <span class="pdt-drag-handle" title="<?php esc_attr_e( 'Drag to reorder', 'polanger-admin-menu-manager' ); ?>">
                  <span class="dashicons dashicons-menu"></span>
                </span>
              </td>
              <td class="pdt-hide-cell" data-label="<?php esc_attr_e( 'Visibility', 'polanger-admin-menu-manager' ); ?>">
                <div class="pdt-hide-selector">
                  <button type="button" class="pdt-hide-toggle <?php echo $is_hidden ? 'is-hidden' : ''; ?> <?php echo $block_all ? 'is-blocked' : ''; ?>" data-hide-all="<?php echo $hide_all ? '1' : '0'; ?>">
                    <span class="dashicons <?php echo $is_hidden ? 'dashicons-hidden' : 'dashicons-visibility'; ?>"></span>
                    <?php if ( $block_all || ! empty( $block_users ) ) : ?>
                      <span class="pdt-block-badge" title="<?php esc_attr_e( 'URL access blocked', 'polanger-admin-menu-manager' ); ?>">🔒</span>
                    <?php endif; ?>
                  </button>
                  <div class="pdt-hide-dropdown">
                    <div class="pdt-hide-dropdown-header">
                      <?php esc_html_e( 'Visibility & Access', 'polanger-admin-menu-manager' ); ?>
                    </div>
                    <div class="pdt-hide-options">
                      <!-- Hide from everyone -->
                      <div class="pdt-option-group <?php echo $hide_all ? 'active' : ''; ?>">
                        <label class="pdt-hide-all-option">
                          <input type="checkbox" name="<?php echo esc_attr( $hide_all_input_name ); ?>" value="on" <?php checked( $hide_all ); ?> class="pdt-hide-all-checkbox" />
                          <span class="dashicons dashicons-hidden"></span>
                          <span><?php esc_html_e( 'Hide from everyone', 'polanger-admin-menu-manager' ); ?></span>
                        </label>
                        <label class="pdt-block-option <?php echo ! $hide_all ? 'disabled' : ''; ?> <?php echo $block_all ? 'active' : ''; ?>" title="<?php esc_attr_e( 'Block direct URL access', 'polanger-admin-menu-manager' ); ?>">
                          <input type="checkbox" name="<?php echo esc_attr( $block_all_input_name ); ?>" value="on" <?php checked( $block_all ); ?> class="pdt-block-all-checkbox" <?php echo ! $hide_all ? 'disabled' : ''; ?> />
                          <span class="dashicons dashicons-lock"></span>
                          <span><?php esc_html_e( 'Block URL access', 'polanger-admin-menu-manager' ); ?></span>
                        </label>
                      </div>
                      
                      <!-- Hide from specific users -->
                      <div class="pdt-hide-users-section <?php echo $hide_all ? 'disabled' : ''; ?>">
                        <div class="pdt-hide-users-header">
                          <span class="dashicons dashicons-admin-users"></span>
                          <?php esc_html_e( 'Hide from specific users:', 'polanger-admin-menu-manager' ); ?>
                        </div>
                        <div class="pdt-hide-users-search-wrap">
                          <input type="search" class="pdt-hide-users-search" placeholder="<?php esc_attr_e( 'Type a user name to search and select...', 'polanger-admin-menu-manager' ); ?>" />
                        </div>
                        <div class="pdt-hide-users-list">
                          <?php foreach ( $this->pdt_get_admin_users() as $user_id => $user_name ) : 
                            $is_user_hidden = in_array( $user_id, $hide_users, true );
                            $is_user_blocked = in_array( $user_id, $block_users, true );
                          ?>
                            <div class="pdt-user-item-row" data-user-label="<?php echo esc_attr( strtolower( $user_name ) ); ?>">
                              <label class="pdt-user-item">
                                <input type="checkbox" name="<?php echo esc_attr( $hide_users_input_name ); ?>[]" value="<?php echo esc_attr( $user_id ); ?>" <?php checked( $is_user_hidden ); ?> <?php echo $hide_all ? 'disabled' : ''; ?> class="pdt-hide-user-checkbox" />
                                <span><?php echo esc_html( $user_name ); ?></span>
                              </label>
                              <label class="pdt-block-user-toggle <?php echo ! $is_user_hidden ? 'disabled' : ''; ?> <?php echo $is_user_blocked ? 'active' : ''; ?>" title="<?php esc_attr_e( 'Block URL access for this user', 'polanger-admin-menu-manager' ); ?>">
                                <input type="checkbox" name="<?php echo esc_attr( $block_users_input_name ); ?>[]" value="<?php echo esc_attr( $user_id ); ?>" <?php checked( $is_user_blocked ); ?> <?php echo ( $hide_all || ! $is_user_hidden ) ? 'disabled' : ''; ?> class="pdt-block-user-checkbox" />
                                <span class="dashicons dashicons-lock"></span>
                              </label>
                            </div>
                          <?php endforeach; ?>
                          <div class="pdt-user-search-empty">
                            <?php esc_html_e( 'Type to find users. Selected users stay visible.', 'polanger-admin-menu-manager' ); ?>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </td>
              <td class="pdt-icon-cell" data-label="<?php esc_attr_e( 'Icon', 'polanger-admin-menu-manager' ); ?>">
                <div class="pdt-icon-picker">
                  <span class="pdt-current-icon dashicons <?php echo esc_attr( $current_icon ); ?>"></span>
                  <input type="hidden" name="<?php echo esc_attr( $icon_input_name ); ?>" value="<?php echo esc_attr( $icon_value ); ?>" class="pdt-icon-input" />
                  <button type="button" class="pdt-icon-btn" title="<?php esc_attr_e( 'Change Icon', 'polanger-admin-menu-manager' ); ?>">
                    <span class="dashicons dashicons-edit"></span>
                  </button>
                </div>
              </td>
              <td class="pdt-original-cell" data-label="<?php esc_attr_e( 'Original Name', 'polanger-admin-menu-manager' ); ?>">
                <span class="pdt-menu-label">
                  <?php echo esc_html( $redable_name ); ?>
                  <?php
                  /**
                   * Fires after a main Menu Manager item label.
                   *
                   * Addons may render read-only context indicators here without
                   * changing or duplicating Menu Manager settings.
                   *
                   * @param string $slug          WordPress admin menu slug.
                   * @param mixed  $item          Captured menu item data.
                   * @param string $redable_name  Plain-text menu label.
                   */
                  do_action( 'pdt_menu_manager_item_label_after', $slug, $item, $redable_name );
                  ?>
                  <span class="pdt-slug-hint">(<?php echo esc_html( $slug ); ?>)</span>
                  <?php if ( ! empty( $submenus ) ) : ?>
                    <span class="pdt-submenu-toggle dashicons dashicons-arrow-down-alt2"></span>
                  <?php endif; ?>
                </span>
              </td>
              <td class="pdt-custom-name-cell" data-label="<?php esc_attr_e( 'Custom Name', 'polanger-admin-menu-manager' ); ?>">
                <input type="text" name="<?php echo esc_attr( $rename_input_name ); ?>" value="<?php echo esc_attr( $rename_value ); ?>" placeholder="<?php echo esc_attr( $redable_name ); ?>" class="pdt-rename-input" />
              </td>
            </tr>
            <?php
            // Render submenus
            if ( ! empty( $submenus ) ) :
              // Apply saved submenu order if exists
              $encoded_parent = $this->pdt_encode_slug( $slug );
              $submenu_order_key = 'submenu-order-' . $encoded_parent;
              $saved_submenu_order = isset( $pdt_settings[ $submenu_order_key ] ) ? $pdt_settings[ $submenu_order_key ] : array();
              
              if ( ! empty( $saved_submenu_order ) ) {
                $ordered_submenus = array();
                foreach ( $saved_submenu_order as $sub_slug_ordered ) {
                  if ( isset( $submenus[ $sub_slug_ordered ] ) ) {
                    $ordered_submenus[ $sub_slug_ordered ] = $submenus[ $sub_slug_ordered ];
                  }
                }
                // Add any new submenus that weren't in saved order
                foreach ( $submenus as $sub_slug_new => $sub_data_new ) {
                  if ( ! isset( $ordered_submenus[ $sub_slug_new ] ) ) {
                    $ordered_submenus[ $sub_slug_new ] = $sub_data_new;
                  }
                }
                $submenus = $ordered_submenus;
              }
              
              foreach ( $submenus as $sub_slug => $sub_data ) :
                // Handle both old format (string) and new format (array with name/position)
                if ( is_array( $sub_data ) && isset( $sub_data['name'] ) ) {
                  $sub_name = $sub_data['name'];
                } else {
                  $sub_name = $sub_data;
                }
                $sub_filtered_name = preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $sub_name );
                $sub_readable_name = wp_strip_all_tags( $sub_filtered_name );
                $nbr_of_items++;
                
                // Encode the full sub key for safe form input names
                $encoded_sub_key = $this->pdt_encode_slug( $slug . '|' . $sub_slug );
                $sub_hide_all_input = 'pdt_settings[hide-all-sub-' . $encoded_sub_key . ']';
                $sub_hide_users_input = 'pdt_settings[hide-users-sub-' . $encoded_sub_key . ']';
                $sub_block_all_input = 'pdt_settings[block-all-sub-' . $encoded_sub_key . ']';
                $sub_block_users_input = 'pdt_settings[block-users-sub-' . $encoded_sub_key . ']';
                $sub_rename_input = 'pdt_settings[rename-sub-' . $encoded_sub_key . ']';
                
                // PRO: Get hide settings for this submenu
                $sub_hide_all = isset( $pdt_settings['hide-all-sub-' . $encoded_sub_key] ) && $pdt_settings['hide-all-sub-' . $encoded_sub_key] === 'on';
                $sub_hide_users = isset( $pdt_settings['hide-users-sub-' . $encoded_sub_key] ) ? $pdt_settings['hide-users-sub-' . $encoded_sub_key] : array();
                if ( ! is_array( $sub_hide_users ) ) {
                  $sub_hide_users = array();
                }
                
                // PRO: Get block settings for this submenu
                $sub_block_all = isset( $pdt_settings['block-all-sub-' . $encoded_sub_key] ) && $pdt_settings['block-all-sub-' . $encoded_sub_key] === 'on';
                $sub_block_users = isset( $pdt_settings['block-users-sub-' . $encoded_sub_key] ) ? $pdt_settings['block-users-sub-' . $encoded_sub_key] : array();
                if ( ! is_array( $sub_block_users ) ) {
                  $sub_block_users = array();
                }
                
                $sub_rename_value = isset( $pdt_settings['rename-sub-' . $encoded_sub_key] ) ? $pdt_settings['rename-sub-' . $encoded_sub_key] : '';
                $sub_is_hidden = $sub_hide_all || ! empty( $sub_hide_users );
                $sub_is_renamed = ! empty( $sub_rename_value );
                
                $sub_row_classes = array( 'pdt-submenu-row' );
                if ( $sub_is_hidden ) {
                  $sub_row_classes[] = 'is-hidden';
                }
                if ( $sub_is_renamed ) {
                  $sub_row_classes[] = 'is-renamed';
                }
                ?>
                <tr class="<?php echo esc_attr( implode( ' ', $sub_row_classes ) ); ?>" data-parent="<?php echo esc_attr( $slug ); ?>" data-sub-slug="<?php echo esc_attr( $sub_slug ); ?>">
                  <td class="pdt-drag-cell pdt-submenu-drag" data-label="<?php esc_attr_e( 'Order', 'polanger-admin-menu-manager' ); ?>">
                    <span class="pdt-drag-handle pdt-submenu-handle" title="<?php esc_attr_e( 'Drag to reorder', 'polanger-admin-menu-manager' ); ?>">
                      <span class="dashicons dashicons-menu"></span>
                    </span>
                  </td>
                  <td class="pdt-hide-cell" data-label="<?php esc_attr_e( 'Visibility', 'polanger-admin-menu-manager' ); ?>">
                    <div class="pdt-hide-selector">
                      <button type="button" class="pdt-hide-toggle <?php echo $sub_is_hidden ? 'is-hidden' : ''; ?> <?php echo $sub_block_all ? 'is-blocked' : ''; ?>" data-hide-all="<?php echo $sub_hide_all ? '1' : '0'; ?>">
                        <span class="dashicons <?php echo $sub_is_hidden ? 'dashicons-hidden' : 'dashicons-visibility'; ?>"></span>
                        <?php if ( $sub_block_all || ! empty( $sub_block_users ) ) : ?>
                          <span class="pdt-block-badge" title="<?php esc_attr_e( 'URL access blocked', 'polanger-admin-menu-manager' ); ?>">🔒</span>
                        <?php endif; ?>
                      </button>
                      <div class="pdt-hide-dropdown">
                        <div class="pdt-hide-dropdown-header">
                          <?php esc_html_e( 'Visibility & Access', 'polanger-admin-menu-manager' ); ?>
                        </div>
                        <div class="pdt-hide-options">
                          <!-- Hide from everyone -->
                          <div class="pdt-option-group <?php echo $sub_hide_all ? 'active' : ''; ?>">
                            <label class="pdt-hide-all-option">
                              <input type="checkbox" name="<?php echo esc_attr( $sub_hide_all_input ); ?>" value="on" <?php checked( $sub_hide_all ); ?> class="pdt-hide-all-checkbox" />
                              <span class="dashicons dashicons-hidden"></span>
                              <span><?php esc_html_e( 'Hide from everyone', 'polanger-admin-menu-manager' ); ?></span>
                            </label>
                            <label class="pdt-block-option <?php echo ! $sub_hide_all ? 'disabled' : ''; ?> <?php echo $sub_block_all ? 'active' : ''; ?>" title="<?php esc_attr_e( 'Block direct URL access', 'polanger-admin-menu-manager' ); ?>">
                              <input type="checkbox" name="<?php echo esc_attr( $sub_block_all_input ); ?>" value="on" <?php checked( $sub_block_all ); ?> class="pdt-block-all-checkbox" <?php echo ! $sub_hide_all ? 'disabled' : ''; ?> />
                              <span class="dashicons dashicons-lock"></span>
                              <span><?php esc_html_e( 'Block URL access', 'polanger-admin-menu-manager' ); ?></span>
                            </label>
                          </div>
                          
                          <!-- Hide from specific users -->
                          <div class="pdt-hide-users-section <?php echo $sub_hide_all ? 'disabled' : ''; ?>">
                            <div class="pdt-hide-users-header">
                              <span class="dashicons dashicons-admin-users"></span>
                              <?php esc_html_e( 'Hide from specific users:', 'polanger-admin-menu-manager' ); ?>
                            </div>
                            <div class="pdt-hide-users-search-wrap">
                              <input type="search" class="pdt-hide-users-search" placeholder="<?php esc_attr_e( 'Type a user name to search and select...', 'polanger-admin-menu-manager' ); ?>" />
                            </div>
                            <div class="pdt-hide-users-list">
                              <?php foreach ( $this->pdt_get_admin_users() as $user_id => $user_name ) : 
                                $sub_is_user_hidden = in_array( $user_id, $sub_hide_users, true );
                                $sub_is_user_blocked = in_array( $user_id, $sub_block_users, true );
                              ?>
                                <div class="pdt-user-item-row" data-user-label="<?php echo esc_attr( strtolower( $user_name ) ); ?>">
                                  <label class="pdt-user-item">
                                    <input type="checkbox" name="<?php echo esc_attr( $sub_hide_users_input ); ?>[]" value="<?php echo esc_attr( $user_id ); ?>" <?php checked( $sub_is_user_hidden ); ?> <?php echo $sub_hide_all ? 'disabled' : ''; ?> class="pdt-hide-user-checkbox" />
                                    <span><?php echo esc_html( $user_name ); ?></span>
                                  </label>
                                  <label class="pdt-block-user-toggle <?php echo ! $sub_is_user_hidden ? 'disabled' : ''; ?> <?php echo $sub_is_user_blocked ? 'active' : ''; ?>" title="<?php esc_attr_e( 'Block URL access for this user', 'polanger-admin-menu-manager' ); ?>">
                                    <input type="checkbox" name="<?php echo esc_attr( $sub_block_users_input ); ?>[]" value="<?php echo esc_attr( $user_id ); ?>" <?php checked( $sub_is_user_blocked ); ?> <?php echo ( $sub_hide_all || ! $sub_is_user_hidden ) ? 'disabled' : ''; ?> class="pdt-block-user-checkbox" />
                                    <span class="dashicons dashicons-lock"></span>
                                  </label>
                                </div>
                              <?php endforeach; ?>
                              <div class="pdt-user-search-empty">
                                <?php esc_html_e( 'Type to find users. Selected users stay visible.', 'polanger-admin-menu-manager' ); ?>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </td>
                  <td class="pdt-icon-cell" data-label="<?php esc_attr_e( 'Icon', 'polanger-admin-menu-manager' ); ?>">
                    <span class="pdt-submenu-indicator">↳</span>
                  </td>
                  <td class="pdt-original-cell" data-label="<?php esc_attr_e( 'Original Name', 'polanger-admin-menu-manager' ); ?>">
                    <span class="pdt-menu-label">
                      <?php echo esc_html( $sub_readable_name ); ?>
                      <?php
                      /**
                       * Fires after a submenu label in Menu Manager.
                       *
                       * @param string $slug               Parent menu slug.
                       * @param string $sub_slug           WordPress admin submenu slug.
                       * @param mixed  $sub_data           Captured submenu data.
                       * @param string $sub_readable_name  Plain-text submenu label.
                       */
                      do_action( 'pdt_menu_manager_submenu_label_after', $slug, $sub_slug, $sub_data, $sub_readable_name );
                      ?>
                    </span>
                  </td>
                  <td class="pdt-custom-name-cell" data-label="<?php esc_attr_e( 'Custom Name', 'polanger-admin-menu-manager' ); ?>">
                    <input type="text" name="<?php echo esc_attr( $sub_rename_input ); ?>" value="<?php echo esc_attr( $sub_rename_value ); ?>" placeholder="<?php echo esc_attr( $sub_readable_name ); ?>" class="pdt-rename-input" />
                  </td>
                </tr>
                <?php
              endforeach;
            endif;

          }
          
        echo '</tbody></table>';
        ?>
          <p class="pdt-summary"><?php esc_html_e( "Number of items : ", "polanger-admin-menu-manager" ); ?>
            <span class="pdt-count"><?php echo esc_html( $nbr_of_items ); ?></span>
            /
            <span class="pdt-total"><?php echo esc_html( $nbr_of_items ); ?></span>
          </p>
          
          <div class="pdt-legend">
            <div class="pdt-legend-title">
              <span class="dashicons dashicons-info-outline"></span>
              <?php esc_html_e( 'Color Legend', 'polanger-admin-menu-manager' ); ?>
            </div>
            <div class="pdt-legend-items">
              <div class="pdt-legend-item">
                <span class="pdt-legend-color hidden"></span>
                <span><?php esc_html_e( 'Hidden menu item', 'polanger-admin-menu-manager' ); ?></span>
              </div>
              <div class="pdt-legend-item">
                <span class="pdt-legend-color has-hidden"></span>
                <span><?php esc_html_e( 'Contains hidden submenu items', 'polanger-admin-menu-manager' ); ?></span>
              </div>
              <div class="pdt-legend-item">
                <span class="pdt-legend-color renamed"></span>
                <span><?php esc_html_e( 'Custom name or icon applied', 'polanger-admin-menu-manager' ); ?></span>
              </div>
              <div class="pdt-legend-item">
                <span class="pdt-legend-color renamed"></span>
                <span><?php esc_html_e( 'Contains renamed submenu items', 'polanger-admin-menu-manager' ); ?></span>
              </div>
              <div class="pdt-legend-item">
                <span class="pdt-legend-color normal"></span>
                <span><?php esc_html_e( 'No changes (default)', 'polanger-admin-menu-manager' ); ?></span>
              </div>
            </div>
          </div>
          <?php

        echo '</div>';
        
        // Output hidden inputs for saved menu order (only if custom order exists)
        $saved_menu_order = isset( $pdt_settings['menu-order'] ) ? $pdt_settings['menu-order'] : array();
        if ( ! empty( $saved_menu_order ) ) {
          foreach ( $saved_menu_order as $menu_slug ) {
            echo '<input type="hidden" name="pdt_settings[menu-order][]" value="' . esc_attr( $menu_slug ) . '" />';
          }
        }
        
        // Output hidden inputs for saved submenu orders
        if ( is_array( $pdt_settings ) ) {
          foreach ( $pdt_settings as $key => $value ) {
            if ( strpos( $key, 'submenu-order-' ) === 0 && is_array( $value ) ) {
              foreach ( $value as $sub_slug ) {
                echo '<input type="hidden" name="pdt_settings[' . esc_attr( $key ) . '][]" value="' . esc_attr( $sub_slug ) . '" />';
              }
            }
          }
        }
        
        // Icon picker modal
        $this->pdt_render_icon_picker_modal();
    }
    
    /**
     * Render the icon picker modal
     */
    private function pdt_render_icon_picker_modal() {
      $dashicons = array(
        'dashicons-admin-appearance', 'dashicons-admin-collapse', 'dashicons-admin-comments',
        'dashicons-admin-customizer', 'dashicons-admin-generic', 'dashicons-admin-home',
        'dashicons-admin-links', 'dashicons-admin-media', 'dashicons-admin-multisite',
        'dashicons-admin-network', 'dashicons-admin-page', 'dashicons-admin-plugins',
        'dashicons-admin-post', 'dashicons-admin-settings', 'dashicons-admin-site',
        'dashicons-admin-tools', 'dashicons-admin-users', 'dashicons-album',
        'dashicons-analytics', 'dashicons-archive', 'dashicons-arrow-down',
        'dashicons-arrow-left', 'dashicons-arrow-right', 'dashicons-arrow-up',
        'dashicons-art', 'dashicons-awards', 'dashicons-backup',
        'dashicons-bank', 'dashicons-beer', 'dashicons-bell',
        'dashicons-block-default', 'dashicons-book', 'dashicons-book-alt',
        'dashicons-buddicons-activity', 'dashicons-buddicons-buddypress-logo', 'dashicons-buddicons-community',
        'dashicons-buddicons-forums', 'dashicons-buddicons-friends', 'dashicons-buddicons-groups',
        'dashicons-buddicons-pm', 'dashicons-buddicons-replies', 'dashicons-buddicons-topics',
        'dashicons-building', 'dashicons-businessman', 'dashicons-businessperson',
        'dashicons-businesswoman', 'dashicons-calculator', 'dashicons-calendar',
        'dashicons-calendar-alt', 'dashicons-camera', 'dashicons-camera-alt',
        'dashicons-car', 'dashicons-carrot', 'dashicons-cart',
        'dashicons-category', 'dashicons-chart-area', 'dashicons-chart-bar',
        'dashicons-chart-line', 'dashicons-chart-pie', 'dashicons-clipboard',
        'dashicons-clock', 'dashicons-cloud', 'dashicons-cloud-saved',
        'dashicons-cloud-upload', 'dashicons-coffee', 'dashicons-color-picker',
        'dashicons-columns', 'dashicons-controls-back', 'dashicons-controls-forward',
        'dashicons-controls-pause', 'dashicons-controls-play', 'dashicons-controls-repeat',
        'dashicons-controls-skipback', 'dashicons-controls-skipforward', 'dashicons-controls-volumeoff',
        'dashicons-controls-volumeon', 'dashicons-cover-image', 'dashicons-dashboard',
        'dashicons-database', 'dashicons-desktop', 'dashicons-dismiss',
        'dashicons-download', 'dashicons-drumstick', 'dashicons-edit',
        'dashicons-edit-large', 'dashicons-edit-page', 'dashicons-editor-aligncenter',
        'dashicons-editor-alignleft', 'dashicons-editor-alignright', 'dashicons-editor-bold',
        'dashicons-editor-break', 'dashicons-editor-code', 'dashicons-editor-contract',
        'dashicons-editor-customchar', 'dashicons-editor-expand', 'dashicons-editor-help',
        'dashicons-editor-indent', 'dashicons-editor-insertmore', 'dashicons-editor-italic',
        'dashicons-editor-justify', 'dashicons-editor-kitchensink', 'dashicons-editor-ltr',
        'dashicons-editor-ol', 'dashicons-editor-outdent', 'dashicons-editor-paragraph',
        'dashicons-editor-paste-text', 'dashicons-editor-paste-word', 'dashicons-editor-quote',
        'dashicons-editor-removeformatting', 'dashicons-editor-rtl', 'dashicons-editor-spellcheck',
        'dashicons-editor-strikethrough', 'dashicons-editor-table', 'dashicons-editor-textcolor',
        'dashicons-editor-ul', 'dashicons-editor-underline', 'dashicons-editor-unlink',
        'dashicons-editor-video', 'dashicons-ellipsis', 'dashicons-email',
        'dashicons-email-alt', 'dashicons-email-alt2', 'dashicons-embed-audio',
        'dashicons-embed-generic', 'dashicons-embed-photo', 'dashicons-embed-post',
        'dashicons-embed-video', 'dashicons-excerpt-view', 'dashicons-exit',
        'dashicons-external', 'dashicons-facebook', 'dashicons-facebook-alt',
        'dashicons-feedback', 'dashicons-filter', 'dashicons-flag',
        'dashicons-food', 'dashicons-format-aside', 'dashicons-format-audio',
        'dashicons-format-chat', 'dashicons-format-gallery', 'dashicons-format-image',
        'dashicons-format-quote', 'dashicons-format-status', 'dashicons-format-video',
        'dashicons-forms', 'dashicons-fullscreen-alt', 'dashicons-fullscreen-exit-alt',
        'dashicons-games', 'dashicons-google', 'dashicons-grid-view',
        'dashicons-groups', 'dashicons-hammer', 'dashicons-heading',
        'dashicons-heart', 'dashicons-hidden', 'dashicons-hourglass',
        'dashicons-html', 'dashicons-id', 'dashicons-id-alt',
        'dashicons-image-crop', 'dashicons-image-filter', 'dashicons-image-flip-horizontal',
        'dashicons-image-flip-vertical', 'dashicons-image-rotate', 'dashicons-image-rotate-left',
        'dashicons-image-rotate-right', 'dashicons-images-alt', 'dashicons-images-alt2',
        'dashicons-index-card', 'dashicons-info', 'dashicons-info-outline',
        'dashicons-insert', 'dashicons-insert-after', 'dashicons-insert-before',
        'dashicons-instagram', 'dashicons-keyboard-hide', 'dashicons-laptop',
        'dashicons-layout', 'dashicons-leftright', 'dashicons-lightbulb',
        'dashicons-linkedin', 'dashicons-list-view', 'dashicons-location',
        'dashicons-location-alt', 'dashicons-lock', 'dashicons-marker',
        'dashicons-media-archive', 'dashicons-media-audio', 'dashicons-media-code',
        'dashicons-media-default', 'dashicons-media-document', 'dashicons-media-interactive',
        'dashicons-media-spreadsheet', 'dashicons-media-text', 'dashicons-media-video',
        'dashicons-megaphone', 'dashicons-menu', 'dashicons-menu-alt',
        'dashicons-menu-alt2', 'dashicons-menu-alt3', 'dashicons-microphone',
        'dashicons-migrate', 'dashicons-minus', 'dashicons-money',
        'dashicons-money-alt', 'dashicons-move', 'dashicons-nametag',
        'dashicons-networking', 'dashicons-no', 'dashicons-no-alt',
        'dashicons-open-folder', 'dashicons-palmtree', 'dashicons-paperclip',
        'dashicons-pdf', 'dashicons-performance', 'dashicons-pets',
        'dashicons-phone', 'dashicons-pinterest', 'dashicons-playlist-audio',
        'dashicons-playlist-video', 'dashicons-plus', 'dashicons-plus-alt',
        'dashicons-plus-alt2', 'dashicons-podio', 'dashicons-portfolio',
        'dashicons-post-status', 'dashicons-pressthis', 'dashicons-printer',
        'dashicons-privacy', 'dashicons-products', 'dashicons-randomize',
        'dashicons-reddit', 'dashicons-redo', 'dashicons-remove',
        'dashicons-rest-api', 'dashicons-rss', 'dashicons-saved',
        'dashicons-schedule', 'dashicons-screenoptions', 'dashicons-search',
        'dashicons-share', 'dashicons-share-alt', 'dashicons-share-alt2',
        'dashicons-shield', 'dashicons-shield-alt', 'dashicons-shortcode',
        'dashicons-slides', 'dashicons-smartphone', 'dashicons-smiley',
        'dashicons-sort', 'dashicons-sos', 'dashicons-spotify',
        'dashicons-star-empty', 'dashicons-star-filled', 'dashicons-star-half',
        'dashicons-sticky', 'dashicons-store', 'dashicons-superhero',
        'dashicons-superhero-alt', 'dashicons-table-col-after', 'dashicons-table-col-before',
        'dashicons-table-col-delete', 'dashicons-table-row-after', 'dashicons-table-row-before',
        'dashicons-table-row-delete', 'dashicons-tablet', 'dashicons-tag',
        'dashicons-tagcloud', 'dashicons-testimonial', 'dashicons-text',
        'dashicons-text-page', 'dashicons-thumbs-down', 'dashicons-thumbs-up',
        'dashicons-tickets', 'dashicons-tickets-alt', 'dashicons-tide',
        'dashicons-translation', 'dashicons-trash', 'dashicons-twitter',
        'dashicons-twitter-alt', 'dashicons-undo', 'dashicons-universal-access',
        'dashicons-universal-access-alt', 'dashicons-unlock', 'dashicons-update',
        'dashicons-update-alt', 'dashicons-upload', 'dashicons-vault',
        'dashicons-video-alt', 'dashicons-video-alt2', 'dashicons-video-alt3',
        'dashicons-visibility', 'dashicons-warning', 'dashicons-welcome-add-page',
        'dashicons-welcome-comments', 'dashicons-welcome-learn-more', 'dashicons-welcome-view-site',
        'dashicons-welcome-widgets-menus', 'dashicons-welcome-write-blog', 'dashicons-whatsapp',
        'dashicons-wordpress', 'dashicons-wordpress-alt', 'dashicons-xing',
        'dashicons-yes', 'dashicons-yes-alt', 'dashicons-youtube'
      );
      ?>
      <div id="pdt-icon-modal" class="pdt-modal pdt-hidden">
        <div class="pdt-modal-content">
          <div class="pdt-modal-header">
            <h3><?php esc_html_e( 'Select Icon', 'polanger-admin-menu-manager' ); ?></h3>
            <button type="button" class="pdt-modal-close">&times;</button>
          </div>
          <div class="pdt-modal-body">
            <div class="pdt-icon-search">
              <input type="text" id="pdt-icon-search" placeholder="<?php esc_attr_e( 'Search icons...', 'polanger-admin-menu-manager' ); ?>" />
            </div>
            <div class="pdt-icon-grid">
              <?php foreach ( $dashicons as $icon ) : ?>
                <span class="pdt-icon-option dashicons <?php echo esc_attr( $icon ); ?>" data-icon="<?php echo esc_attr( $icon ); ?>" title="<?php echo esc_attr( $icon ); ?>"></span>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
      </div>
      <?php
    }

    /**
     * Get all admin menu items and update the list.
     */
    public function pdt_get_menu_items() {

      if ( ! is_admin() ) {
        return;
      }

      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a read-only operation on admin page
      if ( isset( $_GET['page'] ) && 'polanger-dashboard' === sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {

        global $menu, $submenu;
        
        // Sort menu by WordPress position keys to preserve original order
        $sorted_menu = $menu;
        ksort( $sorted_menu );
        
        // Get main menu items with their icons - preserving WordPress order
        $menu_items = array();
        $original_order = array();
        
        foreach ( $sorted_menu as $position => $item ) {
          if ( empty( $item[0] ) || empty( $item[2] ) ) {
            continue;
          }
          // Keep WordPress Settings menu visible; skip only our own plugin pages.
          if ( in_array( $item[2], array( 'polanger-dashboard', 'polanger-settings' ), true ) ) {
            continue;
          }
          // Capture all registered top-level items as they exist in the menu
          // array. Some plugins expose menus using dynamic/custom capabilities
          // that are resolved later than a simple current_user_can() check.
          $slug = $item[2];
          $original_order[] = $slug;
          
          $menu_items[ $slug ] = array(
            'name' => $item[0],
            'icon' => isset( $item[6] ) ? $item[6] : '',
            'position' => $position,
            'submenu' => array()
          );
        }
        
        // Get submenu items - preserving WordPress order
        foreach ( $submenu as $parent_slug => $sub_items ) {
          if ( ! isset( $menu_items[ $parent_slug ] ) ) {
            continue;
          }
          
          // Sort submenus by position
          $sorted_subs = $sub_items;
          ksort( $sorted_subs );
          
          foreach ( $sorted_subs as $sub_position => $sub_item ) {
            if ( empty( $sub_item[0] ) || empty( $sub_item[2] ) ) {
              continue;
            }
            $menu_items[ $parent_slug ]['submenu'][ $sub_item[2] ] = array(
              'name' => $sub_item[0],
              'position' => $sub_position
            );
          }
        }

        update_option( 'pdt_menu_items', $menu_items );
        update_option( 'pdt_original_menu_order', $this->pdt_get_live_wp_menu_order( $original_order ) );

      }

    }

    /**
     * Sort captured menu items by their WordPress sidebar position.
     *
     * @param array $menu_items Captured menu items.
     * @return array
     */
    private function pdt_sort_menu_items_by_position( $menu_items ) {
      if ( empty( $menu_items ) || ! is_array( $menu_items ) ) {
        return array();
      }

      uasort(
        $menu_items,
        static function ( $left, $right ) {
          $left_position  = ( is_array( $left ) && isset( $left['position'] ) ) ? (float) $left['position'] : PHP_FLOAT_MAX;
          $right_position = ( is_array( $right ) && isset( $right['position'] ) ) ? (float) $right['position'] : PHP_FLOAT_MAX;

          if ( $left_position === $right_position ) {
            $left_name  = ( is_array( $left ) && isset( $left['name'] ) ) ? wp_strip_all_tags( (string) $left['name'] ) : '';
            $right_name = ( is_array( $right ) && isset( $right['name'] ) ) ? wp_strip_all_tags( (string) $right['name'] ) : '';

            return strnatcasecmp( $left_name, $right_name );
          }

          return ( $left_position < $right_position ) ? -1 : 1;
        }
      );

      return $menu_items;
    }

    /**
     * Sort menu items by an explicit slug order and append unknown items
     * using their captured sidebar positions.
     *
     * @param array $menu_items Menu items keyed by slug.
     * @param array $slug_order Preferred slug order.
     * @return array
     */
    private function pdt_sort_menu_items_by_slug_order( $menu_items, $slug_order ) {
      if ( empty( $menu_items ) || ! is_array( $menu_items ) ) {
        return array();
      }

      if ( empty( $slug_order ) || ! is_array( $slug_order ) ) {
        return $this->pdt_sort_menu_items_by_position( $menu_items );
      }

      $ordered_items = array();

      foreach ( $slug_order as $slug ) {
        if ( isset( $menu_items[ $slug ] ) ) {
          $ordered_items[ $slug ] = $menu_items[ $slug ];
        }
      }

      $remaining_items = array();
      foreach ( $menu_items as $slug => $item ) {
        if ( ! isset( $ordered_items[ $slug ] ) ) {
          $remaining_items[ $slug ] = $item;
        }
      }

      if ( ! empty( $remaining_items ) ) {
        $remaining_items = $this->pdt_sort_menu_items_by_position( $remaining_items );
        foreach ( $remaining_items as $slug => $item ) {
          $ordered_items[ $slug ] = $item;
        }
      }

      return $ordered_items;
    }

    /**
     * Get the effective live WordPress top-level menu order after third-party
     * menu_order filters have run, excluding this plugin's saved custom order.
     *
     * @param array $fallback_order Fallback order from raw menu positions.
     * @return array
     */
    private function pdt_get_live_wp_menu_order( $fallback_order ) {
      if ( empty( $fallback_order ) || ! is_array( $fallback_order ) ) {
        return array();
      }

      $effective_order = $fallback_order;

      if ( ! apply_filters( 'custom_menu_order', false ) ) {
        return $effective_order;
      }

      remove_filter( 'menu_order', array( $this, 'pdt_custom_menu_order' ), 9999 );
      $filtered_order = apply_filters( 'menu_order', $fallback_order );
      add_filter( 'menu_order', array( $this, 'pdt_custom_menu_order' ), 9999 );

      if ( is_array( $filtered_order ) ) {
        $effective_order = $this->pdt_normalize_menu_order( $filtered_order, $fallback_order );
      }

      return $effective_order;
    }

    /**
     * Normalize a menu order candidate against the current set of known slugs.
     *
     * @param array $candidate_order Candidate slug order.
     * @param array $fallback_order Known slugs in fallback order.
     * @return array
     */
    private function pdt_normalize_menu_order( $candidate_order, $fallback_order ) {
      if ( empty( $fallback_order ) || ! is_array( $fallback_order ) ) {
        return array();
      }

      $allowed = array_fill_keys( $fallback_order, true );
      $seen = array();
      $normalized = array();

      if ( is_array( $candidate_order ) ) {
        foreach ( $candidate_order as $slug ) {
          $slug = (string) $slug;
          if ( isset( $allowed[ $slug ] ) && ! isset( $seen[ $slug ] ) ) {
            $normalized[] = $slug;
            $seen[ $slug ] = true;
          }
        }
      }

      foreach ( $fallback_order as $slug ) {
        $slug = (string) $slug;
        if ( ! isset( $seen[ $slug ] ) ) {
          $normalized[] = $slug;
          $seen[ $slug ] = true;
        }
      }

      return $normalized;
    }

    /**
     * Hide the unnecessary menu items based on settings.
     */
    public function pdt_hide_menu_items() {
      $pdt_settings = $this->pdt_get_effective_settings();

      if ( empty( $pdt_settings ) ) {
        return;
      }

      global $menu, $submenu;

      // Get current user ID
      $current_user_id = get_current_user_id();

      foreach ( $pdt_settings as $setting => $value ) {
        // PRO: Hide from everyone (main menu) - encoded slug
        if ( strpos( $setting, 'hide-all-' ) === 0 && strpos( $setting, 'hide-all-sub-' ) === false ) {
          if ( $value === 'on' ) {
            $encoded = substr( $setting, 9 );
            $slug = $this->pdt_decode_slug( $encoded );
            remove_menu_page( $slug );
            
            // Fallback: directly unset from global $menu array for stubborn menus
            if ( ! empty( $menu ) ) {
              foreach ( $menu as $menu_key => $menu_item ) {
                if ( isset( $menu_item[2] ) && $menu_item[2] === $slug ) {
                  unset( $menu[ $menu_key ] );
                  break;
                }
              }
            }
          }
        }
        
        // PRO: Hide from specific users (main menu) - encoded slug
        if ( strpos( $setting, 'hide-users-' ) === 0 && strpos( $setting, 'hide-users-sub-' ) === false ) {
          if ( ! is_array( $value ) || empty( $value ) ) {
            continue;
          }
          
          // Check if current user is in the hidden users list
          if ( in_array( $current_user_id, $value, true ) ) {
            $encoded = substr( $setting, 11 );
            $slug = $this->pdt_decode_slug( $encoded );
            remove_menu_page( $slug );
            
            // Fallback: directly unset from global $menu array
            if ( ! empty( $menu ) ) {
              foreach ( $menu as $menu_key => $menu_item ) {
                if ( isset( $menu_item[2] ) && $menu_item[2] === $slug ) {
                  unset( $menu[ $menu_key ] );
                  break;
                }
              }
            }
          }
        }
        
        // PRO: Hide from everyone (submenu) - encoded slug containing parent|child
        if ( strpos( $setting, 'hide-all-sub-' ) === 0 ) {
          if ( $value === 'on' ) {
            $encoded = substr( $setting, 13 );
            $decoded = $this->pdt_decode_slug( $encoded );
            $parts = explode( '|', $decoded );
            if ( count( $parts ) === 2 ) {
              remove_submenu_page( $parts[0], $parts[1] );
              
              // Fallback: directly unset from global $submenu array
              if ( ! empty( $submenu[ $parts[0] ] ) ) {
                foreach ( $submenu[ $parts[0] ] as $sub_key => $sub_item ) {
                  if ( isset( $sub_item[2] ) && $sub_item[2] === $parts[1] ) {
                    unset( $submenu[ $parts[0] ][ $sub_key ] );
                    break;
                  }
                }
              }
            }
          }
        }
        
        // PRO: Hide from specific users (submenu) - encoded slug
        if ( strpos( $setting, 'hide-users-sub-' ) === 0 ) {
          if ( ! is_array( $value ) || empty( $value ) ) {
            continue;
          }
          
          // Check if current user is in the hidden users list
          if ( in_array( $current_user_id, $value, true ) ) {
            $encoded = substr( $setting, 15 );
            $decoded = $this->pdt_decode_slug( $encoded );
            $parts = explode( '|', $decoded );
            if ( count( $parts ) === 2 ) {
              remove_submenu_page( $parts[0], $parts[1] );
              
              // Fallback: directly unset from global $submenu array
              if ( ! empty( $submenu[ $parts[0] ] ) ) {
                foreach ( $submenu[ $parts[0] ] as $sub_key => $sub_item ) {
                  if ( isset( $sub_item[2] ) && $sub_item[2] === $parts[1] ) {
                    unset( $submenu[ $parts[0] ][ $sub_key ] );
                    break;
                  }
                }
              }
            }
          }
        }
      }
    }

    /**
     * Block direct URL access to menu pages based on settings.
     */
    public function pdt_block_menu_access() {
      // Don't block on AJAX requests
      if ( wp_doing_ajax() ) {
        return;
      }

      $pdt_settings = $this->pdt_get_effective_settings();

      if ( empty( $pdt_settings ) ) {
        return;
      }

      // Get current user ID and current page
      $current_user_id = get_current_user_id();
      
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a read-only check
      $current_page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
      
      // Get the current admin page file
      global $pagenow;
      
      // Don't block our own settings page
      if ( $current_page === 'polanger-admin-menu-manager' ) {
        return;
      }

      foreach ( $pdt_settings as $setting => $value ) {
        // PRO: Block access from everyone (main menu) - encoded slug
        if ( strpos( $setting, 'block-all-' ) === 0 && strpos( $setting, 'block-all-sub-' ) === false ) {
          if ( $value === 'on' ) {
            $encoded = substr( $setting, 10 );
            $slug = $this->pdt_decode_slug( $encoded );
            if ( $this->pdt_is_current_page( $slug, $pagenow, $current_page ) ) {
              $this->pdt_block_access();
            }
          }
        }
        
        // PRO: Block access from specific users (main menu) - encoded slug
        if ( strpos( $setting, 'block-users-' ) === 0 && strpos( $setting, 'block-users-sub-' ) === false ) {
          if ( ! is_array( $value ) || empty( $value ) ) {
            continue;
          }
          
          if ( in_array( $current_user_id, $value, true ) ) {
            $encoded = substr( $setting, 12 );
            $slug = $this->pdt_decode_slug( $encoded );
            if ( $this->pdt_is_current_page( $slug, $pagenow, $current_page ) ) {
              $this->pdt_block_access();
            }
          }
        }
        
        // PRO: Block access from everyone (submenu) - encoded slug
        if ( strpos( $setting, 'block-all-sub-' ) === 0 ) {
          if ( $value === 'on' ) {
            $encoded = substr( $setting, 14 );
            $decoded = $this->pdt_decode_slug( $encoded );
            $parts = explode( '|', $decoded );
            if ( count( $parts ) === 2 ) {
              $sub_slug = $parts[1];
              if ( $this->pdt_is_current_page( $sub_slug, $pagenow, $current_page ) ) {
                $this->pdt_block_access();
              }
            }
          }
        }
        
        // PRO: Block access from specific users (submenu) - encoded slug
        if ( strpos( $setting, 'block-users-sub-' ) === 0 ) {
          if ( ! is_array( $value ) || empty( $value ) ) {
            continue;
          }
          
          if ( in_array( $current_user_id, $value, true ) ) {
            $encoded = substr( $setting, 16 );
            $decoded = $this->pdt_decode_slug( $encoded );
            $parts = explode( '|', $decoded );
            if ( count( $parts ) === 2 ) {
              $sub_slug = $parts[1];
              if ( $this->pdt_is_current_page( $sub_slug, $pagenow, $current_page ) ) {
                $this->pdt_block_access();
              }
            }
          }
        }
      }
    }

    /**
     * Check if current page matches the menu slug
     */
    private function pdt_is_current_page( $slug, $pagenow, $current_page ) {
      // Check if slug matches current page parameter
      if ( ! empty( $current_page ) && $current_page === $slug ) {
        return true;
      }
      
      // Check if slug matches pagenow (for top-level pages like edit.php, upload.php)
      if ( $pagenow === $slug ) {
        return true;
      }
      
      // Check for pages with query strings (e.g., edit.php?post_type=page, edit-tags.php?taxonomy=category)
      if ( strpos( $slug, '?' ) !== false ) {
        $slug_parts = explode( '?', $slug, 2 );
        $slug_file = $slug_parts[0];
        $slug_query = isset( $slug_parts[1] ) ? $slug_parts[1] : '';
        
        if ( $pagenow === $slug_file ) {
          // Parse query string from slug
          parse_str( $slug_query, $slug_params );
          $match = true;
          
          foreach ( $slug_params as $param_key => $param_value ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $request_value = isset( $_GET[ $param_key ] ) ? sanitize_text_field( wp_unslash( $_GET[ $param_key ] ) ) : '';
            if ( $request_value !== $param_value ) {
              $match = false;
              break;
            }
          }
          
          if ( $match ) {
            return true;
          }
        }
        
        // Also check if slug contains page= parameter and matches current_page
        if ( strpos( $slug_query, 'page=' ) !== false ) {
          parse_str( $slug_query, $slug_params );
          if ( isset( $slug_params['page'] ) && $slug_params['page'] === $current_page ) {
            return true;
          }
        }
      }
      
      // Special handling for submenus: check if slug is just a page parameter value
      // This handles cases like "elementor" which should match admin.php?page=elementor
      if ( ! empty( $current_page ) && strpos( $slug, '.php' ) === false && strpos( $slug, '?' ) === false ) {
        // Slug doesn't contain .php or ?, so it might be a page parameter
        if ( $current_page === $slug ) {
          return true;
        }
      }
      
      // Handle submenus that are stored as full URLs like "admin.php?page=xyz"
      // but we're checking against just the page parameter
      if ( strpos( $slug, 'admin.php?page=' ) === 0 ) {
        $page_value = str_replace( 'admin.php?page=', '', $slug );
        // Handle additional query params after page=
        if ( strpos( $page_value, '&' ) !== false ) {
          $page_value = explode( '&', $page_value )[0];
        }
        if ( $current_page === $page_value ) {
          return true;
        }
      }
      
      return false;
    }

  /**
   * Block access and show a clear permission error screen.
   */
    private function pdt_block_access() {
      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,
          'back_link' => true,
        )
      );
    }

    /**
     * Rename menu items based on settings.
     */
    public function pdt_rename_menu_items() {
      global $menu, $submenu;
      
      $pdt_settings = $this->pdt_get_effective_settings();

      if ( empty( $pdt_settings ) ) {
        return;
      }

      // Rename main menus
      if ( ! empty( $menu ) ) {
        foreach ( $menu as $key => $item ) {
          if ( empty( $item[2] ) ) {
            continue;
          }
          
          $slug = $item[2];
          $encoded_slug = $this->pdt_encode_slug( $slug );
          $rename_key = 'rename-' . $encoded_slug;
          $icon_key = 'icon-' . $encoded_slug;
          
          // Apply custom name
          if ( isset( $pdt_settings[ $rename_key ] ) && ! empty( $pdt_settings[ $rename_key ] ) ) {
            $menu[ $key ][0] = esc_html( $pdt_settings[ $rename_key ] );
          }
          
          // Apply custom icon
          if ( isset( $pdt_settings[ $icon_key ] ) && ! empty( $pdt_settings[ $icon_key ] ) ) {
            $menu[ $key ][6] = esc_attr( $pdt_settings[ $icon_key ] );
          }
        }
      }
      
      // Rename submenus
      if ( ! empty( $submenu ) ) {
        foreach ( $submenu as $parent_slug => $sub_items ) {
          foreach ( $sub_items as $sub_key => $sub_item ) {
            if ( empty( $sub_item[2] ) ) {
              continue;
            }
            
            $sub_slug = $sub_item[2];
            $encoded_sub_key = $this->pdt_encode_slug( $parent_slug . '|' . $sub_slug );
            $rename_key = 'rename-sub-' . $encoded_sub_key;
            
            if ( isset( $pdt_settings[ $rename_key ] ) && ! empty( $pdt_settings[ $rename_key ] ) ) {
              $submenu[ $parent_slug ][ $sub_key ][0] = esc_html( $pdt_settings[ $rename_key ] );
            }
          }
        }
      }
    }

    /**
     * Custom menu order using WordPress filter.
     */
    public function pdt_custom_menu_order( $menu_order ) {
      $pdt_settings = $this->pdt_get_effective_settings();

      if ( empty( $pdt_settings ) ) {
        return $menu_order;
      }

      $saved_order = isset( $pdt_settings['menu-order'] ) ? $pdt_settings['menu-order'] : array();
      
      if ( empty( $saved_order ) ) {
        return $menu_order;
      }

      // Build new order: saved items first, then remaining items
      $new_order = array();
      
      // Add items in saved order
      foreach ( $saved_order as $slug ) {
        if ( in_array( $slug, $menu_order, true ) ) {
          $new_order[] = $slug;
        }
      }
      
      // Add remaining items that weren't in saved order
      foreach ( $menu_order as $slug ) {
        if ( ! in_array( $slug, $new_order, true ) ) {
          $new_order[] = $slug;
        }
      }

      return $new_order;
    }

    /**
     * Reorder submenus based on saved order.
     */
    public function pdt_reorder_submenus() {
      global $menu, $submenu;
      
      $pdt_settings = $this->pdt_get_effective_settings();

      if ( empty( $pdt_settings ) ) {
        return;
      }

      // Reorder submenus
      foreach ( $pdt_settings as $key => $order ) {
        if ( strpos( $key, 'submenu-order-' ) === 0 && is_array( $order ) ) {
          $encoded_parent = substr( $key, 14 );
          $parent_slug = $this->pdt_decode_slug( $encoded_parent );
          
          if ( ! isset( $submenu[ $parent_slug ] ) || empty( $submenu[ $parent_slug ] ) ) {
            continue;
          }
          
          $new_submenu = array();
          $position = 0;
          
          // First, add items in the saved order
          foreach ( $order as $sub_slug ) {
            foreach ( $submenu[ $parent_slug ] as $sub_key => $sub_item ) {
              if ( isset( $sub_item[2] ) && $sub_item[2] === $sub_slug ) {
                $new_submenu[ $position ] = $sub_item;
                unset( $submenu[ $parent_slug ][ $sub_key ] );
                $position++;
                break;
              }
            }
          }
          
          // Then, add any remaining items
          foreach ( $submenu[ $parent_slug ] as $sub_item ) {
            $new_submenu[ $position ] = $sub_item;
            $position++;
          }
          
          $submenu[ $parent_slug ] = $new_submenu;
        }
      }
    }

    /**
     * Load PDT plugin scripts.
     */
    public function pdt_admin_enqueue_style() {
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a read-only operation for enqueuing scripts
      $current_page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
      $pdt_css_path = plugin_dir_path( __FILE__ ) . 'assets/css/pdt.css';
      $pdt_css_version = file_exists( $pdt_css_path ) ? (string) filemtime( $pdt_css_path ) : PDT_VERSION;

      if ( 0 === strpos( $current_page, 'polanger-' ) ) {
        /**
         * Fires on Polanger admin pages before core assets are enqueued.
         *
         * Third-party addons can enqueue or inject theme/UI styles without
         * modifying core files.
         *
         * @param string $current_page Current Polanger page slug.
         */
        do_action( 'polanger_admin_theme_assets', $current_page );
      }
      
      // Menu Manager page
      if ( 'polanger-dashboard' === $current_page ) {
        wp_enqueue_script( 'jquery-ui-sortable' );
        wp_enqueue_script( 'pdt-admin-script', plugin_dir_url( __FILE__ ) . 'assets/js/pdt.js', array( 'jquery', 'jquery-ui-sortable' ), '1.1.0', true );
        wp_localize_script(
          'pdt-admin-script',
          'pdtMenuManagerI18n',
          array(
            'urlAccessBlockedTitle' => __( 'URL access blocked', 'polanger-admin-menu-manager' ),
          )
        );
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
      }
      
      // Activity Log pages
      if ( pdt_is_addon_active( 'admin-activity-log' ) && in_array( $current_page, array( 'polanger-activity-log' ), true ) ) {
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
        wp_enqueue_style( 'pdt-activity-log-style', plugin_dir_url( __FILE__ ) . 'addons/admin-activity-log/css/activity-log.css', array(), '1.0.0' );
      }
      
      // Settings page
      if ( 'polanger-settings' === $current_page ) {
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
        wp_enqueue_style( 'pdt-settings-style', plugin_dir_url( __FILE__ ) . 'assets/css/settings-page.css', array(), PDT_VERSION );
        wp_enqueue_style( 'pdt-activity-log-style', plugin_dir_url( __FILE__ ) . 'addons/admin-activity-log/css/activity-log.css', array(), '1.0.0' );
      }
      
      // Dashboard Widgets page
      if ( pdt_is_addon_active( 'dashboard-widgets' ) && 'polanger-dashboard-widgets' === $current_page ) {
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
        wp_enqueue_style( 'pdt-dashboard-widgets-style', plugin_dir_url( __FILE__ ) . 'addons/dashboard-widgets/css/dashboard-widgets.css', array(), '1.0.3' );
        wp_enqueue_script( 'pdt-dashboard-widgets-script', plugin_dir_url( __FILE__ ) . 'addons/dashboard-widgets/js/dashboard-widgets.js', array( 'jquery' ), '1.0.3', true );
      }

      // Admin Bar page
      if ( 'polanger-admin-bar' === $current_page ) {
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
      }

      // Login Page
      if ( 'polanger-login-page' === $current_page ) {
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
      }

      // Addons page
      if ( 'polanger-addons' === $current_page ) {
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
        wp_enqueue_style( 'pdt-addons-style', plugin_dir_url( __FILE__ ) . 'assets/css/addons-page.css', array(), PDT_VERSION );
        wp_enqueue_script( 'pdt-addons-script', plugin_dir_url( __FILE__ ) . 'assets/js/addons-page.js', array(), PDT_VERSION, true );
      }

      // Help page.
      if ( 'polanger-help' === $current_page ) {
        wp_enqueue_style( 'pdt-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/pdt.css', array(), $pdt_css_version );
        wp_enqueue_style( 'pdt-help-style', plugin_dir_url( __FILE__ ) . 'assets/css/help-page.css', array(), PDT_VERSION );
      }
    }

  }

  /**
   * Let's go ! ☆彡
   */
  new PolangerDashboardTools();

  // Initialize Admin Bar module
  global $pdt_admin_bar;
  $pdt_admin_bar = new PDT_Admin_Bar();

  // Initialize Login Page module
  global $pdt_login_page;
  $pdt_login_page = new PDT_Login_Page();

  // Initialize Settings Page module
  global $pdt_settings_page;
  $pdt_settings_page = new PDT_Settings_Page();

  // Initialize frontend content visibility core module.
  global $pdt_content_visibility;
  $pdt_content_visibility = new PDT_Content_Visibility();

  // Initialize Addons page module
  global $pdt_addons_page;
  $pdt_addons_page = new PDT_Addons_Page();

  // Initialize Help page module.
  global $pdt_help_page;
  $pdt_help_page = new PDT_Help_Page();

  // Initialize extension loader (manifest + runtime registrations).
  global $pdt_extension_loader;
  $pdt_extension_loader = new PDT_Extension_Loader();
  add_filter( 'pdt_register_addons', array( $pdt_extension_loader, 'inject_registered_addons' ), 5 );

  // Safely load optional built-in addon files so one bad addon cannot crash the suite.
  global $pdt_optional_addon_loader;
  $pdt_optional_addon_loader = new PDT_Optional_Addon_Loader( pdt_get_optional_internal_addon_definitions() );

  // Initialize Two-Factor Auth module
  global $pdt_two_factor;
  $pdt_two_factor = new PDT_Two_Factor_Auth();

  // Initialize Activity Log addon
  if ( pdt_is_addon_active( 'admin-activity-log' ) ) {
    global $pdt_activity_log;
    $pdt_activity_log = new PDT_Admin_Activity_Log();
  }

  // Initialize Dashboard Widgets addon
  if ( pdt_is_addon_active( 'dashboard-widgets' ) ) {
    global $pdt_dashboard_widgets;
    $pdt_dashboard_widgets = new PDT_Dashboard_Widgets();
  }

  // Initialize Custom Admin Menu addon
  if ( pdt_is_addon_active( 'custom-admin-menu' ) ) {
    global $pdt_custom_admin_menu;
    $pdt_custom_admin_menu = pdt_boot_optional_internal_addon( 'custom-admin-menu' );
  }

  // Initialize Design System addon
  if ( pdt_is_addon_active( 'design-system' ) ) {
    global $pdt_design_system;
    $pdt_design_system = pdt_boot_optional_internal_addon( 'design-system' );
  }

  // Initialize Comment Security Layer addon
  if ( pdt_is_addon_active( 'comment-security' ) ) {
    global $pdt_comment_security;
    $pdt_comment_security = pdt_boot_optional_internal_addon( 'comment-security' );
  }

  // Initialize reCAPTCHA addon
  if ( pdt_is_addon_active( 'recaptcha' ) ) {
    global $pdt_recaptcha;
    $pdt_recaptcha = pdt_boot_optional_internal_addon( 'recaptcha' );
  }

  // Initialize Polanger Authenticator addon
  if ( pdt_is_addon_active( 'polanger-authenticator' ) ) {
    global $pdt_polanger_authenticator;
    $pdt_polanger_authenticator = pdt_boot_optional_internal_addon( 'polanger-authenticator' );
  }

  // Initialize Multisite Control addon
  if ( is_multisite() && pdt_is_addon_active( 'multisite-control' ) ) {
    global $pdt_multisite_control;
    $pdt_multisite_control = pdt_boot_optional_internal_addon( 'multisite-control' );
  }

  // Initialize Polanger Shield addon
  if ( pdt_is_addon_active( 'polanger-shield' ) ) {
    global $pdt_polanger_shield;
    $pdt_polanger_shield = pdt_boot_optional_internal_addon( 'polanger-shield' );
  }

  // Initialize WooCommerce Security addon
  if ( pdt_is_addon_active( 'woocommerce-security' ) ) {
    global $pdt_woocommerce_security;
    $pdt_woocommerce_security = pdt_boot_optional_internal_addon( 'woocommerce-security' );
  }

  // Initialize Maintenance Center addon
  if ( pdt_is_addon_active( 'maintenance-center' ) ) {
    global $pdt_maintenance_center;
    $pdt_maintenance_center = pdt_boot_optional_internal_addon( 'maintenance-center' );
  }

  // Initialize Firewall addon
  if ( pdt_is_addon_active( 'firewall' ) ) {
    global $pdt_firewall;
    $pdt_firewall = pdt_boot_optional_internal_addon( 'firewall' );
  }

  // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals
}
