<?php

/*
	Googlyzer
	Contact: Bill Edgar (bill.edgar@oaktondata.com)
	http://www.oaktondata.com/googlyzer
	
	Copyright (c) 2011-2012, Oakton Data LLC
	All rights reserved.

	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
	    
	    * Redistributions of source code must retain the above copyright
	      notice, this list of conditions and the following disclaimer.
	    * Redistributions in binary form must reproduce the above copyright
	      notice, this list of conditions and the following disclaimer in the
	      documentation and/or other materials provided with the distribution.
	    * Neither the name of the Oakton Data LLC nor the
	      names of its contributors may be used to endorse or promote products
	      derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
	ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
	WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
	DISCLAIMED. IN NO EVENT SHALL Oakton Data LLC BE LIABLE FOR ANY
	DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	
	This is the googlyzer_AdminPage PHP class file.
	
 */

if ( !class_exists( 'googlyzer_AdminPage' ) ) {

	/** googlyzer_AdminPage class
	 *
	 * PHP class for creating Googlyzer Admin/Options page.
	 * @author wmsedgar
	 *
	 */
	class googlyzer_AdminPage {
		/* public variables */
		
		/* private variables */
		private $parentInstance = 		null;
		private $stars = 				null;
		
		/**
		 * old style constructor method for backward PHP compatibility
		 */ 
		public function googlyzer_AdminPage( $parentInstance ) {
			$this->__construct( $parentInstance );
		}
		
		/**
		 * public constructor method
		 */
		public function __construct( $parentInstance ) {
			$this->parentInstance = $parentInstance;	
			$this->header();
			$this->body();
		}
		
		/*
		 * private functions
		 */
		
		private function aboutOptions() {
			try {
				// output html for about page
				$this->outputHtml( GOOGLYZER_ABOUT_HTML );
			} catch ( googlyzer_Exception $e ) {
				echo $e->getError();
			}
		}
		
		private function body() {
			$tab = $this->getCurrentTab();
			// display input sections and fields based on current tab
			switch ( $tab ) {
				case 'about':
					$this->aboutOptions();
					break;
				case 'composites':
					$this->compositeOptions();
					break;
				case 'ga_tracking':
					$this->gaTrackingOptions();
					break;
				case 'general':
					$this->generalOptions();
					break;
				case 'linecharts':
					$this->linechartOptions();
					break;
				case 'piecharts':
					$this->piechartOptions();
					break;
				case 'tables':
					$this->tableOptions();
					break;
			}
			echo "</div>";
		}
		
		private function compositeOptions() {
			try {
				// output beginning html composites options page
				$this->outputHtml( GOOGLYZER_COMPOSITES_BEGIN_HTML );
				settings_fields( $option_group = 'googlyzer-composites' );
				ob_start( 'googlyzer_Utilities::bufferFilter' );
				do_settings_sections( $page = 'composites' );
				ob_end_flush();
				?>
					<script type="text/javascript">
						jQuery(document).ready(function() { 
							googlyzer_CheckFields() 
						});
					</script>
				<?php 
				// create the buttons
				$this->settingButtons( 'composites' );
				// output ending html composites options page
				$this->outputHtml( GOOGLYZER_COMPOSITES_END_HTML );
			} catch ( googlyzer_Exception $e ) {
				echo $e->getError();
			}
		}
		
		private function gaTrackingOptions() {
			try {
				// output beginning html ga tracking options page
				$this->outputHtml( GOOGLYZER_GA_TRACKING_BEGIN_HTML );
				settings_fields( $option_group = 'googlyzer-ga_tracking' );
				ob_start( 'googlyzer_Utilities::bufferFilter' );
				do_settings_sections( $page = 'ga_tracking' );
				ob_end_flush();
				?>
					<script type="text/javascript">
						jQuery(document).ready(function() { 
							googlyzer_CheckFields() 
						});
					</script>
				<?php 
				// create the buttons
				$this->settingButtons( 'ga_tracking' );
				// output ending html ga tracking options page
				$this->outputHtml( GOOGLYZER_GA_TRACKING_END_HTML );
			} catch ( googlyzer_Exception $e ) {
				echo $e->getError();
			}
		}
		
		private function generalOptions() {
			try {
				// create Google Service authentication form
				$this->googleAuthService();
				// output html for general settings page
				$this->outputHtml( GOOGLYZER_SETTINGS_END_HTML );
				settings_fields( $option_group = 'googlyzer-options' );
				/*
				 * @todo figure out how to pass additional params to output buffer callback
				 * for string search and replace
				 */
				ob_start( 'googlyzer_Utilities::bufferFilter' );
				do_settings_sections( $page = 'googlyzer-general' );
				ob_end_flush();
				// output javascript to check and set initial form values
				?>
					<script type="text/javascript">
						jQuery(document).ready(function() { 
							googlyzer_CheckFields(); 
							googlyzer_LoadTableID();
							});
					</script>
				<?php 
				// create the buttons
				$this->settingButtons( 'general' );
				?>
										</form>
									</div>
								</div>
							</div>
						</div>
					</div>
				<?php
			} catch ( googlyzer_Exception $e ) {
				echo $e->getError();
			}
		}
		
		/**
		 * 
		 * returns current tab
		 */
		private function getCurrentTab() {
			// return current tab, or general as default
			return ( isset ( $_GET['tab'] ) ? $_GET['tab'] : 'general' );
		}
		
		/**
		 * 
		 * Creates Google Service authentication form
		 */
		private function googleAuthService() {
			// instantiate new googlyzer_GoogleAuth object
			if ( class_exists( 'googlyzer_GoogleAuth' ) ) {
				// set up html for stars on general options
				$this->starsHtml();
				try {
					$gaAuth = new googlyzer_GoogleAuth();
					// check to see if google authentication token already exists
					if ( !empty( $this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_auth_token'] ) ) {
						// authentication token already exists, does user want to logout?
						if ( $gaAuth->STATUS === 'Logout' ) {
							// process logout
							// delete google authorization token, login, password, domain, and ga_tableid from options array
							$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_login'] = null;
							$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_password'] = null;
							$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_auth_token'] = null;
							$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['website'] = null;
							$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_tableid'] = null;
							$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_beginning'] = null;
							// update options array in WP database
							update_option( $option_name = 'googlyzer-options',
								$newvalue = $this->parentInstance->OPTIONS['googlyzer-options']['options'] );
							// output html
							$this->outputHtml( GOOGLYZER_SETTINGS_HTML, 
								$replacement_array = array( '[INSERT_STATUS]'=>'Not authenticated.', '[INSERT_RATING_STARS]'=>$this->stars ) );
							// then output javascript to reset form
							?>
								<script type="text/javascript">
									jQuery(document).ready(function() { 
										googlyzer_ToggleElements( 'enable', new Array( 'ga_email', 'ga_password' ) );
										googlyzer_UpdateElements( { 
											'GoogleAuthButton':'Login', 
											'standard_ga_auth_token':null, 
											'standard_ga_login':null, 
											'standard_ga_password':null ,
											'standard_ga_beginning':null
											} );
										});
								</script>
							<?php
							// set status for form refresh
							$gaAuth->STATUS = 'Not authenticated.';
						// otherwise user is already authenticated and has not changed status
						} else {
							// output html
							$this->outputHtml( GOOGLYZER_SETTINGS_HTML, 
							$replacement_array = array( '[INSERT_STATUS]'=>'Authenticated.', '[INSERT_RATING_STARS]'=>$this->stars ) );
							?>
								<script type="text/javascript">
									jQuery(document).ready(function() { 
										googlyzer_ToggleElements( 'disable', new Array( 'ga_email', 'ga_password' ) );
										googlyzer_UpdateElements( { 
											'GoogleAuthButton':'Logout',
											'ga_auth_store_enable':'<?php if ( empty( $this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_login'] ) ) { echo ''; } else { echo 'checked'; } ?>'
											} );
										});
								</script>
							<?php
						}
					} else {
						// check to see if captcha is required
						if ( preg_match( "/CaptchaRequired/", $gaAuth->STATUS ) ) {
							// output html
							$this->outputHtml( GOOGLYZER_SETTINGS_HTML, 
								$replacement_array = array( 
									'[INSERT_STATUS]' => $gaAuth->STATUS, 
									'[INSERT_CAPTCHA_IMG_SRC]' => $gaAuth->CAPTCHA_URL,
									'[INSERT_CAPTCHA_TOKEN]' => $gaAuth->CAPTCHA_TOKEN,
									'[INSERT_RATING_STARS]'=>$this->stars
									) );
							// insert javascript in page to enable display of captcha form elements
							?>
								<script type="text/javascript">
									jQuery(document).ready(function() { 
										googlyzer_ShowHideElements( true, new Array( 
											'captcha_notification', 
											'captcha_instructions', 
											'captcha_img','captcha_response', 
											'captcha_description' 
											) );
										googlyzer_UpdateElements( { 
											'ga_auth_store_enable':'<?php if ( $gaAuth->STORE === 'enabled' ) { echo 'checked'; } ?>',
											'ga_email':'<?php echo $gaAuth->EMAIL; ?>', 
											'ga_password':'<?php echo $gaAuth->PASSWORD ?>' 
											} );
										});
								</script>';
							<?php
						// check for successful authentication
						} else if ( $gaAuth->STATUS == 'Authenticated.' ) {
							// store authentication token in options array
							$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_auth_token'] = $gaAuth->AUTH_TOKEN;
							if ( $gaAuth->STORE === 'enabled' ) {
								$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_login'] = $gaAuth->EMAIL;
								$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_password'] = $gaAuth->PASSWORD;
							} else {
								$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_login'] = null;
								$this->parentInstance->OPTIONS['googlyzer-options']['options']['standard']['ga_password'] = null;
							}
							// update options array in WP database
							update_option( $option_name = 'googlyzer-options', 
								$newvalue = $this->parentInstance->OPTIONS['googlyzer-options']['options'] );
							// output html
							$this->outputHtml( GOOGLYZER_SETTINGS_HTML, 
								$replacement_array = array( '[INSERT_STATUS]' => $gaAuth->STATUS, '[INSERT_RATING_STARS]'=>$this->stars ) );
							?>
								<script type="text/javascript">
									jQuery(document).ready(function() { 
										googlyzer_ToggleElements( 'disable', new Array( 'ga_email', 'ga_password' ) );
										googlyzer_UpdateElements( { 
											'GoogleAuthButton':'Logout',
											'ga_auth_store_enable':'<?php if ( $gaAuth->STORE === 'enabled' ) { echo 'checked'; } ?>',
											'standard_ga_auth_token':'<?php echo $gaAuth->AUTH_TOKEN; ?>',
											'standard_ga_login':'<?php if ( $gaAuth->STORE === 'enabled' ) { echo $gaAuth->EMAIL; } ?>',
											'standard_ga_password':'<?php if ( $gaAuth->STORE === 'enabled' ) { echo $gaAuth->PASSWORD; } ?>'
											} );
										});
								</script>';
							<?php
						} else {
							// authentication error
							// output html
							$this->outputHtml( GOOGLYZER_SETTINGS_HTML, 
								$replacement_array = array( '[INSERT_STATUS]' => $gaAuth->STATUS, '[INSERT_RATING_STARS]'=>$this->stars ) );
							?>
								<script type="text/javascript">
									jQuery(document).ready(function() { 
										googlyzer_UpdateElements( { 
											'ga_auth_store_enable':'<?php if ( $gaAuth->STORE === 'enabled' ) { echo 'checked'; } ?>',
											'ga_email':'<?php echo $gaAuth->EMAIL; ?>', 
											'ga_password':'<?php echo $gaAuth->PASSWORD ?>'
											} );
										});
								</script>';
							<?php
						}
					}
				} catch ( googlyzer_Exception $e ) {
					echo $e->getError();
				}
			} else {
				throw new googlyzer_Exception( 'googlyzer_GoogleAuth class not loaded.' );
			}		
		} // end method googleAuthService
		
		/**
		 * 
		 * output header section of admin page body
		 */
		private function header(){
			?>
				<script type="text/javascript">
					// jquery for collapsing options areas
					jQuery(document).ready(function() {
						//toggle the component with class msg_body
						jQuery(".head_panel").click(function() {
					    	jQuery(this).next(".content_panel").slideToggle(300);
							});
						});
				</script>
				<div class="wrap">
					<div id="icon-plugins" class="icon32"></div>
						<h2>Googlyzer Administration</h2>
						Googlyzer v<?php echo GOOGLYZER_VERSION; ?> configuration options.
			<?php 
			$this->loadTabs();
		}
		
		private function linechartOptions() {
			try {
				// output beginning html linecharts options page
				$this->outputHtml( GOOGLYZER_LINECHARTS_BEGIN_HTML );
				settings_fields( $option_group = 'googlyzer-linecharts' );
				$pages = array( 'linechart1', 'linechart2', 'linechart3', 'linechart4' );
				foreach ( $pages as $page_num ) {
					ob_start( 'googlyzer_Utilities::bufferFilter' );
					do_settings_sections( $page = $page_num );
					ob_end_flush();
					if ( $page_num !== 'linechart4' ) {
						$this->outputHtml( GOOGLYZER_LINECHARTS_REPEAT_HTML, 
							array( '%Number%' => substr( $page_num, 9 )+1 ) );
					}
				}
				// close div layers for settings
				echo "</div></div>";
				// create the buttons
				$this->settingButtons( 'linecharts' );
				// close the form and output the instructions
				$this->outputHtml( GOOGLYZER_LINECHARTS_INSTRUCTIONS_HTML );
				?>
					<script type="text/javascript">
						jQuery(document).ready(function() { 
							googlyzer_CheckFields() 
							});
					</script>
				<?php
			} catch ( googlyzer_Exception $e ) {
					echo $e->getError();
			}
		}
		
		private function loadTabs() {
			// check to see what tab we're on
			if (isset ( $_GET['tab'])) :
				$current = $_GET['tab'];
			else :
				$current = 'general';
			endif;
			$links = array();
			foreach ( $this->parentInstance->TABS as $tab => $name ) {
				if ($tab == $current) :
					$links[] = "<a class='nav-tab nav-tab-active' href='?page=googlyzer&tab=$tab'>$name</a>";
				else :
					$links[] = "<a class='nav-tab' href='?page=googlyzer&tab=$tab'>$name</a>";
				endif;
			}
			echo '<h2 class="nav-tab-wrapper">';
			foreach ( $links as $link ) {
		          echo $link;
			}
			echo '</h2>';
		}
		
		/**
		 * 
		 * output html input, return true/false for success/failure
		 * @param $target = external file with html for output
		 * @param $replacement_array = array containing items to be searched/replaced
		 * @param $script = string output for script to be appended to html
		 * @throws googlyzer_Exception
		 */
		private function outputHtml( $target, $replacement_array = array(), $script = '' ) {
			// output html for about page
			if ( class_exists( 'googlyzer_Utilities' ) ) {
				try {
					echo googlyzer_Utilities::getFilteredHtml( $target, $replacement_array, $script );
					echo $script;
				} catch ( googlzyer_Exception $e ) {
					echo $e->getError();
				}
			} else {
				throw new googlzyer_Exception( 'googlyzer_Utilities class not loaded.' );
			}
		}
		
		private function piechartOptions() {
			try {
				// output beginning html piecharts options page
				$this->outputHtml( GOOGLYZER_PIECHARTS_BEGIN_HTML );
				settings_fields( $option_group = 'googlyzer-piecharts' );
				$pages = array( 'piechart1', 'piechart2' );
				foreach ( $pages as $page_num ) {
					ob_start( 'googlyzer_Utilities::bufferFilter' );
					do_settings_sections( $page = $page_num );
					ob_end_flush();
					if ( $page_num !== 'piechart2' ) {
						$this->outputHtml( GOOGLYZER_PIECHARTS_REPEAT_HTML, 
							array( '%Number%' => substr( $page_num, 8 )+1 ) );
					}
				}
				// close div layers for settings
				echo "</div></div>";
				// create the buttons
				$this->settingButtons( 'piecharts' );
				// close the form and output the instructions
				$this->outputHtml( GOOGLYZER_PIECHARTS_INSTRUCTIONS_HTML );
				?>
					<script type="text/javascript">
						jQuery(document).ready(function() { 
							googlyzer_CheckFields() 
							});
					</script>
				<?php
			} catch ( googlyzer_Exception $e ) {
					echo $e->getError();
			}
		}
		
		private function settingButtons( $tab ) {
			if ( in_array( $tab, array( 'ga_tracking', 'general', 'linecharts', 'piecharts', 'tables', 'composites' ) ) ) {
				?>
					<p class='submit'>
						<input 
							name="googlyzer[submit-<?php echo $tab; ?>]" 
							type="submit" 
							class="button-primary" 
							value="<?php esc_attr_e( 'Save Settings', 'googlyzer' ); ?>" 
						/>
						<input 
							name="googlyzer[reset-<?php echo $tab; ?>]" 
							type="button" 
							class="button-secondary" 
							value="<?php esc_attr_e( 'Reset', 'googlyzer' ); ?>"
							onclick="googlyzer_FormReset('options_form')"
						/>
						<input 
							name="googlyzer[defaults-<?php echo $tab; ?>]" 
							type="button" 
							class="button-secondary" 
							value="<?php esc_attr_e( 'Restore Defaults', 'googlyzer' ); ?>" 
							onclick="googlyzer_RestoreDefaults()"
						/>
					</p>
				<?php
			}
		}
		
		private function starsHtml() {
			$stars_html = "";
			for ($i=0; $i<5; $i++) {
				$stars_html .= "<img src='"
				. GOOGLYZER_IMAGES
				. "star_rating_small.png'>";
			}
			$this->stars = $stars_html;
		}
		
		private function tableOptions() {
			try {
				// output beginning html tables options page
				$this->outputHtml( GOOGLYZER_TABLES_BEGIN_HTML );
				settings_fields( $option_group = 'googlyzer-tables' );
				$pages = array( 'table1', 'table2' );
				foreach ( $pages as $page_num ) {
					ob_start( 'googlyzer_Utilities::bufferFilter' );
					do_settings_sections( $page = $page_num );
					ob_end_flush();
					if ( $page_num !== 'table2' ) {
						$this->outputHtml( GOOGLYZER_TABLES_REPEAT_HTML, 
							array( '%Number%' => substr( $page_num, 5 )+1 ) );
					}
				}
				// close div layers for settings
				echo "</div></div>";
				// create the buttons
				$this->settingButtons( 'tables' );
				// close the form and output the instructions
				$this->outputHtml( GOOGLYZER_TABLES_INSTRUCTIONS_HTML );
				?>
					<script type="text/javascript">
						jQuery(document).ready(function() { 
							googlyzer_CheckFields() 
							});
					</script>
				<?php
			} catch ( googlyzer_Exception $e ) {
					echo $e->getError();
			}
		}
		
	} // end class googlyzer_AdminPage
	
} // end if class exists