<?php
if (!defined('WPINC')) { die; }

/**
 * Detect the current language in a portable way:
 * - use custausu_lang() when available;
 * - fall back to URI prefixes such as /it/.
 */
function custausu_detect_lang_from_request(): string {
    // 0) Default language and normalized language list.
    $default = strtolower(trim((string) custausu_config('routes.policy.default_lang', 'en')));
    if ($default === '') $default = 'en';

    $langs = (array) custausu_config('i18n.langs', [$default]);
    $langs = array_values(array_filter(array_map(function($x){
        $x = strtolower(trim((string)$x));
        return $x !== '' ? $x : null;
    }, $langs)));

    if (empty($langs)) $langs = [$default];

    // 1) Use custausu_lang() when available.
    if (function_exists('custausu_lang')) {
        $l = strtolower(trim((string) custausu_lang()));
        if ($l !== '' && in_array($l, $langs, true)) return $l;
    }

    // 2) Use path prefixes such as /it/ or /en/.
    $uri = isset($_SERVER['REQUEST_URI'])
        ? sanitize_text_field(wp_unslash((string) $_SERVER['REQUEST_URI']))
        : '';

    $path = (string) wp_parse_url($uri, PHP_URL_PATH);
    $path = $path !== '' ? $path : '/';

    if (function_exists('custausu_lang_from_path')) {
        $l = strtolower(trim((string) custausu_lang_from_path($path)));
        if ($l !== '' && in_array($l, $langs, true)) return $l;
    }

    // 3) Fallback to Polylang / custausu_current_lang.
    if (function_exists('custausu_current_lang')) {
        $l = strtolower(trim((string) custausu_current_lang()));
        if ($l !== '' && in_array($l, $langs, true)) return $l;
    }

    return $default;
}

/**
 * Decide whether to inject into the current menu.
 * Portable default: true for every menu.
 * Can be restricted via config or filter.
 */
function custausu_should_inject_menu($args): bool {

    // 1) Restrict by theme_location when configured.
    $locs = function_exists('custausu_config') ? (array) custausu_config('routes.menu.theme_locations', []) : [];
    $locs = array_values(array_filter(array_map('strval', $locs)));

    if (!empty($locs)) {
        $current = isset($args->theme_location) ? (string) $args->theme_location : '';
        if ($current === '') return false;
        return in_array($current, $locs, true);
    }

    // 2) Restrict by menu slug, name, or ID when configured.
    $menus = function_exists('custausu_config') ? (array) custausu_config('routes.menu.menus', []) : [];
    $menus = array_values(array_filter(array_map('strval', $menus)));

    if (!empty($menus)) {
        // $args->menu may be a string, ID, or term object.
        if (isset($args->menu)) {
            if (is_string($args->menu) && in_array($args->menu, $menus, true)) return true;

            if (is_numeric($args->menu) && in_array((string)$args->menu, $menus, true)) return true;

            if (is_object($args->menu)) {
                if (!empty($args->menu->slug) && in_array((string)$args->menu->slug, $menus, true)) return true;
                if (!empty($args->menu->name) && in_array((string)$args->menu->name, $menus, true)) return true;
                if (!empty($args->menu->term_id) && in_array((string)$args->menu->term_id, $menus, true)) return true;
            }
        }
        return false;
    }

    // 3) Fallback override filter.
    $ok = true;
    if (function_exists('apply_filters')) {
        $ok = (bool) apply_filters('custausu_menu_login_inject', $ok, $args);
    }
    return $ok;
}

/**
 * Create a WP menu item compatible with the standard walker.
 */
function custausu_make_menu_item(array $data) {
    $defaults = [
        'ID' => 0,
        'db_id' => 0,
        'menu_item_parent' => 0,
        'object_id' => 0,
        'object' => 'custom',
        'type' => 'custom',
        'type_label' => 'Custom Link',
        'title' => '',
        'url' => '',
        'target' => '',
        'attr_title' => '',
        'description' => '',
        'classes' => [],
        'xfn' => '',

        /*
         * WordPress nav walkers expect these runtime properties on menu items.
         * Synthetic CAS items must provide them to avoid undefined-property
         * notices in classic themes/walkers.
         */
        'current' => false,
        'current_item_ancestor' => false,
        'current_item_parent' => false,
        'current_object_id' => 0,
        'current_object' => '',
        'menu_order' => 0,
        'post_type' => 'nav_menu_item',
        'post_status' => 'publish',
        'filter' => 'raw',
    ];

    $o = (object) array_merge($defaults, $data);

    // The walker expects classes to be an array.
    if (!is_array($o->classes)) $o->classes = [];

    return $o;
}

