<?php


namespace Eventman\Admin;

use Eventman\Includes\Post\CustomPostType;
use Eventman\Includes\Post\ImageGallery;
use Eventman\Includes\Views\CustomPostTypeViewBuilder;
use LS_Sliders;
use threewp_broadcast\api\api;
use WP_Error;
use WP_Site;
use WP_User;

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       http://example.com
 * @since      1.0.0
 *
 * @package    MS_Eventman
 * @subpackage MS_Eventman/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    MS_Eventman
 * @subpackage MS_Eventman/admin
 * @author     Your Name <email@example.com>
 */
class MsEventmanAdmin
{

    use LogTrait;

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $ms_eventman The ID of this plugin.
     */
    private $ms_eventman;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @param string $ms_eventman The name of this plugin.
     * @param string $version The version of this plugin.
     * @since    1.0.0
     */
    public function __construct($ms_eventman, $version)
    {
        $this->ms_eventman = $ms_eventman;
        $this->version = $version;

    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueueStyles()
    {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in MsEventmanLoader as all of the hooks are defined
         * in that particular class.
         *
         * The MsEventmanLoader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_style($this->ms_eventman, plugin_dir_url(__FILE__) . 'css/ms-eventman-admin.css', array(), $this->version, 'all');

        wp_enqueue_style('datetimepicker', plugin_dir_url(__FILE__) . 'css/jquery.datetimepicker.min.css');

        $current_screen = get_current_screen();
        if ($current_screen->base == 'post' && $current_screen->id == 'exhibitors') {
            wp_enqueue_script('gallery', plugin_dir_url(__FILE__) . 'js/gallery.js', ['jquery', 'jquery-ui-core'] );
        }
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueueScripts()
    {
        wp_enqueue_script($this->ms_eventman, plugin_dir_url(__FILE__) . 'js/ms-eventman-admin.js', array('jquery','mpt-featured-image'), $this->version, false);

        wp_enqueue_script('admin-script', plugin_dir_url(__FILE__) . 'js/jquery.datetimepicker.full.js');
    }

    /**
     * The plugin requires the elision qode plugin.
     */
    public function requireElision()
    {
        if (is_admin() && current_user_can('activate_plugins') && !is_plugin_active('elision-core/elision-core.php')) {
            add_action('admin_notices', 'requireElisionNotice');

            deactivate_plugins(plugin_basename(__FILE__));

            if (isset($_GET['activate'])) {
                unset($_GET['activate']);
            }
        }
    }

    /**
     * Create a notice to require the elision qode plugin.
     */
    public function requireElisionNotice()
    {
        echo '<div class="error"><p>' . __('This Plugin depends on the Elision Core Plugin. Please install this first before activating this plugin.', 'ms-eventman') . '</p></div>';
    }

    /**
     * Hide Activation link if a a file is not the plugin root.
     * @param $links
     * @param $file
     * @return mixed
     */
    public function disableActivationLink($links, $file)
    {
        if ('ms-eventman/ms-eventman.php' == $file and isset($links['activate'])) {
            $links['activate'] = '<span>Activate</span>';
        }

        return $links;
    }

    /**
     * Apply changes to the admin menu.
     */
    public function adminMenu()
    {
        $this->removeCreatePostForCustomPostTypes();
        $this->customizeMenuItemsEventCategories();
        $this->addEventsMenuItem();
        $this->removeUnusedMenuItems();
        $this->addFullExhibitorOverviewToSites();
    }

    public function networkMenu($context) {
        $this->addEventmanOptions();
    }

    /**
     * Disable create post for exhibitors and partners on non-main sites.
     */
    public function removeCreatePostForCustomPostTypes()
    {
        if (!is_main_site()) {
            remove_submenu_page('edit.php?post_type=exhibitors', "post-new.php?post_type=exhibitors");
            remove_submenu_page('edit.php?post_type=partners', "post-new.php?post_type=partners");
        }
    }

    /**
     * Create metabox for the gallery for exhibitors.
     */
    public function addGalleryMetaBox()
    {
        add_meta_box(
            'post_gallery',
            _x('Gallery Pictures', 'ms-eventman'),
            [new ImageGallery(), 'imageGallery'],
            'exhibitors',
            'normal',
            'default'
        );
    }

    /**
     * Save meta fields when saving an exhibitor.
     */
    public function saveExhibitorsForSite()
    {
        $blog_id = $_POST['id'];
        check_admin_referer('siteExhibitorsCheck' . $blog_id); // security check

        $api = new api();
        switch_to_blog(get_main_site_id());
        $broadcastPostIds = [];
        if ($_POST['broadcast']) {
            $broadcastPostIds = array_keys($_POST['broadcast']);
        }

        // unlink all deselected
//        switch_to_blog($blog_id);
//        $posts = get_posts([
//            'post_type' => 'exhibitors',
//            'post_status' => array_filter(
//                CustomPostType::allStatuses(),
//                function ($s) {
//                    return $s != 'trash';
//                })
//        ]);
//        foreach ($posts as $post) {
//            $controller = $api->linking($post->ID);
//            if ($controller->is_child() && !in_array($controller->parent(), $broadcastPostIds)) {
//                $postId = $controller->parent()['post_id'];
//                switch_to_blog(get_main_site_id());
//                $api->unlink($postId, [$blog_id]);
//                restore_current_blog();
//            }
//        }
//        restore_current_blog();
//
//        foreach ($broadcastPostIds as $postId) {
//            $api->broadcast_children($postId, [$blog_id]);
//        }

        wp_redirect(add_query_arg([
            'page' => 'exhibitors',
            'id' => $blog_id,
            'updated' => 'true'], network_admin_url('sites.php')
        ));
    }

    /**
     * Save meta fields when saving a partner.
     */
    public function savePartnersForSite()
    {
        $blog_id = $_POST['id'];
        check_admin_referer('sitePartnersCheck' . $blog_id); // security check

        $api = new api();
        switch_to_blog(get_main_site_id());
        $broadcastPostIds = [];
        if ($_POST['broadcast']) {
            $broadcastPostIds = array_keys($_POST['broadcast']);
        }

        // unlink all deselected
        switch_to_blog($blog_id);
        $posts = get_posts([
            'post_type' => 'partners',
            'post_status' => array_filter(
                CustomPostType::allStatuses(),
                function ($s) {
                    return $s != 'trash';
                })
        ]);
        foreach ($posts as $post) {
            $controller = $api->linking($post->ID);
            if ($controller->is_child() && !in_array($controller->parent(), $broadcastPostIds)) {
                $blogId = $controller->parent()['blog_id'];
                $postId = $controller->parent()['post_id'];
                switch_to_blog(get_main_site_id());
                $api->unlink($postId, [$blog_id]);
                restore_current_blog();
            }
        }
        restore_current_blog();

        foreach ($broadcastPostIds as $postId) {
            $api->broadcast_children($postId, [$blog_id]);
        }

        wp_redirect(add_query_arg(array(
            'page' => 'partners',
            'id' => $blog_id,
            'updated' => 'true'), network_admin_url('sites.php')
        ));
    }

    /**
     * Echo a HTML page listing the partners in the network.
     */
    public function siteInfoExhibitors()
    {
        echo CustomPostTypeViewBuilder::broadcastTablePage("exhibitors");
    }

    /**
     * Echo a HTML page listing the partners in the network.
     */
    public function siteInfoPartners()
    {
        echo CustomPostTypeViewBuilder::broadcastTablePage("partners");
    }

    /**
     * Remove Event submenu from exhibitor and partner items.
     */
    public function customizeMenuItemsEventCategories()
    {
        remove_submenu_page('edit.php?post_type=exhibitors', 'edit-tags.php?taxonomy=events&amp;post_type=exhibitors');
        remove_submenu_page('edit.php?post_type=partners', 'edit-tags.php?taxonomy=events&amp;post_type=partners');
    }

    /**
     * Create a 'Events' menu item.
     */
    public function addEventsMenuItem()
    {
        if (!is_main_site()) {
            add_menu_page(__("Events", 'ms-eventman'), __("Events", 'ms-eventman'), "manage_categories", "edit-tags.php?taxonomy=events", "", "dashicons-schedule", 4);
        }
    }

    /**
     * Reorder the admin menu to place custom types on top.
     * @param $order
     * @return array
     */
    public function reorderMenu($order)
    {
        $idx = array_search("separator1", $order) + 1;
        $tail = array_splice($order, $idx, sizeof($order) - $idx);

        $cpts = [
            "edit-tags.php?taxonomy=events",    // "Events"
            "edit.php?post_type=exhibitors",    // "Exhibitors"
            "edit.php?post_type=partners",      // "Partners"
            "separator2"
        ];
        $defaultPosts = [
            'edit.php?post_type=page',          // "Pages"
            'edit.php',                         // "Posts"
            'upload.php',                       // "Media"
            'edit-comments.php',                // "Comments"
            "gf_edit_forms",
            'edit.php?post_type=portfolio_page',
            'edit.php?post_type=testimonials',
            'edit.php?post_type=slides',        // "Qode Slider"
            'edit.php?post_type=carousels',     // "Qode Carousel"
            'themes.php'
        ];
        foreach (array_merge($cpts, $defaultPosts) as $page) {
            array_splice($tail, array_search($page, $tail), 1);
        }

        return array_merge($order, $cpts, $defaultPosts, $tail);
    }

    /**
     * returns true.
     * @return bool returns true.
     */
    public function returnTrue()
    {
        return true;
    }

    /**
     * Set the active menu item to 'Events' if selected.
     * @param $file string the filename
     * @return string the filename
     */
    public function setActiveMenuItemOnEventsTaxonomy($file)
    {
        global $pagenow;
        global $parent_file;
        global $plugin_page;
        global $submenu_file;

        if (strcasecmp($pagenow, 'edit-tags.php') == 0 && strcasecmp($_GET['taxonomy'], 'events') == 0
            || strcasecmp($pagenow, 'term.php') == 0 && strcasecmp($_GET['taxonomy'], 'events') == 0) {
            $parent_file = "edit-tags?taxonomy=events";
            $plugin_page = $parent_file;
            $submenu_file = $parent_file;
            $file = $parent_file;
        }
        return $file;
    }

    /**
     * Add JS for dynamic menu selection.
     */
    public function eventsPageScript()
    {
        global $pagenow;
        if (strcasecmp($pagenow, 'edit-tags.php') == 0 && strcasecmp($_GET['taxonomy'], 'events') == 0
            || strcasecmp($pagenow, 'term.php') == 0 && strcasecmp($_GET['taxonomy'], 'events') == 0) {
            echo '<script>
                    (function($) {
                        $(window).load(function() {
                            let item = $("#toplevel_page_edit-tags-taxonomy-events");
                            item.removeClass("wp-not-current-submenu");
                            item.addClass("wp-has-current-submenu");
                            $(item[0].children[0]).removeClass("wp-not-current-submenu");
                            $(item[0].children[0]).addClass("wp-has-current-submenu");
                        });
                    })(jQuery);
                </script>';
        }
    }

    /**
     * Apply default settings, menus, etc. when a new site is created.
     * @param WP_Site $site
     * @param $args
     */
    public function addDefaultsToNewSite(WP_Site $site, $args)
    {
        switch_to_blog($site->blog_id);

        $themeName = 'elision-child';
        foreach (wp_get_themes() as $id => $theme) {
            if ($theme->parent() && $theme->parent()->get('Name') == 'Elision') {
                $themeName = $id;
                break;
            }
        }

        // set theme, enables qode and others
        switch_theme($themeName);
        switch_to_blog(get_main_site_id());

        // get the home page
        $page = get_page_by_title('Home');

        if (!empty($page)) {
            $page = is_array($page) ? (object) $page : $page;
            // init broadcast
            $api = new api();
            // broadcast common homepage
            $homepageId = $page->ID;
            $api->broadcast_children($homepageId, [$site->blog_id]);
            switch_to_blog($site->blog_id);

            // set homepage for new site to be static on the broadcasted page above
            $page = get_page_by_title('Home');
            update_option('page_on_front', $homepageId);
            update_option('show_on_front', 'page');
            restore_current_blog();
        }

        switch_to_blog($site->blog_id);


        // set default qode options
        $qodeOptionsKey = 'qode_options_elision';
        $qodeOptions = get_option($qodeOptionsKey, []);

        global $my_Qode_Import;
        $my_Qode_Import->file_options('options.txt');
        $defaultQodeOptions = $my_Qode_Import->file_options('options.txt');

        $customOptions = [
            'page_transitions' => '0',
            'boxed' => 'no',
            'loading_animation' => 'on',
            'smooth_scroll' => 'no',
            'responsiveness' => 'yes',
            'show_back_button' => 'no',
            'elements_animation_on_touch' => 'no',
            'disable_qode_seo' => 'no',
            'h1_fontsize' => '24',
            'h2_fontsize' => '22',
            'h3_fontsize' => '18',
            'h4_fontsize' => '16',
            'h5_fontsize' => '12',
            'h6_fontsize' => '10',
            'page_title_fontsize' => '23',
            'header_in_grid' => 'no',
            'header_top_area' => 'no',
            'header_sticky' => 'no',
            'menu_in_center' => 'no',
            'logo_animation' => 'no',
            'center_logo_image' => 'no',
            'scroll_amount_for_sticky' => '100',
            'title_style' => 'title_on_bottom',
            'responsive_title_image' => 'no',
            'fixed_title_image' => 'no',
            'page_title_position' => '0',
            'footer_in_grid' => 'no',
            'show_footer_top' => 'yes',
            'footer_top_columns' => '1',
            'footer_text' => 'yes',
            'footer_top_background_color' => '#ffffff',
            'button_title_google_fonts' => '-1',
            'message_title_google_fonts' => '-1',
            'enable_content_bottom_area' => 'yes',
            'content_bottom_in_grid' => 'no',
            'parallax_onoff' => 'on',
            'portfolio_style' => '1',
            'portfolio_qode_like' => 'on',
            'lightbox_single_project' => 'no',
            'portfolio_columns_number' => '2',
            'portfolio_single_sidebar' => 'default',
            'pagination' => '1',
            'blog_style' => '2',
            'category_blog_sidebar' => 'default',
            'blog_hide_comments' => 'yes',
            'qode_like' => 'off',
            'number_of_chars' => '45',
            'blog_single_sidebar' => 'default',
            'blog_author_info' => 'no',
            'enable_contact_form' => 'no',
            'hide_contact_form_website' => 'no',
            'use_recaptcha' => 'no',
            'enable_google_map' => 'no',
            'enable_social_share' => 'yes',
            'enable_facebook_share' => 'yes',
            'enable_twitter_share' => 'yes',
            'enable_google_plus' => 'no',
            'enable_linkedin' => 'yes',
            'enable_tumblr' => 'no',
            'enable_pinterest' => 'yes',
            'enable_vk' => 'no',
            'facebook_icon' => plugin_dir_url(__FILE__) . 'img/facebook.svg',
            'twitter_icon' => plugin_dir_url(__FILE__) . 'img/twitter.svg',
            'pinterest_icon' => plugin_dir_url(__FILE__) . 'img/pinterest.svg',
            'linkedin_icon' => plugin_dir_url(__FILE__) . 'img/linkedin.svg',
            'favicon_image' => '',
            'google_analytics_code' => '',
            'custom_css' => '',
            'title_image' => '',
            'enable_side_area' => 'no',
            'post_types_names_exhibitors' => 'exhibitors',
            'post_types_names_partners' => 'partners'
        ];

        update_option($qodeOptionsKey, array_merge($defaultQodeOptions, $customOptions));

        // create menus
        $mainMenuId = wp_create_nav_menu(__('Main Menu'));
        $rightTopMenuId = wp_create_nav_menu(__('Right Top Menu'));
        $leftTopMenuId = wp_create_nav_menu(__('Left Top Menu'));
        $socialMenuId = wp_create_nav_menu(__('Social Media Top Menu'));

        if (!($mainMenuId instanceof WP_Error)) {
            $topNav = 'top-navigation';
            $this->setMenuLocation($topNav, $mainMenuId);
            wp_update_nav_menu_item($mainMenuId, 0, [
                'menu-item-title' => 'Home',
                'menu-item-url' => get_home_url(),
                'menu-item-status' => 'publish'
            ]);
        }
        if (!($leftTopMenuId instanceof WP_Error)) {
            $topAddNav = 'top-additional-navigation-left';
            $this->setMenuLocation($topAddNav, $leftTopMenuId);
            $postId = wp_update_nav_menu_item($leftTopMenuId, 0, [
                'menu-item-title' => 'Home',
                'menu-item-url' => get_home_url(),
                'menu-item-status' => 'publish'
            ]);
            update_post_meta($postId, '_menu_item_icon', 'fa-home');
        }
        if (!($rightTopMenuId instanceof WP_Error)) {
            $topAddNav = 'top-additional-navigation';
            $this->setMenuLocation($topAddNav, $rightTopMenuId);
            wp_update_nav_menu_item($rightTopMenuId, 0, [
                'menu-item-title' => 'Tickets',
                'menu-item-classes' => 'button',
                'menu-item-url' => get_home_url(),
                'menu-item-status' => 'publish'
            ]);
        }
        if (!($socialMenuId instanceof WP_Error)) {
            $socNav = 'top-social-navigation';
            $this->setMenuLocation($socNav, $socialMenuId);

            $socials = ['Instagram' => 'fab fa-instagram', 'Twitter' => 'fab fa-twitter-square', 'Facebook' => 'fab fa-facebook-square', 'YouTube' => 'fab fa-youtube-square'];
            foreach ($socials as $socialName => $icon) {
                $postId = wp_update_nav_menu_item($socialMenuId, 0, [
                    'menu-item-title' => $socialName,
                    'menu-item-url' => get_home_url(),
                    'menu-item-status' => 'publish'
                ]);
                update_post_meta($postId, '_menu_item_icon', $icon);
            }
        }

        restore_current_blog();
    }

    /**
     * Create new View settings.
     */
    public function registerSettings()
    {
        $this->registerCptArchiveOptions();
    }

    /**
     * Intercept certain license notices.
     */
    public function interceptPluginActions()
    {
        global $wp_filter;

        foreach ($wp_filter['admin_notices']->callbacks as $priority => $notice) {
            foreach ($notice as $key => $value) {
                if (strpos($key, 'adminNoticeLicenseActivation') !== false) {
                    unset($notice[$key]);
                }
            }
            $wp_filter['admin_notices']->callbacks[$priority] = $notice;
        }
    }

    /**
     * Remove redundant dashboard panels and add new panels.
     */
    public function dashboardSetup()
    {
        $dash = new Dashboard();
        remove_action('welcome_panel', 'wp_welcome_panel');

        if (!is_main_site()) {
            add_meta_box(
                'dashboard_widget_guide_events',
                '<i class="dashicons dashicons-schedule"></i> ' . esc_html__('Events', 'ms-eventman'),
                [$dash, 'guideEvents'],
                'dashboard',
                'side',
                'high'
            );
        }
        add_meta_box(
            'dashboard_widget_guide_exhibitors',
            '<i class="dashicons dashicons-visibility"></i> ' . esc_html__('Exhibitors', 'ms-eventman'),
            [$dash, 'guideExhibitors'],
            'dashboard',
            'side',
            'high'
        );
        add_meta_box(
            'dashboard_widget_guide_partners',
            '<i class="dashicons dashicons-admin-users"></i> ' . esc_html__('Partners', 'ms-eventman'),
            [$dash, 'guidePartners'],
            'dashboard',
            'side',
            'high'
        );
        add_meta_box(
            'dashboard_widget_guide_news',
            '<i class="dashicons dashicons-admin-post"></i> ' . esc_html__('Posts', 'ms-eventman'),
            [$dash, 'guideNews'],
            'dashboard',
            'side',
            'high'
        );
    }

    /**
     * Set the location of a menu.
     * @param string $nav
     * @param $mainMenuId
     */
    public function setMenuLocation(string $nav, $mainMenuId)
    {
        $locations = get_registered_nav_menus();
        $menu_locations = get_nav_menu_locations();
        if (isset($locations[$nav])) {
            $menu_locations[$nav] = $mainMenuId;
        }
        set_theme_mod('nav_menu_locations', $menu_locations);
    }

    /**
     * Remove redundant Qode slides and Carousel post types.
     */
    public function removeUnusedMenuItems()
    {
        remove_menu_page('edit.php?post_type=slides');
        remove_menu_page('edit.php?post_type=carousels');
    }

    /**
     * Add a publish field to the events taxonomy.
     * @param $columns
     * @return mixed
     */
    public function addEventPublishColumn($columns)
    {
        $columns['published'] = __("Published", "ms-eventman");
        return $columns;
    }

    /**
     * Manage the Events table columns.
     *
     * Add a 'publish' column.
     *
     * @param $out
     * @param $columnName
     * @param $termId
     * @return string
     */
    public function manageEventListColumns($out, $columnName, $termId)
    {
        switch ($columnName) {
            case 'published':
                $checked = get_term_meta($termId, 'publish', true) === 'on' ? 'checked="checked"' : '';
                $out .= sprintf('<input type="checkbox" %s disabled />', $checked);
                break;
            default:
                break;
        }

        return $out;
    }

    /**
     * Add archive options for Exhibitors and Partners in the Read options.
     */
    protected function registerCptArchiveOptions()
    {
        $exhibitorOptionName = 'exhibitors_archive_page';
        $partnerOptionName = 'partners_archive_page';
        register_setting(
            'reading',
            $exhibitorOptionName,
            [
                'type' => 'string',
                'sanitize_callback' => 'sanitize_text_field',
                'default' => NULL
            ]);
        register_setting(
            'reading',
            $partnerOptionName,
            [
                'type' => 'string',
                'sanitize_callback' => 'sanitize_text_field',
                'default' => NULL
            ]);
        register_setting(
            'reading',
            'location_page',
            [
                'type' => 'string',
                'sanitize_callback' => 'sanitize_text_field',
                'default' => NULL
            ]);

        add_settings_field(
            $exhibitorOptionName,
            __('Exhibitors', 'ms-eventman') . ' ' . __("Archive", "ms-eventman") . ' ' . __("Page", "ms-eventman"),
            [&$this, 'exhibitorsArchiveSettingsPage'],
            'reading',
            'default',
            [
                'label_for' => $exhibitorOptionName
            ]);
        add_settings_field(
            $partnerOptionName,
            __('Partners', 'ms-eventman') . ' ' . __("Archive", "ms-eventman") . ' ' . __("Page", "ms-eventman"),
            [&$this, 'partnersArchiveSettingsPage'],
            'reading',
            'default',
            [
                'label_for' => $partnerOptionName
            ]);
        add_settings_field(
            $partnerOptionName,
            __('Location', 'ms-eventman') . __("Page", "ms-eventman"),
            [&$this, 'locationPageSetting'],
            'reading',
            'default',
            [
                'label_for' => 'location_page'
            ]);
    }

    public function exhibitorsArchiveSettingsPage($args)
    {
        $type = 'exhibitors';
        $this->archiveOptions($args, $type);
    }

    public function partnersArchiveSettingsPage($args)
    {
        $type = 'partners';
        $this->archiveOptions($args, $type);
    }

    public function locationPageSetting($args)
    {
        $pageId = get_option('location_page');

        $args = array(
            'posts_per_page' => -1,
            'orderby' => 'name',
            'order' => 'ASC',
            'post_type' => 'page',
        );
        $items = get_posts($args);

        echo '<select id="location_page" name="location_page">';
        // empty option as default
        echo '<option value="0">' . __('— Select —', 'wordpress') . '</option>';

        // foreach page we create an option element, with the post-ID as value
        foreach ($items as $item) {

            // add selected to the option if value is the same as $project_page_id
            $selected = ($pageId == $item->ID) ? 'selected="selected"' : '';

            echo '<option value="' . $item->ID . '" ' . $selected . '>' . $item->post_title . '</option>';
        }

        echo '</select>';
    }

    /**
     * @param $args
     * @param string $type
     */
    protected function archiveOptions($args, string $type)
    {
        $pageId = get_option($type . '_archive_page');

        $args = array(
            'posts_per_page' => -1,
            'orderby' => 'name',
            'order' => 'ASC',
            'post_type' => 'page',
        );
        $items = get_posts($args);

        echo '<select id="' . $type . '_archive_page" name="' . $type . '_archive_page">';
        // empty option as default
        echo '<option value="0">' . __('— Select —', 'wordpress') . '</option>';

        // foreach page we create an option element, with the post-ID as value
        foreach ($items as $item) {

            // add selected to the option if value is the same as $project_page_id
            $selected = ($pageId == $item->ID) ? 'selected="selected"' : '';

            echo '<option value="' . $item->ID . '" ' . $selected . '>' . $item->post_title . '</option>';
        }

        echo '</select>';
    }

    public function addCustomPostStates($states)
    {
        global $post;

        // get saved project page ID
        $exhibitorsPageId = get_option('exhibitors_archive_page');
        $partnersPageId = get_option('partners_archive_page');

        // add our custom state after the post title only,
        // if post-type is "page",
        // "$post->ID" matches the "$exhibitorsPageId",
        // and "$exhibitorsPageId" is not "0"
        if (is_object($post)) {
            if ('page' == get_post_type($post->ID) && $post->ID == $exhibitorsPageId && $exhibitorsPageId != '0') {
                $states[] = __('Exhibitors Overview', 'ms-eventman');
            } elseif ('page' == get_post_type($post->ID) && $post->ID == $partnersPageId && $partnersPageId != '0') {
                $states[] = __('Partners Overview', 'ms-eventman');
            }
        }

        return $states;
    }

    /**
     * Add a favicon to the admin menu.
     */
    public function addFavicon()
    {
        global $qode_options_elision;
        $favicon = $qode_options_elision['favicon_image'];
        echo '<link rel="shortcut icon" href="' . $favicon . '" />';
    }

    /**
     * Add a Broadcasts submenu to non-main sites under Partners and Exhibitors.
     */
    private function addFullExhibitorOverviewToSites()
    {
        if (!is_main_site()) {
            $this->log('Adding broadcast pages to exhibitors and partners.');
            add_submenu_page(
                'edit.php?post_type=exhibitors',
                _x('Edit', 'ms-eventman') . ' ' . _x("Exhibitors", 'ms-eventman'),
                _x('Broadcasts', 'ms-eventman'),
                'manage_network_options',
                'broadcast_exhibitors',
                [$this, 'siteInfoExhibitors']
            );
            add_submenu_page(
                'edit.php?post_type=partners',
                _x('Broadcast', 'ms-eventman') . ' ' . _x("Partners", 'ms-eventman'),
                _x('Broadcasts', 'ms-eventman'),
                'manage_network_options',
                'broadcast_partners',
                [$this, 'siteInfoPartners']
            );
//            add_submenu_page(
//                'edit.php?post_type=page',
//                _x('Broadcast', 'ms-eventman') . ' ' . _x("Partners", 'ms-eventman'),
//                _x('Broadcasts', 'ms-eventman'),
//                'manage_network_options',
//                'broadcast_page',
//                function() {
//                    echo CustomPostTypeViewBuilder::broadcastTablePage("page");
//                }
//            );
        }
    }

    private function addEventmanOptions()
    {
        $this->log('Adding Network menu options.');
        $opts = new Options();
        add_menu_page(
            __("Eventmanager Options"),
            __("Eventmanager Options"),
            'manage_network',
            'ms-eventman-options',
            [$opts, 'displayOptions'],
            'dashicons-admin-tools'
        );
        add_submenu_page(
            'ms-eventman-options',
            __("Logs"),
            __("Logs"),
            'manage_network',
            'ms-eventman-logs',
            [$opts, 'displayLogs']
        );
    }

    public function navEdit()
    {
        global $pagenow;

        if ($pagenow === 'nav-menus.php') {
            $navEdit = new NavEdit();
            add_action('admin_enqueue_scripts', [$navEdit, 'enqueue_styles_and_scripts']);
        }
    }

}
