<?php

/*
public static function activate( $network_wide ) {
	add_option( 'web_property_id', 'UA-0000000-0' );
}

public static function uninstall( $network_wide ) {
	delete_option( 'web_property_id' );
}

public function action_admin_init() {
	register_setting( $this->plugin_name, 'web_property_id' );
}
*/
class CV_Monitor_Settings {

	private $main;
	public $hook;
	public $slug = 'cv-monitor-settings';
	public $option_group = 'cv_monitor_settings_group';
	public $option_page = 'cv_monitor_settings';
	public $option_name = 'cv_monitor_options';

	// Option Names
	public $option_heartbeat_location = 'heartbeat_location';
	public $option_heartbeat_frequency = 'heartbeat_frequency';
	public $option_long_comments = 'no_long_comments';
	public $option_hentry = 'hentry';
	public $option_microdata = 'microdata';
	public $option_js_footer = 'js_footer';
	public $option_js_external_links = 'js_external_links';
	public $option_js_image_sizes = 'js_image_sizes';
	public $option_remove_ver = 'remove_ver';
	public $option_revisions = 'revisions';
	public $option_404 = 'redirect_404';
	public $option_disable_emojis = 'disable_emojis';
	public $option_remove_woo = 'remove_woo';
	public $option_remove_wpapi_header = 'remove_wpapi_header';
	public $option_remove_wpapi = 'remove_wpapi';
	public $option_remove_shortlink_header = 'remove_shortlink_header';
	public $option_remove_pingback_header = 'remove_pingback_header';
	public $option_remove_generator = 'remove_generator';
	public $option_remove_rsd = 'remove_rsd';
	public $option_remove_index_rel = 'remove_index_rel';
	public $option_remove_parent_rel = 'remove_up_rel';
	public $option_remove_start_rel = 'remove_start_rel';
	public $option_remove_adjacent_rel = 'remove_adjacent_rel';
	public $option_remove_wlwmanifest = 'remove_wlwmanifest';
	public $option_remove_shortlink = 'remove_shortlink';
	public $option_remove_feed_links = 'remove_feed_links';
	public $option_remove_feed_links_extra = 'remove_feed_links_extra';
	public $option_remove_pingback_link = 'remove_pingback_link';