/**
 * Menu greeting label with CAS/Polylang-aware language handling.
 */
function custausu_menu_greeting_label(): string {

    $user = wp_get_current_user();
    $name = $user && $user->exists() ? $user->display_name : '';

    $lang = custausu_detect_lang_from_request();

    $fmt = ($lang === 'it')
        ? '| ' . (function_exists('custausu__t_safe') ? custausu__t_safe('Ciao %s') : 'Ciao %s') . ' |'
        : '| ' . (function_exists('custausu__t_safe') ? custausu__t_safe('Hi %s') : 'Hi %s') . ' |';

    return sprintf($fmt, esc_html($name));
}

/**
 * CAS account URL for logged-in menu users.
 *
 * Important:
 * - CAS landing route is the post-login/post-registration destination.
 * - "My Account" must point to the WordPress user profile area.
 */
function custausu_menu_account_url(string $lang): string {
    return admin_url('profile.php');
}

/**
 * Small menu label helper. Keeps Free package usable before translation files exist.
 */
function custausu_menu_label(string $en, string $it, string $lang): string {
    return $lang === 'it' ? $it : $en;
}

/**
 * Normalize menu URLs to compare static login page items against CAS login route.
 */
function custausu_menu_url_path(string $url): string {
    $path = (string) wp_parse_url($url, PHP_URL_PATH);
    $path = $path !== '' ? $path : '/';
    return untrailingslashit($path);
}

/**
 * Detect static login/account-login menu items so they can become "My Account"
 * once the visitor is authenticated.
 */
function custausu_menu_is_login_item($item, string $login_url): bool {
    $item_url = isset($item->url) ? (string) $item->url : '';

    if ($item_url !== '' && custausu_menu_url_path($item_url) === custausu_menu_url_path($login_url)) {
        return true;
    }

    $title = isset($item->title) ? strtolower(trim(wp_strip_all_tags((string) $item->title))) : '';
    $title = function_exists('remove_accents') ? remove_accents($title) : $title;

    return in_array($title, [
        'login',
        'account login',
        'accesso account',
        'accesso',
    ], true);
}

/**
 * Detect an existing logout item to avoid duplicate logout links.
 */
function custausu_menu_has_logout_item(array $items): bool {
    foreach ($items as $item) {
        $url = isset($item->url) ? (string) $item->url : '';
        if ($url !== '' && strpos($url, 'action=logout') !== false) {
            return true;
        }

        $title = isset($item->title) ? strtolower(trim(wp_strip_all_tags((string) $item->title))) : '';
        $title = function_exists('remove_accents') ? remove_accents($title) : $title;

        if (in_array($title, ['logout', 'log out', 'esci'], true)) {
            return true;
        }
    }

    return false;
}


/**
 * Remove CAS technical auth pages from nav menu object arrays.
 *
 * Some themes, including classic/fallback menu implementations, build an
 * automatic menu as nav menu objects instead of using wp_list_pages().
 */

if (!function_exists('custausu_menu_is_language_switcher_item')) {
    /**
     * Detect Polylang/language-switcher menu items.
     *
     * CAS hides technical auth pages from normal navigation, but language
     * switchers must remain visible even when their target URL is a hidden
     * auth page translation such as register/lost-password/reset-confirm.
     */
    function custausu_menu_is_language_switcher_item($item): bool {
        if (!is_object($item)) {
            return false;
        }

        $classes = isset($item->classes) && is_array($item->classes)
            ? $item->classes
            : [];

        foreach ($classes as $class) {
            $class = strtolower(trim((string) $class));

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

            if (
                $class === 'lang-item' ||
                strpos($class, 'lang-item-') === 0 ||
                strpos($class, 'pll-') === 0 ||
                strpos($class, 'polylang') !== false ||
                strpos($class, 'language-switcher') !== false
            ) {
                return true;
            }
        }

        return false;
    }
}

