<?php
/**
 * CV Monitor
 *
 * @package   CV_Monitor_Admin
 * @author    Gabriel Mariani <gabriel@coursevector.com>
 * @license   GPL-2.0+
 * @link      http://coursevector.com
 * @copyright 2019 CourseVector
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

class CV_Monitor_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	public $plugin_name;
	public $plugin_slug;

	/**
	 * The version of this plugin.
	 *
	 * @var      string    $version    The current version of this plugin.
	 */
	public $version;

	/**
	 * Admin directory
	 *
	 * @var string
	 */
	public $dir;

	// Reference to the main class with utility functions
	public $plugin;

	private $page = '';

	/**
	 * Initialize the plugin by loading admin scripts & styles and adding a settings page and menu.
	 */
	public function __construct( $plugin, $site ) {
		$this->plugin = $plugin;
		$this->plugin_name = $plugin->get_plugin_name();
		$this->plugin_slug = $plugin->get_plugin_slug();
		$this->version = $plugin->get_version();
		$this->site = $site;
		// __DIR__ is available in PHP version 5.3 and up
		$this->dir = plugin_dir_path( dirname( __FILE__ ) );//version_compare( PHP_VERSION, '5.3.0', '<' ) ? dirname( __FILE__ ) : __DIR__;
	}

	public function init() {
		global $pagenow;

		// Send initial dispatch
		/*if ( false !== get_option( 'cv_monitor_last_checked' ) ) {
			echo __( 'Update last sent ', $this->main->plugin_name ) . $thisslug>parse_timestamp( get_option( 'cv_monitor_last_checked' ) ) . ',';
		} else {
			echo __( 'No status has been sent yet,', $this->main->plugin_name );
		}*/

		if ( current_user_can( 'manage_options' ) ) {

			require_once $this->dir . 'admin/class-database.php';
			require_once $this->dir . 'admin/class-settings.php';
			require_once $this->dir . 'admin/class-error-logs.php';
			require_once $this->dir . 'admin/class-dashboard.php';
			require_once $this->dir . 'admin/class-security.php';
			require_once $this->dir . 'admin/class-support.php';

			// Add an action link pointing to the options page.
			$plugin_basename = plugin_basename( $this->dir . $this->plugin_name . '.php' );
			add_filter( 'plugin_action_links_' . $plugin_basename, array( &$this, 'filter_plugin_action_links' ) );

			$this->dashboard_page = new CV_Monitor_Dashboard( $this );
			$this->settings_page = new CV_Monitor_Settings( $this );
			$this->database_page = new CV_Monitor_Database( $this );
			$this->error_logs_page = new CV_Monitor_Error_Logs( $this );
			$this->security_page = new CV_Monitor_Security( $this );
			$this->support_page = new CV_Monitor_Support( $this );

			// Validate page value
			$this->page = isset($_GET['page']) ? $_GET['page'] : '?';
			if ( $this->page === '?' ) $this->page = isset($_POST['option_page']) ? $_POST['option_page'] : '?';
			if ( $this->page === '?' ) $this->page = $pagenow;

			$arr_pages = array( $this->settings_page->slug,
								$this->settings_page->option_group,
								$this->database_page->slug,
								$this->error_logs_page->slug,
								$this->security_page->slug,
								$this->support_page->slug,
								$this->dashboard_page->slug);
			if ( ! in_array( $this->page, $arr_pages ) ) $this->page = $this->dashboard_page->slug;

			switch ( $this->page ) {
				//case $this->settings_page->slug :
				//case $this->settings_page->option_group :
				//	$this->settings_page->init();
				//	break;
				case $this->database_page->slug :
					$this->database_page->init();
					break;
				case $this->error_logs_page->slug :
					$this->error_logs_page->init();
					break;
				case $this->security_page->slug :
					$this->security_page->init();
					break;
				case $this->support_page->slug :
					$this->support_page->init();
					break;
				default :
					$this->dashboard_page->init();
			}

			// Always init in order to take action on settings made
			$this->settings_page->init();

			add_action( 'admin_menu', array( &$this, 'admin_menu' ) );
			add_action( 'admin_init', array( &$this, 'admin_init' ) );
		}
	}

	//--------------------------------------
	//  Public
	//--------------------------------------

	/**
	 * Register the administration menu for this plugin into the WordPress Dashboard menu.
	 */
	public function admin_menu() {

		$warnings = get_transient( 'cv_monitor_vuln_count' );
		$warning_count = (int)$warnings;//count( $warnings );
		$warning_title = esc_attr( sprintf( '%d site vulnerabilities', $warning_count ) );
		$menu_label = sprintf( __( 'CourseVector %s' ), "<span class='update-plugins count-$warning_count' title='$warning_title'><span class='update-count'>" . number_format_i18n($warning_count) . "</span></span>" );

		global $wp_version;
		if ( version_compare( $wp_version, '3.8', '<' ) ) {
			// White with grey outline to work on a light AND dark background
			add_menu_page( 'CourseVector', $menu_label, 'manage_options', $this->dashboard_page->slug, array( $this->dashboard_page, 'display_page' ), "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIGZpbGw9IiNmMWYyZjMiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIj48ZGVmcz48ZmlsdGVyIGlkPSJzdmdfMV9ibHVyIiB4PSItNTAlIiB5PSItNTAlIiB3aWR0aD0iMjAwJSIgaGVpZ2h0PSIyMDAlIj48ZmVHYXVzc2lhbkJsdXIgc3RkRGV2aWF0aW9uPSIxMCIvPjwvZmlsdGVyPjwvZGVmcz48Zz48cmVjdCB4PSItMSIgeT0iLTEiIHdpZHRoPSI1MTQiIGhlaWdodD0iNTE0IiBpZD0iY2FudmFzX2JhY2tncm91bmQiIGZpbGw9Im5vbmUiLz48L2c+PGc+PGcgaWQ9InN2Z18xIiBmaWx0ZXI9InVybCgjc3ZnXzFfYmx1cikiPjxwb2x5Z29uIGlkPSJzdmdfMTIiIGZpbGw9IiMzMzMzMzMiIGZpbGwtcnVsZT0iZXZlbm9kZCIgcG9pbnRzPSI0NC43MzA1ODA0NTIwNDM3OTYsMTg1LjA0MjYyNjgzMzk3OTc0IDQ2OS4zMzM2MTcyMTAxNTUzNSw2MS4zMzMwOTU1Mjk0NDQxMSAxMTAuOTc1MDQxODUxNDU5NTQsMjQ4LjA5NDU2MDQ4ODMwMTggNDQuNzMwNTgwNDUyMDQzNzk2LDE4NS4wNDI2MjY4MzM5Nzk3NCAiIC8+PHBvbHlnb24gaWQ9InN2Z18xMyIgZmlsbD0iIzMzMzMzMyIgZmlsbC1ydWxlPSJldmVub2RkIiBwb2ludHM9IjQzLjY2NjQwNDUzNzAxMjU3LDQ0OS43NTQzOTU4MzIxMzMgNDY5LjMzMzYxNzIxMDE1NTM1LDYxLjMzMzA5NTUyOTQ0NDExIDExMC45NzUwNDE4NTE0NTk1NCwyNDguMDk0NTYwNDg4MzAxOCA0My42NjY0MDQ1MzcwMTI1Nyw0NDkuNzU0Mzk1ODMyMTMzICIgLz48L2c+PHBvbHlnb24gaWQ9InN2Z18yIiBmaWxsPSIjZmRmZGZkIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHBvaW50cz0iNDQuNzMwNTc5Mzc2MjIwNywxODUuMDQyNjMzMDU2NjQwNjIgNDY5LjMzMzYxODE2NDA2MjUsNjEuMzMzMDk5MzY1MjM0Mzc1IDExMC45NzUwNDQyNTA0ODgyOCwyNDguMDk0NTQzNDU3MDMxMjUgNDQuNzMwNTc5Mzc2MjIwNywxODUuMDQyNjMzMDU2NjQwNjIgIiAvPjxwb2x5Z29uIGlkPSJzdmdfMyIgZmlsbD0iI2ZkZmRmZCIgZmlsbC1ydWxlPSJldmVub2RkIiBwb2ludHM9IjQzLjY2NjQwNDcyNDEyMTA5NCw0NDkuNzU0Mzk0NTMxMjUgNDY5LjMzMzYxODE2NDA2MjUsNjEuMzMzMDk5MzY1MjM0Mzc1IDExMC45NzUwNDQyNTA0ODgyOCwyNDguMDk0NTQzNDU3MDMxMjUgNDMuNjY2NDA0NzI0MTIxMDk0LDQ0OS43NTQzOTQ1MzEyNSAiIC8+PC9nPjwvc3ZnPg==", 2 );
		} else {
			// All white for a dark background
			add_menu_page( 'CourseVector', $menu_label, 'manage_options', $this->dashboard_page->slug, array( $this->dashboard_page, 'display_page' ), "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIGZpbGw9IiNmMWYyZjMiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIj48Zz48cG9seWdvbiBpZD0ic3ZnXzEyIiBmaWxsPSIjZjFmMmYzIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHBvaW50cz0iNDQuNzMwNTgwNDUyMDQzNzk2LDE4NS4wNDI2MjY4MzM5Nzk3NCA0NjkuMzMzNjE3MjEwMTU1MzUsNjEuMzMzMDk1NTI5NDQ0MTEgMTEwLjk3NTA0MTg1MTQ1OTU0LDI0OC4wOTQ1NjA0ODgzMDE4IDQ0LjczMDU4MDQ1MjA0Mzc5NiwxODUuMDQyNjI2ODMzOTc5NzQgIi8+PHBvbHlnb24gaWQ9InN2Z18xMyIgZmlsbD0iI2YxZjJmMyIgZmlsbC1ydWxlPSJldmVub2RkIiBwb2ludHM9IjQzLjY2NjQwNDUzNzAxMjU3LDQ0OS43NTQzOTU4MzIxMzMgNDY5LjMzMzYxNzIxMDE1NTM1LDYxLjMzMzA5NTUyOTQ0NDExIDExMC45NzUwNDE4NTE0NTk1NCwyNDguMDk0NTYwNDg4MzAxOCA0My42NjY0MDQ1MzcwMTI1Nyw0NDkuNzU0Mzk1ODMyMTMzICIvPjwvZz48L3N2Zz4=", 2 );
		}

		// Dashboard
		$this->dashboard_page->hook = add_submenu_page( $this->dashboard_page->slug, 'Dashboard', 'Dashboard', 'manage_options', $this->dashboard_page->slug, array( &$this->dashboard_page, 'display_page' ) );

		// Database
		$this->database_page->hook = add_submenu_page( $this->dashboard_page->slug, 'Database', 'Database', 'manage_options', $this->database_page->slug, array( &$this->database_page, 'display_page' ) );

		// Error Logs
		$this->error_logs_page->hook = add_submenu_page( $this->dashboard_page->slug, 'Error Logs', 'Error Logs', 'manage_options', $this->error_logs_page->slug, array( &$this->error_logs_page, 'display_page' ) );

		// Security
		$menu_label = sprintf( __( 'Vulnerabilities %s' ), "<span class='update-plugins count-$warning_count' title='$warning_title'><span class='update-count'>" . number_format_i18n($warning_count) . "</span></span>" );
		$this->security_page->hook = add_submenu_page( $this->dashboard_page->slug, 'Vulnerabilities', $menu_label, 'manage_options', $this->security_page->slug, array( &$this->security_page, 'display_page' ) );

		// Settings
		// add_submenu_page ( string $parent_slug, string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' )
		$this->settings_page->hook = add_submenu_page( $this->dashboard_page->slug, 'Settings', 'Settings', 'manage_options', $this->settings_page->slug, array( &$this->settings_page, 'display_page' ) );
		//$hook = $this->sites_page->hook;
		//add_action( "load-$hook", array( $this->sites_page, 'add_screen_options' ) );

		// Support
		$this->support_page->hook = add_submenu_page( $this->dashboard_page->slug, 'Support', 'Support', 'manage_options', $this->support_page->slug, array( &$this->support_page, 'display_page' ) );

		// Load admin style sheet and JavaScript.
		// enqueue_style added in 3.3+
		if ( version_compare( get_bloginfo( 'version' ), '3.3', '<' ) ) {
			add_action( 'admin_print_styles-' . $this->plugin_screen_hook_suffix, array( &$this, 'admin_enqueue_scripts' ) );
		} else {
			add_action( 'admin_enqueue_scripts', array( &$this, 'admin_enqueue_scripts' ) );
		}
	}

	public function admin_init() {
		//wp_register_style( "{$this->plugin_name}-style", plugin_dir_url( __FILE__ ) . 'css/admin.css', array(), $this->version, 'all' );

		// New feature that may be enabled on update rather than activation
		if ( false == wp_next_scheduled( 'cv_optimize_db' ) ) {
			// Schedule the event for right now, then to repeat weekly using the hook 'cv_optimize_db'
			wp_schedule_event( time(), 'weekly', 'cv_optimize_db' );
		}

		switch ( $this->page ) {
			case $this->settings_page->slug :
			case $this->settings_page->option_group :
				$this->settings_page->admin_init();
				break;
			case $this->database_page->slug :
				$this->database_page->admin_init();
				break;
			case $this->error_logs_page->slug :
				$this->error_logs_page->admin_init();
				break;
			case $this->security_page->slug :
				$this->security_page->admin_init();
				break;
			case $this->support_page->slug :
				$this->support_page->admin_init();
				break;
			default :
				$this->dashboard_page->admin_init();
		}
	}

	/**
	 * Register and enqueue admin-specific JavaScript.
	 *
	 * @return    null    Return early if no settings page is registered.
	 */
	public function admin_enqueue_scripts( $hook ) {
		$this->settings_page->admin_enqueue_scripts( $hook );
		$this->database_page->admin_enqueue_scripts( $hook );
		$this->error_logs_page->admin_enqueue_scripts( $hook );
		$this->security_page->admin_enqueue_scripts( $hook );
		$this->support_page->admin_enqueue_scripts( $hook );
		$this->dashboard_page->admin_enqueue_scripts( $hook );

		/*if ( ! $hook ) {
			// For WordPress 2.7 - 3.1
			wp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( '/' . dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/assets/js/admin.js' ), array( 'jquery' ), CV_Monitor::VERSION );
		} else {
			if ( $hook == $this->plugin_screen_hook_suffix ) {
				wp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( '/assets/js/admin.js', dirname( __FILE__ ) ), array( 'jquery' ), CV_Monitor::VERSION );
			}
		}*/
	}

	/**
	 * Add settings action link to the plugins page.
	 */
	public function filter_plugin_action_links( $links ) {
		return array_merge(
			array(
				'settings' => '<a href="' . admin_url( 'admin.php?page=' . $this->settings_page->slug ) . '">' . __( 'Settings', $this->plugin_slug ) . '</a>'
			),
			$links
		);
	}
}