	private $heartbeat_frequencies = array(
		'Use default (15 seconds)'   => 'default',
		'15 seconds'    => '15',
		'20 seconds'    => '20',
		'25 seconds'    => '25',
		'30 seconds'    => '30',
		'35 seconds'    => '35',
		'40 seconds'    => '40',
		'45 seconds'    => '45',
		'50 seconds'    => '50',
		'60 seconds'    => '60',
		'2 minutes'     => '120',
		'3 minutes'     => '180',
		'4 minutes'     => '240',
		'5 minutes'     => '300',
	);
	private $heartbeat_locations = array(
		'Use default'                   => 'use-default',
		'Disable everywhere'            => 'disable-heartbeat-everywhere',
		'Disable on dashboard page'     => 'disable-heartbeat-dashboard',
		'Allow only on post edit pages' => 'allow-heartbeat-post-edit',
	);
	private $post_revisions = array(
		'Use default (Unlimited)'   => true,
		'0'    			=> 0,
		'2'    			=> 2,
		'3'    			=> 3,
		'4'    			=> 4,
		'5'    			=> 5,
		'10'    		=> 10,
		'20'    		=> 20,
		'50'    		=> 50,
		'100'    		=> 100,
	);

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $main ) {
		$this->main = $main;
		//$this->option_group = $this->main->plugin_name . '-settings';
		$this->option_page = $this->slug;
	}

	public function init() {
		//$this->check_heartbeat();
	}

	public function display_page() {
		include_once ( $this->main->dir . 'admin/partials/page-settings.php' );
	}

	public function admin_init() {
		wp_register_style( "{$this->main->plugin_name}-style", plugin_dir_url( __FILE__ ) . 'css/admin-settings.css', array(), $this->main->version, 'all' );
		//wp_register_script( "{$this->main->plugin_name}-script", plugin_dir_url( __FILE__ ) . 'js/admin-settings.js', array( 'jquery' ), $this->main->version, false );

		// Default option values
		$default_values = array(
			$this->option_heartbeat_location => 'allow-heartbeat-post-edit',
			//$this->option_heartbeat_frequency => 'use-default',
			$this->option_heartbeat_frequency => '45',
			$this->option_long_comments => '1',
			//$this->option_hentry => '1',
			$this->option_microdata => '1',
			//$this->option_js_footer => '1',
			$this->option_js_external_links => '1',
			//$this->option_js_image_sizes => '1',
			$this->option_remove_ver => '1',
			$this->option_revisions => '20',
			$this->option_404 => '1',
			$this->option_disable_emojis => '1',
			$this->option_remove_woo => '1',
			$this->option_remove_wpapi_header => '0',
			$this->option_remove_wpapi => '0',
			$this->option_remove_shortlink_header => '1',
			$this->option_remove_pingback_header => '1',
			$this->option_remove_generator => '1',
			$this->option_remove_rsd => '1',
			$this->option_remove_index_rel => '1',
			$this->option_remove_parent_rel => '1',
			$this->option_remove_start_rel => '1',
			//$this->option_remove_adjacent_rel => '1',
			$this->option_remove_wlwmanifest => '1',
			$this->option_remove_shortlink => '1',
			//$this->option_remove_feed_links => '1',
			//$this->option_remove_feed_links_extra => '1',
			$this->option_remove_pingback_link => '1'
		);
		if( false === get_option( $this->option_name ) ) 	add_option( $this->option_name, $default_values );

		// register_setting( $option_group, $option_name, $sanitize_callback );
		register_setting( $this->option_group, $this->option_name, array( &$this, 'options_validate' ) );

		// add_settings_section( $id, $title, $callback, $page );
		add_settings_section( 'performance-section', 	'General', 				array( &$this, 'settings_options_callback' ), $this->option_page );
		add_settings_section( 'security-section', 		'Security', 			array( &$this, 'settings_options_callback' ), $this->option_page );
		add_settings_section( 'seo-section', 			'SEO', 					array( &$this, 'settings_options_callback' ), $this->option_page );
		add_settings_section( 'headers-section', 		'WordPress Headers', 	array( &$this, 'settings_options_callback' ), $this->option_page );
		add_settings_section( 'tags-section', 			'WordPress Meta Tags', 	array( &$this, 'settings_options_callback' ), $this->option_page );

		// add_settings_field( $id, $title, $callback, $page, $section, $args );

		// Performance
		add_settings_field(
			$this->option_heartbeat_location,
			'Heartbeat Enabled Locations',
			array( &$this, 'setting_dropdown' ),
			$this->option_page,
			'performance-section',
			array($this->option_heartbeat_location, '', $this->heartbeat_locations)
		);
		add_settings_field(
			$this->option_heartbeat_frequency,
			'Heartbeat Frequency',
			array( &$this, 'setting_dropdown' ),
			$this->option_page,
			'performance-section',
			array($this->option_heartbeat_frequency, '', $this->heartbeat_frequencies)
		);

		// Is AutoOptimize installed? if so disable this
		$message = 'Moves JavaScript code to page footer, speeding up page rendering.';
		$autoptimize_enabled = defined('AUTOPTIMIZE_PLUGIN_DIR');
		if ( $autoptimize_enabled ) {
			$message .= '<br><em><strong>DISABLED</strong> Conflicts with Autoptimize Plugin</em>';
		}
		add_settings_field(
			$this->option_js_footer,
			'Move JS to footer',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'performance-section',
			array($this->option_js_footer, $message, $autoptimize_enabled)
		);
		add_settings_field(
			$this->option_js_external_links,
			'Open external links in a new window',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'performance-section',
			array($this->option_js_external_links, '')
		);
		add_settings_field(
			$this->option_disable_emojis,
			'Disable Emojis',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'performance-section',
			array($this->option_disable_emojis, 'Disable loading emoji CSS and JS if not being used.')
		);
		add_settings_field(
			$this->option_revisions,
			'Limit Post Revisions',
			array( &$this, 'setting_dropdown' ),
			$this->option_page,
			'performance-section',
			array($this->option_revisions, '', $this->post_revisions )
		);

		// Security
		add_settings_field(
			$this->option_long_comments,
			'Stop Long Comments',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'security-section',
			array($this->option_long_comments, 'A security precaution to stop comments that are too long (>13kB).')
		);

		// SEO
		add_settings_field(
			$this->option_hentry,
			'Remove \'hEntry\' class',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'seo-section',
			array($this->option_hentry, 'Removes hentry on pages; a quick solution for the <a href="https://kb.yoast.com/kb/fixing-hcard-author-error/" rel="nofollow" target="_blank">hCard error</a> in Google Structured Data.')
		);
		add_settings_field(
			$this->option_remove_ver,
			'Remove \'ver\' query string',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'seo-section',
			array($this->option_remove_ver, 'Remove query strings from static resources like CSS & JS files. Improves <a href="http://technumero.com/internet/remove-query-strings-from-static-resources/2986" rel="nofollow" target="_blank">PageSpeed/GTMetrix</a> score.')
		);
		add_settings_field(
			$this->option_microdata,
			'Preserve microdata',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'seo-section',
			array($this->option_microdata, 'Prevents WordPress from stripping <a href="https://en.wikipedia.org/wiki/Microdata_(HTML)" rel="nofollow" target="_blank">microdata</a> and structured data in posts.')
		);
		add_settings_field(
			$this->option_js_image_sizes,
			'Add Width/Height to all images',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'seo-section',
			array($this->option_js_image_sizes, 'Adds the width/height attribute to all images. Improves <a href="https://gtmetrix.com/specify-image-dimensions.html" rel="nofollow" target="_blank">PageSpeed/GTMetrix</a> score.')
		);
		add_settings_field(
			$this->option_404,
			'Redirect 404 to homepage',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'seo-section',
			array($this->option_404, 'Permanently redirect all 404\'s to the main blog URL. The primary purpose is to salvage Google PageRank&trade; from missing pages.')
		);

		// Headers
		// Remove the Link header for the WP REST API
		add_settings_field(
			$this->option_remove_wpapi_header,
			'Remove WordPress REST API',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'headers-section',
			array($this->option_remove_wpapi_header, '<code>Link: &lt;http://example.com/wp-json/&gt;; rel="https://api.w.org/"</code>')
		);
		add_settings_field(
			$this->option_remove_shortlink_header,
			'Remove ShortLink',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'headers-section',
			array($this->option_remove_shortlink_header, '<code>Link: &lt;http://example.com/?p=1286&gt;; rel=shortlink</code>')
		);
		add_settings_field(
			$this->option_remove_pingback_header,
			'Remove X-Pingback',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'headers-section',
			array($this->option_remove_pingback_header, '<code>X-Pingback: "http://example.com/xmlrpc.php"</code>')
		);

		// Meta Tags
		// https://developer.wordpress.org/reference/functions/get_the_generator/
		add_settings_field(
			$this->option_remove_generator,
			'Remove WordPress Version',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_generator, '<table class="checkbox-table"><tr><td>HTML/XHTML</td><td><code>&lt;meta name="generator" content="WordPress 4.0" /&gt;</code></td></tr>' .
				'<tr><td>Atom</td><td><code>&lt;generator uri="https://wordpress.org/" version="4.0"&gt;</code></td></tr>' .
				'<tr><td>RSS</td><td><code>&lt;generator&gt;https://wordpress.org/?v=4.0&lt;/generator&gt;</code></td></tr>' .
				'<tr><td>RDF</td><td><code>&lt;admin:generatorAgent rdf:resource="https://wordpress.org/?v=4.0" /&gt;</code></td></tr>' .
				'<tr><td>Comment</td><td><code>&lt;!-- generator="WordPress/4.0" --&gt;</code></td></tr>' .
				'<tr><td>Export</td><td><code>&lt;!-- generator="WordPress/4.0" created="2016-05-31 10:08" --&gt;</code></td></tr></table>')
		);
		add_settings_field(
			$this->option_remove_wpapi,
			'Remove WordPress REST API',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_wpapi, '<table class="checkbox-table"><tr><td><code>&lt;link rel=\'https://api.w.org/\' href=\'http://example.com/wp-json/\' /&gt;</code></td></tr>' .
				'<tr><td><code>&lt;link rel="alternate" type="application/json+oembed" href="http://example.com/wp-json/oembed/1.0/embed?url=http%3A%2F%2Fexample.com%2F" /&gt;</code></td></tr>'.
				'<tr><td><code>&lt;link rel="alternate" type="text/xml+oembed" href="http://example.com/wp-json/oembed/1.0/embed?url=http%3A%2F%2Fexample.com%2F&#038;format=xml" /&gt;</code></td></tr></table>')
		);
		add_settings_field(
			$this->option_remove_woo,
			'Remove Woo Framework Version',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_woo, '<code>&lt;meta name="generator" content="Woo Framework Version x.x.x" /&gt;</code>')
		);
		add_settings_field(
			$this->option_remove_rsd,
			'Remove <a href="https://en.wikipedia.org/wiki/Really_Simple_Discovery" target="_blank">Really Simple Discovery (RSD)</a>',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_rsd, '<code>&lt;link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://example.com/xmlrpc.php?rsd" /&gt;</code>')
		);
		add_settings_field(
			$this->option_remove_pingback_link,
			'Remove Pingback',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_pingback_link, '<code>&lt;link rel="pingback" href="http://example.com/xmlrpc.php" /&gt;</code>')
		);
		add_settings_field(
			$this->option_remove_wlwmanifest,
			'Remove Windows Live Writer manifest',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_wlwmanifest, '<code>&lt;link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://example.com/wp-includes/wlwmanifest.xml" /&gt;</code>')
		);
		add_settings_field(
			$this->option_remove_shortlink,
			'Remove ShortLink',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_shortlink, '<code>&lt;link rel="shortlink" href="http://example.com/?p=1286" /&gt;</code>')
		);
		add_settings_field(
			$this->option_remove_feed_links,
			'Remove RSS Feed',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_feed_links, '<table class="checkbox-table"><tr><td>Site</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title Feed" href="http://example.com/feed/" /&gt;</code></td></tr><tr><td>Site Comments</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title Comments Feed" href="http://example.com/comments/feed/" /&gt;</code></td></tr></table>')
		);
		add_settings_field(
			$this->option_remove_feed_links_extra,
			'Remove Extra RSS Feeds',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_feed_links_extra, '<table class="checkbox-table">' .
				'<tr><td>Comments</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title Comments Feed" href="http://example.com/feed/" /&gt;</code></td></tr>'.
				'<tr><td>Category</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title Category Feed" href="http://example.com/feed/" /&gt;</code></td></tr>'.
				'<tr><td>Tag</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title Tag Feed" href="http://example.com/feed/" /&gt;</code></td></tr>'.
				'<tr><td>Taxonomy</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title %TAXONOMY% Feed" href="http://example.com/feed/" /&gt;</code></td></tr>'.
				'<tr><td>Author</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title %AUTHOR% Feed" href="http://example.com/feed/" /&gt;</code></td></tr>'.
				'<tr><td>Search</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title Search Results for &#8220;search-phrase&#8221; Feed" href="http://example.com/feed/" /&gt;</code></td></tr>'.
				'<tr><td>Archive</td><td><code>&lt;link rel="alternate" type="application/rss+xml" title="Example Title Archive Feed" href="http://example.com/feed/" /&gt;</code></td></tr>'.
				'</table>')
		);
		add_settings_field(
			$this->option_remove_adjacent_rel,
			'Remove "next/prev"',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_adjacent_rel, '<table class="checkbox-table"><tr><td><code>&lt;link rel="next" title="Example Title" href="http://example.com/next-post" /&gt;</code></td></tr><tr><td><code>&lt;link rel="prev" title="Example Title" href="http://example.com/prev-post" /&gt;</code></td></tr></table>')
		);
		add_settings_field(
			$this->option_remove_index_rel,
			'Remove "index"',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_index_rel, 'WordPress &lt; 3.3<br/><code>&lt;link rel="index" title="Example Title" href="http://example.com" /&gt;</code>')
		);
		add_settings_field(
			$this->option_remove_parent_rel,
			'Remove "up"',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_parent_rel, 'WordPress &lt; 3.3<br/><code>&lt;link rel="up" title="Example Title" href="http://example.com" /&gt;</code>')
		);
		add_settings_field(
			$this->option_remove_start_rel,
			'Remove "start/end"',
			array( &$this, 'setting_checkbox' ),
			$this->option_page,
			'tags-section',
			array($this->option_remove_start_rel, 'WordPress &lt; 3.3<br/><table class="checkbox-table"><tr><td><code>&lt;link rel="start" title="Example Title" href="http://example.com" /&gt;</code></td></tr><tr><td><code>&lt;link rel="end" title="Example Title" href="http://example.com" /&gt;</code></td></tr></table>')
		);
	}

	public function setting_input( $args ) {
		$options = (array) get_option( $this->option_name );
		$name = esc_attr( $this->option_name ) . "[" . esc_attr( $args[0] ) . "]";
		$value = esc_attr( $options[$args[0]] );
		$label = $args[1];
		$hint = $args[2];
		echo "<label for='{$name}'>{$label} <input name='{$name}' class='small-text' type='text' value='{$value}' /> {$hint}</label>";
	}

	public function setting_dropdown( $args ) {
		$options = (array) get_option( $this->option_name );
		$name = esc_attr( $this->option_name ) . "[" . esc_attr( $args[0] ) . "]";
		$value = esc_attr( $options[$args[0]] );
		$label = $args[1];
		$extra = $args[2];

		$html = "<select name='{$name}'>";
			foreach ( $extra as $key => $value2 ) {
				$selected = ($value == $value2) ? 'selected="selected"' : '';
				$html .= "<option value='{$value2}' {$selected}>{$key}</option>";
			}
		$html .= "</select>";
		$html .= "<label for='{$name}'>{$label}</label>";
		echo $html;
	}

	public function setting_checkbox( $args ) {
		$options = (array) get_option( $this->option_name );
		$name = esc_attr( $this->option_name ) . "[" . esc_attr( $args[0] ) . "]";
		$value = isset( $options[$args[0]] ) ? $options[$args[0]] : false;
		$label = $args[1];
		$disabled = isset($args[2]) ? $args[2] : false;
		echo "<input id='{$name}' name='{$name}' type='checkbox' value='1' " . checked(1, $value, false) . " " . ($disabled ? 'disabled' : '') . " /><label for='{$name}' class='checkbox-label' > {$label}</label>";
	}

	public function settings_options_callback() {
		// echo '<p>Main description of this section here.</p>';
	}

	public function options_validate( $input ) {
		/*$newinput['text_string'] = trim($input['text_string']);
		if(!preg_match('/^[a-z0-9]{32}$/i', $newinput['text_string'])) {
			$newinput['text_string'] = '';
		}*/
		return $input;
	}

	/**
	 * Register the stylesheets for the Dashboard.
	 *
	 * @since    1.0.0
	 */
	public function admin_enqueue_scripts($hook) {
		if ( $hook === $this->hook ) {
			wp_enqueue_style( "{$this->main->plugin_name}-style" );
			wp_enqueue_script( "{$this->main->plugin_name}-script" );
		}
	}

	/////////////////////////////////////////////
	// Change HeartBeat settings
	// http://jeffmatson.net/heartbeat-control
	// Version: 1.0.3
	// Author: Jeff Matson
	// Author URI: http://jeffmatson.net
	// License: GPL2
	/////////////////////////////////////////////
	private function check_heartbeat() {
		$option = get_option( $this->option_name );
		$heartbeat_location = $option[$this->option_heartbeat_location];
		$heartbeat_frequency = $option[$this->option_heartbeat_frequency];

		if ( $heartbeat_location == 'disable-heartbeat-everywhere') {
			function stop_heartbeat() {
				wp_deregister_script('heartbeat');
			}
			add_action( 'init', 'stop_heartbeat', 1 );
		} elseif ($heartbeat_location == 'disable-heartbeat-dashboard') {
			function stop_heartbeat() {
				global $pagenow;

				if ( $pagenow == 'index.php' ) wp_deregister_script('heartbeat');
			}
			add_action( 'init', 'stop_heartbeat', 1 );
		} elseif ($heartbeat_location == 'allow-heartbeat-post-edit') {
			function stop_heartbeat() {
				global $pagenow;

				if ( $pagenow != 'post.php' && $pagenow != 'post-new.php' )	wp_deregister_script('heartbeat');
			}
			add_action( 'init', 'stop_heartbeat', 1 );
		}

		if ( is_numeric( $heartbeat_frequency ) ) {
			function heartbeat_frequency( $settings ) {
				global $heartbeat_frequency;

				$settings['interval'] = $heartbeat_frequency;
				return $settings;
			}
			add_filter( 'heartbeat_settings', 'heartbeat_frequency' );
		}
	}
}