if (!function_exists('custausu_menu_html_item_is_language_switcher')) {
    /**
     * Detect language-switcher fragments in fallback/block menu HTML.
     */
    function custausu_menu_html_item_is_language_switcher(string $item_html): bool {
        $item_html = strtolower($item_html);

        if ($item_html === '') {
            return false;
        }

        return (
            strpos($item_html, 'lang-item') !== false ||
            strpos($item_html, 'pll-') !== false ||
            strpos($item_html, 'polylang') !== false ||
            strpos($item_html, 'language-switcher') !== false ||
            strpos($item_html, 'hreflang=') !== false
        );
    }
}


function custausu_menu_prune_auth_service_items(array $items): array {
    $hidden_ids = function_exists('custausu_menu_hidden_auth_page_ids')
        ? custausu_menu_hidden_auth_page_ids()
        : [];

    $hidden_ids = array_values(array_unique(array_filter(array_map('absint', $hidden_ids))));

    if (empty($hidden_ids)) {
        return $items;
    }

    $hidden_paths = [];

    foreach ($hidden_ids as $page_id) {
        $url = get_permalink($page_id);
        if (is_string($url) && $url !== '') {
            $path = (string) wp_parse_url($url, PHP_URL_PATH);
            $path = $path !== '' ? untrailingslashit($path) : '';
            if ($path !== '') {
                $hidden_paths[] = $path;
            }
        }
    }

    $hidden_paths = array_values(array_unique($hidden_paths));

    $filtered = [];

    foreach ($items as $item) {
        if (function_exists('custausu_menu_is_language_switcher_item') && custausu_menu_is_language_switcher_item($item)) {
            $filtered[] = $item;
            continue;
        }

        $object_id = isset($item->object_id) ? absint($item->object_id) : 0;

        if ($object_id > 0 && in_array($object_id, $hidden_ids, true)) {
            continue;
        }

        $url = isset($item->url) ? (string) $item->url : '';
        if ($url !== '' && !empty($hidden_paths)) {
            $path = (string) wp_parse_url($url, PHP_URL_PATH);
            $path = $path !== '' ? untrailingslashit($path) : '';

            if ($path !== '' && in_array($path, $hidden_paths, true)) {
                continue;
            }
        }

        $filtered[] = $item;
    }

    return $filtered;
}

