<?php

/**
 * Code Manager admin page
 *
 * @package .
 */
use Code_Manager\Code_Manager_Dashboard;
use Code_Manager\Code_Manager_List_View;
use Code_Manager\Code_Manager_Model;
use Code_Manager\Code_Manager_Settings;
use Code_Manager\Code_Manager_Tabs;
/**
 * Class Code_Manager_Admin
 *
 * Defines admin specific functionality for the Code Manager.
 *
 * @author  Peter Schulz
 * @since   1.0.0
 */
class Code_Manager_Admin {
    // SAVING SPACE - According to the plugin guideliness it is allowed to include external fonts:
    // https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/#8-plugins-may-not-send-executable-code-via-third-party-systems
    const CDN_FONTAWESOME = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/';

    const PAGE_MAIN = 'code_manager';

    const PAGE_TAB = 'code_manager_tab';

    const PAGE_SETTINGS = 'code_manager_settings';

    /**
     * Current page (menu slug)
     *
     * @var null|string
     */
    protected $page = null;

    /**
     * Handle to list view
     *
     * @var Code_Manager\Code_Manager_List_View
     */
    protected $cm_list_view = null;

    /**
     * Code_Manager_Admin constructor.
     *
     * Checks if WP Data Access is available to add additional features.
     *
     * @since   1.0.0
     */
    public function __construct() {
        if ( isset( $_REQUEST['page'] ) ) {
            $this->page = sanitize_text_field( wp_unslash( $_REQUEST['page'] ) );
            // input var okay.
        }
    }

    /**
     * Add stylesheets to back-end
     *
     * Only added when Code Manager is visible. Adds minimal CSS depending on actual page (menu slug).
     *
     * @since   1.0.0
     */
    public function enqueue_styles() {
        if ( self::PAGE_MAIN === $this->page ) {
            // Code Manager list mode.
            wp_enqueue_style( 'wp-codemirror' );
            if ( isset( $_REQUEST['action'] ) && ('new' === $_REQUEST['action'] || 'edit' === $_REQUEST['action']) ) {
                // Code Manager data entry form.
                wp_enqueue_style(
                    'code_manager',
                    plugins_url( '../assets/css/code_manager.css', __FILE__ ),
                    array(),
                    CODE_MANAGER_VERSION
                );
            }
            $this->load_global_css();
        } elseif ( self::PAGE_TAB === $this->page ) {
            // Code Manager tab mode.
            wp_enqueue_style( 'wp-codemirror' );
            wp_enqueue_style(
                'code_manager_tabmode',
                plugins_url( '../assets/css/code_manager_tabmode.css', __FILE__ ),
                array(),
                CODE_MANAGER_VERSION
            );
            $this->load_global_css();
        } elseif ( self::PAGE_SETTINGS === $this->page ) {
            // Code Manager settings page.
            wp_enqueue_style(
                'code_manager_settings',
                plugins_url( '../assets/css/code_manager_settings.css', __FILE__ ),
                array(),
                CODE_MANAGER_VERSION
            );
            $this->load_global_css();
        }
    }

    /**
     * Adds CSS needed by all Code Manager pages
     *
     * @since   1.0.0
     */
    protected function load_global_css() {
        // Dashboard CSS.
        wp_enqueue_style(
            'code_manager_dashboard',
            plugins_url( '../assets/css/code_manager_dashboard.css', __FILE__ ),
            array(),
            CODE_MANAGER_VERSION
        );
        // Global Code Manager styling.
        wp_enqueue_style(
            'code_manager_global',
            plugins_url( '../assets/css/code_manager_global.css', __FILE__ ),
            array(),
            CODE_MANAGER_VERSION
        );
        // Add tooltips to add Code Manager pages.
        wp_enqueue_style(
            'code_manager_tooltip_css',
            plugins_url( '../assets/css/jquery-ui.min.css', __FILE__ ),
            array(),
            CODE_MANAGER_VERSION
        );
        // SAVING SPACE - According to the plugin guideliness it is allowed to include external fonts:
        // https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/#8-plugins-may-not-send-executable-code-via-third-party-systems .
        // Load fontawesome icons.
        wp_enqueue_style(
            'cm_fontawesome_icons',
            self::CDN_FONTAWESOME . 'fontawesome.min.css',
            array(),
            null
        );
        wp_enqueue_style(
            'cm_fontawesome_icons_solid',
            self::CDN_FONTAWESOME . 'solid.min.css',
            array(),
            null
        );
    }

