<?php
class rank_tracker_tool_admin {

	function rank_tracker_tool_admin() {
		add_action('admin_menu', array(&$this, 'admin_menu'));
		if ( isset($_POST['export']) ) {
			global $rank_tracker_tool;
			$options = $rank_tracker_tool->get_options();			
			$filename = str_replace('www.', '', strtolower($_SERVER['SERVER_NAME'])).date('YMd').'.csv';
			header('Content-Description: File Transfer');
			header("Content-Disposition: attachment; filename=$filename");
			//header("Content-type: application/vnd.ms-excel");
			header("Content-type: text/csv");
			//header("Content-type: text/plain");
			header('Pragma: no-cache');
			$output = 'Keyword,Rank,Prev Rank,URL,PR,Last Checked';
			foreach ( $options['rankings'] as $keyword => $stats )
				$rank[$keyword] = $stats['rank'];
			array_multisort($rank, SORT_ASC, $options['rankings']);
			foreach ( $options['rankings'] as $keyword => $stats )
				$output .= $this->newline().stripslashes(str_replace(',','',$keyword)).','.$stats['rank'].','.$stats['previousrank'].','.str_replace(',','',$stats['url']).','.trim($stats['pr']).','.date('d M Y', $stats['lastchecked']);
			echo $output;
			exit;
		}// end if
	}// end function

	function admin_menu() {
		$pluginpage = add_options_page('Rank Tracker Settings', 'Rank Tracker', 'manage_options', __FILE__, array(&$this, 'settings_page'));
		add_action("admin_print_scripts-$pluginpage", array(&$this, 'admin_head'));
	}// end function

	function admin_head() {
		echo '<link rel="stylesheet" href="'.WP_PLUGIN_URL.'/rank-tracker-tool/admin.css" type="text/css" />'."\n";
	}// end

	function settings_page() {
		global $rank_tracker_tool;
		$options = $rank_tracker_tool->get_options();

		if ( isset($_POST['update']) ) {
			
			// check user is authorised
			if ( function_exists('current_user_can') && !current_user_can('manage_options') )
				die('Sorry, not allowed...');
			check_admin_referer('rank_tracker_tool_settings');

			isset($_POST['sendemail']) ? $options['sendemail'] = true : $options['sendemail'] = false;
			$options['to_email'] = trim($_POST['to_email']);
			$options['country'] = $_POST['country'];
			
			if ( isset($_POST['clear']) )
				unset($options['rankings']);

			update_option('rank_tracker_tool', $options);

			echo '<div id="message" class="updated fade"><p><strong>Settings saved.</strong></p></div>';
		
		}// end if

		echo '<div class="wrap">'
			.'<h2>'.$rank_tracker_tool->name.' Settings - version '.$rank_tracker_tool->version.'</h2>'
			.'<form method="post">';
		wp_nonce_field('rank_tracker_tool_settings');
		echo '<table class="form-table">'
			.'<tr>'
				.'<th scope="row">Send emails:</th>'
				.'<td><input type="checkbox" id="sendemail" name="sendemail"';
					if ( $options['sendemail'] ) echo 'checked="checked"';
					echo ' /> <span class="description">Tick this box to receive emails with new or changed ranking info.</span</td>'
			.'</tr>'
			.'<tr>'
				.'<th scope="row">Destination email address:</th>'
				.'<td><input type="text" name="to_email" id="to_email" value="'.stripslashes($options['to_email']).'" class="regular-text" /> <span class="description">The email address to send notifications to.</span></td>'
			.'</tr>'
		.'<tr>'
			.'<th scope="row">Google country:</th>'
			.'<td><select name="country" id="country">'
			.'<option value="http://www.google.com"';
				if ( $options['country'] == 'http://www.google.com' ) echo ' selected="selected"';
				echo '>http://www.google.com</option>'
			.'<option value="http://www.google.ca"';
				if ( $options['country'] == 'http://www.google.ca' ) echo ' selected="selected"';
				echo '>http://www.google.ca</option>'
			.'<option value="http://www.google.com.au"';
				if ( $options['country'] == 'http://www.google.com.au' ) echo ' selected="selected"';
				echo '>http://www.google.com.au</option>'
			.'<option value="http://www.google.co.uk"';
				if ( $options['country'] == 'http://www.google.co.uk' ) echo ' selected="selected"';
				echo '>http://www.google.co.uk</option>'
			.'<option value="http://www.google.ie"';
				if ( $options['country'] == 'http://www.google.ie' ) echo ' selected="selected"';
				echo '>http://www.google.ie</option>'
			.'</select> <span class="description">Which country to track your Google rankings for.</span></td>'
		.'</tr>'
			.'</table>'
			.'<h3>Your Rankings</h3>'
			.'<p>These are some of the keyword phrases your pages are ranking for in Google.</p>'
			.'<table class="ranktracker"><tr><th>Keyword</th><th colspan="2">Rank</th><th>URL</th><th>PR</th><th>Last Checked</th></tr>';
			if ( is_array($options['rankings']) && count($options['rankings']) ) {
				foreach ( $options['rankings'] as $keyword => $stats )
					$rank[$keyword] = $stats['rank'];
				array_multisort($rank, SORT_ASC, $options['rankings']);
				foreach ( $options['rankings'] as $keyword => $stats ) {
					static $row;
					if ( $row % 2 )
						$rowstyle = 'even';
					else
						$rowstyle = 'odd';
					++$row;
					echo '<tr class="'.$rowstyle.'"><td class="keyword">'.stripslashes($keyword).'</td><td class="rank">'.$stats['rank'].'</td><td class="previousrank">('.$stats['previousrank'].')</td><td class="url">'.$stats['url'].'</td><td class="pr">'.$stats['pr'].'</td><td class="lastchecked">'.date("d M Y, g:i a", $stats['lastchecked']).'</td></tr>';
				}// end foreach
				echo '</table>'
				.'<p><input type="submit" name="export" class="button" value="Export to CSV" /></p>';
			} else {
				echo '<tr><td colspan="6">No ranking data has been collected yet.</td></tr>'
				.'</table>';
			}// end if
			echo '<p><input type="checkbox" id="clear" name="clear" /> <span class="description">Tick this box and click the Save Changes button to delete existing data.</span></p>'
			.'<p class="submit"><input type="submit" name="update" class="button-primary" value="Save Changes" /></p>'
			.'</form>'
			.'</div>';
	}// end function

	function newline() {
		$newline = "\r\n";
		if ( strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'win') )
			$newline = "\r\n";
		elseif ( strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'mac') )
			$newline = "\r";
		else
			$newline = "\n";
		return $newline;
	}// end func

}// end class
$rank_tracker_tool_admin = new rank_tracker_tool_admin;