add_filter('wp_nav_menu_objects', function($items, $args) {

    $items = custausu_menu_prune_auth_service_items(is_array($items) ? $items : []);

    if (!custausu_should_inject_menu($args)) {
        return $items;
    }

    $lang = custausu_detect_lang_from_request();

    // Base URL.
    $home_after_logout = function_exists('custausu_home_url_for_lang')
        ? custausu_home_url_for_lang($lang)
        : home_url('/');

   $login_url = function_exists('custausu_route_url')
        ? custausu_route_url('login', $lang)
        : wp_login_url();

    // Safe negative IDs avoid collisions with real menu item IDs.
    $parent_id = -910001;
    $child_logout_id = -910002;
    $child_profile_id = -910003;
    $login_id = -910004;

    // Logged-in users on classic menus get a My Account parent with child actions.
    if (is_user_logged_in()) {
        $account_id = -910001;
        $edit_profile_id = -910003;
        $logout_id = -910002;

        $account_url = custausu_menu_account_url($lang);
        $account_label = custausu_menu_label('My Account', 'Il mio account', $lang);
        $edit_profile_label = custausu_menu_label('Edit Profile', 'Modifica profilo', $lang);
        $logout_label = custausu_menu_label('Logout', 'Esci', $lang);

        $account_parent_id = $account_id;
        $replaced_login_item = false;

        foreach ($items as $item) {
            if (custausu_menu_is_login_item($item, $login_url)) {
                $item->title = $account_label;
                $item->url = $account_url;
                $item->menu_item_parent = 0;
                $item->classes = array_values(array_unique(array_merge(
                    is_array($item->classes) ? $item->classes : [],
                    ['menu-item', 'menu-item-has-children', 'custausu-menu-account']
                )));

                $account_parent_id = !empty($item->ID) ? (int) $item->ID : (int) $item->db_id;
                if ($account_parent_id === 0) {
                    $account_parent_id = $account_id;
                    $item->ID = $account_id;
                    $item->db_id = $account_id;
                    $item->object_id = $account_id;
                }

                $replaced_login_item = true;
                break;
            }
        }

        if (!$replaced_login_item) {
            $account_item = custausu_make_menu_item([
                'ID' => $account_id,
                'db_id' => $account_id,
                'object_id' => $account_id,
                'title' => $account_label,
                'url' => $account_url,
                'menu_item_parent' => 0,
                'classes' => ['menu-item', 'menu-item-has-children', 'custausu-menu-account'],
            ]);

            array_unshift($items, $account_item);
            $account_parent_id = $account_id;
        }

        $has_edit_profile = false;
        foreach ($items as $item) {
            $title = isset($item->title) ? strtolower(trim(wp_strip_all_tags((string) $item->title))) : '';
            $title = function_exists('remove_accents') ? remove_accents($title) : $title;
            $url = isset($item->url) ? (string) $item->url : '';

            if (
                in_array($title, ['edit profile', 'modifica profilo'], true)
                || strpos($url, 'profile.php') !== false
            ) {
                if ((int) ($item->menu_item_parent ?? 0) === (int) $account_parent_id) {
                    $has_edit_profile = true;
                    break;
                }
            }
        }

        if (!$has_edit_profile) {
            $edit_profile_item = custausu_make_menu_item([
                'ID' => $edit_profile_id,
                'db_id' => $edit_profile_id,
                'object_id' => $edit_profile_id,
                'title' => $edit_profile_label,
                'url' => admin_url('profile.php'),
                'menu_item_parent' => $account_parent_id,
                'classes' => ['menu-item', 'custausu-menu-edit-profile'],
            ]);

            $items[] = $edit_profile_item;
        }

        if (!custausu_menu_has_logout_item($items)) {
            $logout_item = custausu_make_menu_item([
                'ID' => $logout_id,
                'db_id' => $logout_id,
                'object_id' => $logout_id,
                'title' => $logout_label,
                'url' => wp_logout_url($home_after_logout),
                'menu_item_parent' => $account_parent_id,
                'classes' => ['menu-item', 'custausu-menu-logout'],
            ]);

            $items[] = $logout_item;
        }

        return $items;
    }

    // Logged-out users get a Login item only when the menu does not already expose it.
    foreach ($items as $item) {
        if (custausu_menu_is_login_item($item, $login_url)) {
            return $items;
        }
    }

    $login_item = custausu_make_menu_item([
        'ID' => $login_id,
        'db_id' => $login_id,
        'object_id' => $login_id,
        'title' => custausu_menu_label('Login', 'Accesso account', $lang),
        'url' => $login_url,
        'menu_item_parent' => 0,
        'classes' => ['menu-item', 'custausu-menu-login'],
    ]);

    array_unshift($items, $login_item);

    return $items;

}, 10, 2);


/**
 * Render a simple CAS block-navigation list item.
 */
function custausu_menu_block_list_item_html(string $class, string $url, string $label): string {
    return '<li class="wp-block-pages-list__item ' . esc_attr($class) . '">'
        . '<a class="wp-block-pages-list__item__link wp-block-navigation-item__content" href="' . esc_url($url) . '">'
        . esc_html($label)
        . '</a></li>';
}


/**
 * Hidden CAS auth service page paths for HTML fallback pruning.
 */
function custausu_menu_hidden_auth_paths(): array {
    $ids = function_exists('custausu_menu_hidden_auth_page_ids')
        ? custausu_menu_hidden_auth_page_ids()
        : [];

    $paths = [];

    foreach ($ids as $id) {
        $url = get_permalink(absint($id));
        if (!is_string($url) || $url === '') {
            continue;
        }

        $path = (string) wp_parse_url($url, PHP_URL_PATH);
        $path = $path !== '' ? untrailingslashit($path) : '';

        if ($path !== '') {
            $paths[] = $path;
        }
    }

    return array_values(array_unique($paths));
}

/**
 * Remove CAS auth service page links from page-list/fallback HTML.
 */