    /**
     * Add scripts to back-end
     *
     * Only added when Code Manager is visible. Adds relevant JS only depending on action and tabmode.
     *
     * @since   1.0.0
     */
    public function enqueue_scripts() {
        if ( self::PAGE_MAIN === $this->page || self::PAGE_TAB === $this->page ) {
            // Code Manager list + tab mode.
            $this->load_global_js();
            // Register codeEditor (PHP = default editor, can be overridden on user request).
            $cm_settings['codeEditor'] = wp_enqueue_code_editor( array(
                'type'       => 'application/x-httpd-php',
                'codemirror' => array(
                    'lineNumbers'  => true,
                    'autoRefresh'  => true,
                    'mode'         => 'php',
                    'lineWrapping' => true,
                ),
            ) );
            wp_enqueue_script( 'wp-theme-plugin-editor' );
            wp_localize_script( 'wp-theme-plugin-editor', 'cm_settings', $cm_settings );
            if ( isset( $_REQUEST['action'] ) && ('new' === $_REQUEST['action'] || 'edit' === $_REQUEST['action']) ) {
                // Code Manager data entry form.
                wp_enqueue_script(
                    'code_manager',
                    plugins_url( '../assets/js/code_manager.js', __FILE__ ),
                    array(),
                    CODE_MANAGER_VERSION,
                    true
                );
            } elseif ( self::PAGE_TAB === $this->page ) {
                // Code Manager tab mode.
                wp_enqueue_script(
                    'code_manager_tabmode',
                    plugins_url( '../assets/js/code_manager_tabmode.js', __FILE__ ),
                    array(),
                    CODE_MANAGER_VERSION,
                    true
                );
            } else {
                // Code Manager list mode.
                wp_enqueue_script(
                    'code_manager_listmode',
                    plugins_url( '../assets/js/code_manager_listmode.js', __FILE__ ),
                    array(),
                    CODE_MANAGER_VERSION,
                    true
                );
            }
            // Message.
            wp_enqueue_script(
                'code_manager_message',
                plugins_url( '../assets/js/code_manager_message.js', __FILE__ ),
                array(),
                CODE_MANAGER_VERSION,
                true
            );
            // Enqueue clipboard.
            wp_enqueue_script( 'clipboard' );
            // Register external library notify.js.
            wp_enqueue_script(
                'code_manager_notify',
                plugins_url( '../assets/js/notify.min.js', __FILE__ ),
                array('jquery'),
                CODE_MANAGER_VERSION,
                true
            );
        } elseif ( self::PAGE_SETTINGS === $this->page ) {
            $this->load_global_js();
        }
    }

