<?php
/*
* Define class pspGTMetrix
* Make sure you skip down to the end of this file, as there are a few
* lines of code that are very important.
*/
!defined('ABSPATH') and exit;
if (class_exists('pspGTMetrix') != true) {
    class pspGTMetrix
    {
        /*
        * Some required plugin information
        */
        const VERSION = '1.0';

        /*
        * Store some helpers config
        */
		public $the_plugin = null;

		private $module_folder = '';
		private $module = '';

		static protected $_instance;

        /*
        * Required __construct() function that initalizes the AA-Team Framework
        */
        public function __construct()
        {
        	global $psp;

        	$this->the_plugin = $psp;
			$this->module_folder = $this->the_plugin->cfg['paths']['plugin_dir_url'] . 'modules/gtmetrix/';
			$this->module = $this->the_plugin->cfg['modules']['gtmetrix'];

			if (is_admin()) {
	            add_action('admin_menu', array( &$this, 'adminMenu' ));
			}
			
			// load the ajax helper
			require_once( $this->the_plugin->cfg['paths']['plugin_dir_path'] . 'modules/gtmetrix/ajax.php' );
			new pspGTMetrixAjax( $this->the_plugin );
        }

		/**
	    * Hooks
	    */
	    static public function adminMenu()
	    {
	       self::getInstance()
	    		->_registerAdminPages();
	    }

	    /**
	    * Register plug-in module admin pages and menus
	    */
		protected function _registerAdminPages()
    	{
    		if ( $this->the_plugin->capabilities_user_has_module('gtmetrix') ) {
	    		add_submenu_page(
	    			$this->the_plugin->alias,
	    			$this->the_plugin->alias . " " . __('GTMetrix', 'psp'),
		            __('GTMetrix', 'psp'),
		            'read',
		            $this->the_plugin->alias . "_GTMetrix",
		            array($this, 'display_index_page')
		        );
    		}

			return $this;
		}

		public function display_meta_box()
		{
			if ( $this->the_plugin->capabilities_user_has_module('gtmetrix') ) {
				$this->printBoxInterface();
			}
		}

		public function display_index_page()
		{
			$this->printBaseInterface();
		}
		
		public function moduleValidation() {
			$ret = array(
				'status'			=> false,
				'html'				=> ''
			);
			
			// find if user makes the setup
			$module_settings = $gtmetrix_settings = $this->the_plugin->get_theoption( $this->the_plugin->alias . "_gtmetrix" );
			
			$gtmetrix_mandatoryFields = array(
				'api_key'			=> false,
				'email'				=> false
			);
			if ( isset($gtmetrix_settings['api_key']) && !empty($gtmetrix_settings['api_key']) ) {
				$gtmetrix_mandatoryFields['api_key'] = true;
			}
			if ( isset($gtmetrix_settings['email']) && !empty($gtmetrix_settings['email']) ) {
				$gtmetrix_mandatoryFields['email'] = true;
			}
			$mandatoryValid = true;
			foreach ($gtmetrix_mandatoryFields as $k=>$v) {
				if ( !$v ) {
					$mandatoryValid = false;
					break;
				}
			}
			if ( !$mandatoryValid ) {
				$error_number = 1; // from config.php / errors key
				
				$ret['html'] = $this->the_plugin->print_module_error( $this->module, $error_number, 'Error: Unable to use GTMetrix module, yet!' );
				return $ret;
			}
			$ret['status'] = true;
			return $ret;
		}
		
		/*
		* printBaseInterface, method
		* --------------------------
		*
		* this will add the base DOM code for you options interface
		*/
		private function printBaseInterface()
		{
?>
		<?php echo psp_asset_path( 'js', $this->module_folder . 'app.class.js', false ); ?>
		<?php
			//echo psp_asset_path( 'css', $this->module_folder . 'assets/skins/minimal/blue.css', false );
			//echo psp_asset_path( 'js', $this->module_folder . 'assets/icheck.js', false );
		?>

		<div class="<?php echo $this->the_plugin->alias; ?>">
			
			<div class="<?php echo $this->the_plugin->alias; ?>-content"> 
				
				<!-- Page detail -->
				<div id="psp-gtmetrix-detail">
					<div id="psp-gtmetrix-ajaxresponse"></div>
				</div>

				<?php
				// show the top menu
				pspAdminMenu::getInstance()->make_active('monitoring|gtmetrix')->show_menu();
				?>

				<!-- Content -->
				<section class="<?php echo $this->the_plugin->alias; ?>-main">
					
					<?php 
					echo psp()->print_section_header(
						$this->module['gtmetrix']['menu']['title'],
						$this->module['gtmetrix']['description'],
						$this->module['gtmetrix']['help']['url']
					);
					?>
					
					<div class="panel panel-default <?php echo $this->the_plugin->alias; ?>-panel">
			
						<div class="panel-heading psp-panel-heading">
							<h2><?php _e('Analyze your website with GTMetrix', 'psp');?></h2>
						</div>
						
						<div class="panel-body <?php echo $this->the_plugin->alias; ?>-panel-body">
							
							<!-- Container -->
							<div class="psp-container clearfix">
			
								<!-- Main Content Wrapper -->
								<div id="psp-content-wrap" class="<?php echo $this->the_plugin->alias; ?>-gtmetrix clearfix">
									
									<?php 
									// find if user makes the setup
									$moduleValidateStat = $this->moduleValidation();
									
									if ( !$moduleValidateStat['status'] )
										echo $moduleValidateStat['html'];
									else{ 
									?>
		                        		
									<form class="psp-form" id="1" action="#save_with_ajax">
										<div class="psp-form-row psp-table-ajax-list" id="psp-table-ajax-response">
										<?php
										$settings = $this->the_plugin->getAllSettings( 'array', 'gtmetrix' );
										$attrs = array(
											'id' 				=> 'pspGTMetrix',
											'show_header' 		=> true,
											'show_header_buttons' => true,
											'items_per_page' 	=> '10',
											'post_statuses' 	=> 'all',
											'columns'			=> array(
												'checkbox'	=> array(
													'th'	=>  'checkbox',
													'td'	=>  'checkbox',
												),

												'id'		=> array(
													'th'	=> __('ID', 'psp'),
													'td'	=> '%ID%',
													'width' => '40'
												),

												'title'		=> array(
													'th'	=> __('Title', 'psp'),
													'td'	=> '%title%',
													'align' => 'left'
												),

												'gtmetrix_pagespeed_score'	=> array(
													'th'	=> __('Google Pagespeed Score', 'psp'),
													'td'	=> '%pagespeed_score%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_the_pagespeed_score'
												),
												
												'gtmetrix_yslow_score'	=> array(
													'th'	=> __('YSlow Score', 'psp'),
													'td'	=> '%yslow_score%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_the_yslow_score'
												),
												
												'gtmetrix_first_paint_time'	=> array(
													'th'	=> __('First Paint Time', 'psp'),
													'td'	=> '%first_paint_time%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_first_paint_time'
												),
												
												'gtmetrix_dom_content_loaded_time'	=> array(
													'th'	=> __('DOM content loaded time', 'psp'),
													'td'	=> '%dom_content_loaded_time%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_dom_content_loaded_time'
												),
												
												'gtmetrix_page_load_time'	=> array(
													'th'	=> __('Page Load Time', 'psp'),
													'td'	=> '%page_load_time%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_page_load_time'
												),
												
												'gtmetrix_html_bytes'	=> array(
													'th'	=> __('HTML Bytes', 'psp'),
													'td'	=> '%html_bytes%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_html_bytes'
												),
												
												'gtmetrix_page_bytes'	=> array(
													'th'	=> __('Page Bytes', 'psp'),
													'td'	=> '%page_bytes%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_page_bytes'
												),
												
												'gtmetrix_fully_loaded_time'	=> array(
													'th'	=> __('Fully Load Time', 'psp'),
													'td'	=> '%fully_loaded_time%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_fully_loaded_time'
												),
												
												'gtmetrix_connect_duration'	=> array(
													'th'	=> __('Connect Duration', 'psp'),
													'td'	=> '%connect_duration%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_connect_duration'
												),
												
												'gtmetrix_html_load_time'	=> array(
													'th'	=> __('HTML Load Time', 'psp'),
													'td'	=> '%html_load_time%',
													'width' => '130',
													'css' 	=> array(
														'padding' => '0px',
														'background' => '#fcfcfc'
													),
													'class' => 'psp_html_load_time'
												),
												
												'gtmetrix_speed_details'	=> array(
													'th'	=> __('View report', 'psp'),
													'td'	=> '%view_gtmetrix_report%',
													'option' => array(
														'value' => __('View Report', 'psp'),
														//'action' => 'do_item_view_report',
														'color' => 'info'
													),
													'width' => '80',
													'class' => 'psp_html_view_report'
												),
												
												'optimize_btn' => array(
													'th'	=> __('Action', 'psp'),
													'td'	=> '%button%',
													'option' => array(
														'value' => __('Analyze', 'psp'),
														'action' => 'do_item_gtmetrix_test',
														'color' => 'danger'
													),
													'width' => '80'
												),
											),
											'mass_actions' 	=> array(
													'speed_test_mass' => array(
														'value' => __('Mass Analyze', 'psp'),
														'action' => 'do_speed_test_mass',
														'color' => 'info'
													)
												)
										);

										// if report type not both 
										if( isset($settings['report_type']) && $settings['report_type'] != "both" ){
											$removeWhat = 'desktop';
											if( $settings['report_type'] == 'desktop' ){
												$removeWhat = 'mobile';
											}
											unset($attrs['columns']['gtmetrix_speed_' . ( $removeWhat ) . '_score']);
										}

										pspAjaxListTable::getInstance( $this->the_plugin )
											->setup( $attrs )
											->print_html();
							            ?>
							            </div>
						            </form>
						            <?php } ?>
					            </div>
							</div>
						</div>
					</div>
				</section>
			</div>
		</div>
<?php
		}
		
		/**
	    * Singleton pattern
	    *
	    * @return pspGTMetrix Singleton instance
	    */
	    static public function getInstance()
	    {
	        if (!self::$_instance) {
	            self::$_instance = new self;
	        }

	        return self::$_instance;
	    }
    }
}

// Initialize the pspGTMetrix class
$pspGTMetrix = pspGTMetrix::getInstance();