function custausu_menu_prune_auth_service_links_html(string $html): string {
    if (trim($html) === '') {
        return wp_kses_post($html);
    }

    $hidden_paths = function_exists('custausu_menu_hidden_auth_paths')
        ? custausu_menu_hidden_auth_paths()
        : [];

    $hidden_titles = [
        'registrazione account',
        'recupera password',
        'conferma reset password',
        'account register',
        'lost password',
        'lost password confirmation',
        'confirm password reset',
    ];

    return wp_kses_post((string) preg_replace_callback(
        '~<li\b[^>]*>.*?</li>~is',
        function ($m) use ($hidden_paths, $hidden_titles) {
            $item_html = (string) $m[0];

            if (function_exists('custausu_menu_html_item_is_language_switcher') && custausu_menu_html_item_is_language_switcher($item_html)) {
                return $item_html;
            }

            if (!empty($hidden_paths) && preg_match('~href=(["\'])(.*?)\1~i', $item_html, $hm)) {
                $href = html_entity_decode((string) $hm[2], ENT_QUOTES, get_bloginfo('charset') ?: 'UTF-8');
                $path = (string) wp_parse_url($href, PHP_URL_PATH);
                $path = $path !== '' ? untrailingslashit($path) : '';

                if ($path !== '' && in_array($path, $hidden_paths, true)) {
                    return '';
                }
            }

            $title = strtolower(trim(wp_strip_all_tags($item_html)));
            $title = function_exists('remove_accents') ? remove_accents($title) : $title;

            foreach ($hidden_titles as $hidden_title) {
                if ($title !== '' && strpos($title, $hidden_title) !== false) {
                    return '';
                }
            }

            return $item_html;
        },
        $html
    ));
}


/**
 * Patch core/page-list output for block themes.
 *
 * Block themes can render "all pages" via <!-- wp:page-list /-->, bypassing
 * wp_nav_menu_objects entirely. This keeps CAS usable on default WP themes:
 * logged-out users see the login page, logged-in users see My Account + Logout.
 */
function custausu_menu_filter_page_list_block(string $block_content): string {
    if (trim($block_content) === '') {
        return wp_kses_post($block_content);
    }

    $block_content = function_exists('custausu_menu_prune_auth_service_links_html')
        ? custausu_menu_prune_auth_service_links_html($block_content)
        : $block_content;

    if (!is_user_logged_in()) {
        return wp_kses_post($block_content);
    }

    $lang = custausu_detect_lang_from_request();

    $home_after_logout = function_exists('custausu_home_url_for_lang')
        ? (string) custausu_home_url_for_lang($lang)
        : home_url('/');

    if ($home_after_logout === '') {
        $home_after_logout = home_url('/');
    }

    $login_url = function_exists('custausu_route_url')
        ? (string) custausu_route_url('login', $lang)
        : wp_login_url();

    $account_url = function_exists('custausu_menu_account_url')
        ? custausu_menu_account_url($lang)
        : $home_after_logout;

    $account_label = function_exists('custausu_menu_label')
        ? custausu_menu_label('My Account', 'Il mio account', $lang)
        : 'My Account';

    $logout_label = function_exists('custausu_menu_label')
        ? custausu_menu_label('Logout', 'Esci', $lang)
        : 'Logout';

    $login_path = function_exists('custausu_menu_url_path')
        ? custausu_menu_url_path($login_url)
        : untrailingslashit((string) wp_parse_url($login_url, PHP_URL_PATH));

    $replaced_login = false;

    $block_content = preg_replace_callback(
        '~<a\b([^>]*)href=(["\'])(.*?)\2([^>]*)>(.*?)</a>~is',
        function ($m) use (&$replaced_login, $login_path, $account_url, $account_label) {
            $href = html_entity_decode((string) $m[3], ENT_QUOTES, get_bloginfo('charset') ?: 'UTF-8');
            $href_path = function_exists('custausu_menu_url_path')
                ? custausu_menu_url_path($href)
                : untrailingslashit((string) wp_parse_url($href, PHP_URL_PATH));

            $title = strtolower(trim(wp_strip_all_tags((string) $m[5])));
            $title = function_exists('remove_accents') ? remove_accents($title) : $title;

            $is_login = ($href_path !== '' && $login_path !== '' && $href_path === $login_path)
                || in_array($title, [
                    'login',
                    'account login',
                    'accesso account',
                    'accesso',
                ], true);

            if (!$is_login) {
                return $m[0];
            }

            $replaced_login = true;

            return '<a' . $m[1] . 'href=' . $m[2] . esc_url($account_url) . $m[2] . $m[4] . '>'
                . esc_html($account_label)
                . '</a>';
        },
        $block_content
    );

    if (!$replaced_login && strpos($block_content, 'custausu-menu-account') === false) {
        $account_item = custausu_menu_block_list_item_html('custausu-menu-account', $account_url, $account_label);

        if (preg_match('~<ul\b[^>]*>~i', $block_content, $m, PREG_OFFSET_CAPTURE)) {
            $pos = $m[0][1] + strlen($m[0][0]);
            $block_content = substr($block_content, 0, $pos) . $account_item . substr($block_content, $pos);
        } else {
            $block_content = $account_item . $block_content;
        }
    }

    if (strpos($block_content, 'custausu-menu-logout') === false && strpos($block_content, 'action=logout') === false) {
        $logout_item = custausu_menu_block_list_item_html('custausu-menu-logout', wp_logout_url($home_after_logout), $logout_label);

        if (preg_match('~</ul>\s*$~i', $block_content)) {
            $block_content = preg_replace('~</ul>\s*$~i', $logout_item . '</ul>', $block_content, 1);
        } else {
            $block_content .= $logout_item;
        }
    }

    return wp_kses_post($block_content);
}