    /**
     * Load global JS library files
     *
     * @return void
     */
    protected function load_global_js() {
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'jquery-ui-core' );
        wp_enqueue_script( 'jquery-ui-dialog' );
        wp_enqueue_script( 'jquery-ui-tooltip' );
        wp_enqueue_script( 'jquery-ui-sortable' );
        // Dashboard JS.
        wp_enqueue_script(
            'code_manager_dashboard',
            plugins_url( '../assets/js/code_manager_dashboard.js', __FILE__ ),
            array(),
            CODE_MANAGER_VERSION,
            true
        );
    }

    /**
     * Add plugin menus (only accessible to admin users)
     *
     * @since   1.0.0
     */
    public function add_menu_items() {
        if ( current_user_can( 'manage_options' ) ) {
            // Check if code  manager table is available.
            $code_manager_model = new Code_Manager_Model();
            $code_manager_table_found = $code_manager_model::table_exists();
            // Add top level menu.
            add_menu_page(
                self::PAGE_MAIN,
                'Code Manager',
                'manage_options',
                self::PAGE_MAIN,
                null,
                'dashicons-editor-code',
                999999999
            );
            // Add Code Manager submenu.
            $cm_list_menu = add_submenu_page(
                self::PAGE_MAIN,
                'LIST Mode',
                'LIST Mode',
                'manage_options',
                self::PAGE_MAIN,
                array($this, 'code_manager_page')
            );
            // Create list view to handle screen options.
            if ( self::PAGE_MAIN === $this->page && $code_manager_table_found ) {
                header( 'X-XSS-Protection: 0' );
                $this->cm_list_view = new Code_Manager_List_View(array(
                    'page_hook_suffix' => $cm_list_menu,
                ));
            }
            // Add Code Manager tab mode submenu.
            $cm_tab_menu = add_submenu_page(
                self::PAGE_MAIN,
                'TAB Mode',
                'TAB Mode',
                'manage_options',
                self::PAGE_TAB,
                array($this, 'code_manager_tab_mode')
            );
            // Create list view to handle screen options.
            if ( self::PAGE_TAB === $this->page && $code_manager_table_found ) {
                header( 'X-XSS-Protection: 0' );
                $this->cm_list_view = new Code_Manager_List_View(array(
                    'page_hook_suffix' => $cm_tab_menu,
                ));
            }
        }
    }

    /**
     * Remove notifications from development dashboard
     *
     * @return void
     */
    public function user_admin_notices() {
        if ( self::PAGE_MAIN === $this->page || 'code_manager_settings' === $this->page ) {
            $code_manager_plugin_hide_foreign_notices = get_option( 'code_manager_plugin_hide_foreign_notices' );
            if ( false === $code_manager_plugin_hide_foreign_notices || 'on' === $code_manager_plugin_hide_foreign_notices ) {
                remove_all_actions( 'admin_notices' );
                remove_all_actions( 'all_admin_notices' );
            }
        }
    }

    /**
     * Filter menu if in dashboard mode
     *
     * @param array $submenu_file Sub menus.
     * @return mixed
     */
    public function submenu_filter( $submenu_file ) {
        $hidden_submenus = array('code_manager-account', 'code_manager-wp-support-forum', 'code_manager-contact');
        foreach ( $hidden_submenus as $submenu ) {
            remove_submenu_page( self::PAGE_MAIN, $submenu );
        }
        return $submenu_file;
    }

    /**
     * Register settings page
     *
     * @since   1.0.0
     */
    public function code_manager_register_settings_page() {
        add_options_page(
            'Code Manager',
            'Code Manager',
            'manage_options',
            self::PAGE_SETTINGS,
            array($this, 'code_manager_settings_page')
        );
    }

    /**
     * Show settings page
     *
     * @since   1.0.0
     */
    public function code_manager_settings_page() {
        Code_Manager_Dashboard::add_dashboard();
        $cm_settings = new Code_Manager_Settings();
        $cm_settings->show();
    }

    /**
     * Show Code Manager in list mode
     *
     * @since   1.0.0
     */
    public function code_manager_page() {
        Code_Manager_Dashboard::add_dashboard();
        $this->cm_list_view->show();
    }

    /**
     * Show Code Manager in tab mode
     *
     * @since   1.0.0
     */
    public function code_manager_tab_mode() {
        Code_Manager_Dashboard::add_dashboard();
        $code_manager_tab = new Code_Manager_Tabs();
        $code_manager_tab->show();
    }

    /**
     * Plugin table not found > show error page
     *
     * @since   1.0.0
     */
    public function code_manager_page_not_found() {
        Code_Manager_Dashboard::add_dashboard();
        ?>
		<div class="wrap">
			<h1 class="wp-heading-inline">
				<?php 
        echo 'Code Manager';
        ?>
			</h1>
			<p>
				<?php 
        echo __( 'ERROR: Repository table not found!', 'code-manager' );
        ?>
			</p>
		</div>
		<?php 
    }

}