add_filter('render_block_core/page-list', function($block_content) {
    return wp_kses_post(custausu_menu_filter_page_list_block((string) $block_content));
}, 30, 1);


/**
 * CAS auth service pages should not appear in automatic page-list menus.
 *
 * These pages are linked from the login/register templates and are not meant
 * to be public navigation items:
 * - register
 * - lost password
 * - lost password confirmation
 */
function custausu_menu_hidden_auth_page_ids(): array {
    $settings = get_option('custausu_global_settings', []);

    if (!is_array($settings)) {
        return [];
    }

    $routes_page_ids = isset($settings['routes_page_ids']) && is_array($settings['routes_page_ids'])
        ? $settings['routes_page_ids']
        : [];

    $hide_keys = ['register', 'lostpassword', 'lostpassword_confirm'];
    $ids = [];

    foreach ($routes_page_ids as $lang_routes) {
        if (!is_array($lang_routes)) {
            continue;
        }

        foreach ($hide_keys as $key) {
            $id = isset($lang_routes[$key]) ? absint($lang_routes[$key]) : 0;
            if ($id > 0) {
                $ids[] = $id;
            }
        }
    }

    $ids = array_values(array_unique(array_filter($ids)));

    return $ids;
}

/**
 * Hide CAS technical auth pages from automatic page-list outputs.
 *
 * This affects wp_page_menu() / wp_list_pages() fallbacks and themes that
 * rely on automatic page lists when no custom menu is selected.
 */
add_filter('wp_list_pages_excludes', function($exclude) {
    $exclude = is_array($exclude) ? array_map('absint', $exclude) : [];
    $custausu_exclude = function_exists('custausu_menu_hidden_auth_page_ids')
        ? custausu_menu_hidden_auth_page_ids()
        : [];

    return array_values(array_unique(array_merge($exclude, $custausu_exclude)));
}, 20);

/**
 * Classic fallback page menus do not pass through wp_nav_menu_objects.
 * When logged in, post-process their HTML with the same account/logout logic
 * used for block page-list navigation.
 */
add_filter('wp_page_menu', function($menu) {
    if (!is_user_logged_in()) {
        return wp_kses_post((string) $menu);
    }

    return function_exists('custausu_menu_filter_page_list_block')
        ? wp_kses_post(custausu_menu_filter_page_list_block((string) $menu))
        : wp_kses_post((string) $menu);
}, 20);

/* WPORG-06G-KADENCE-FALLBACK-LATE-PRUNE */
if (!function_exists('custausu_menu_prune_auth_service_page_menu_late')) {
    /**
     * Final fallback pruning after themes rewrite wp_page_menu() markup.
     *
     * Reuses the existing CAS HTML pruner, including its Polylang guards.
     */
    function custausu_menu_prune_auth_service_page_menu_late($menu, $args = []): string {
        $menu = is_string($menu) ? $menu : '';

        if (
            $menu === '' ||
            !function_exists('custausu_menu_prune_auth_service_links_html')
        ) {
            return wp_kses_post($menu);
        }

        return wp_kses_post(custausu_menu_prune_auth_service_links_html($menu));
    }
}

add_filter(
    'wp_page_menu',
    'custausu_menu_prune_auth_service_page_menu_late',
    999,
    2
);

