<html>
<head>
	<link rel='stylesheet' type='text/css' href='../CSS/Font.css'>
</head>
<body>
<center><h4>Settings</h4></center>

<?php
require "../Common/openDB.php";
require "../Common/preferences.php";
date_default_timezone_set($TimeZone);

// Read preferences file
$handle = fopen("../Common/preferences.php","r");
?>

<form action='set_prefs.php?pressedbutton=yes' method='post'>
<table>
	<col width = '50%'>
	<col width = '25%'>

<?php
// Save prefs file
if(isset($_POST[ok]) || isset($_POST[defaults])){
	if(file_exists("tmp.prefs"))unlink("tmp.prefs");
	$new_file = fopen("tmp.prefs","w");
}elseif(isset($_POST[cancel])){
	header("location: SplashScreen/SplashScreen.html");;
}

while(!feof($handle)){
	$line = fgets($handle);
	$line = trim($line);
	if(startsWith($line,"$")){

		// Get variable, value and default
		$variable = strafter($line, "$");
		$variable = strbefore($variable,"=");
		$variable = trim($variable);
		$value = strafter($line, "=");
		$value = strbefore($value,";");
		$value = trim($value);
		$default = strafter($line, "/");
		$default = strafter($default, "/");
		$default = trim($default);

		// Get help string
		$help = strafter($prev_line,"/");
		$help = strafter($help,"/");

		// Save prefs file
		if(isset($_POST[ok])){

			if($_POST[$variable] == NULL){
				$_POST[$variable] = "false"; // empty checkboxes are not posted and you get NULL, assume all NULL entries are false checkboxes
			}elseif($_POST[$variable] == "on"){
				$_POST[$variable] = "true"; // empty checkboxes are not posted and you get NULL, assume all NULL entries are false checkboxes
			}elseif($variable == "TimeZone"){
				$default = substr($default, strpos($default, " ") + 1);     // For some reasone default has "/ " prepended to it, get everything after the first space
				$_POST[$variable] = "\"" . $_POST[$variable] . "\"";
			}
			fwrite($new_file,"$" . $variable ." = ". $_POST[$variable]."; // ". $default . "\n");

		}elseif(isset($_POST[defaults])){
			if($variable == "TimeZone"){
				$default = substr($default, strpos($default, " ") + 1);     // For some reasone default has "/ " prepended to it, get everything after the first space
				//$default = "\"" . $default . "\"";
			}
			fwrite($new_file,"$" . $variable ." = ". $default ."; // ". $default . "\n");
		}elseif(!$_GET[pressedbutton] == "yes"){
			// Display items
			echo ("<tr><td>{$help}</td><td>");
			echo "</br>";
			echo "</br>";

			// Now value is either a numeric or boolean or string
			// display text box for numeric
			if(is_numeric($value)){
				echo("<input type='text' autocomplete='off' name='{$variable}' size = '20' value='{$value}'/>");

			// display checkbox for boolean
			}elseif($value == "true" || $value == "false"){ // it is boolean display check box
				if($value == "true"){
					$checked = "checked";
				}else{
					$checked = " ";
				}
				echo ("<input type='checkbox' autocomplete='off' name='{$variable}' {$checked}/>");

			// display is unique for strings, test help string
			}else{
				if(strbefore($help, " zone") == " Time"){ // If starts with " Time zone..."
					echo "<select name='TimeZone'>".generate_timezone_list()."</select>";
				}else{
					// put more strings here
					echo "ERROR while reading preferences file <br/>";
				}
			}
			echo "</td></tr>";
		}
	}elseif(isset($_POST[ok]) || isset($_POST[defaults])){
		fwrite($new_file,$line . "\n");
	}
	$prev_line = $line;
}
fclose($handle);
?>
</table>
<table>
	<tr colspan='3'>
	<td align='right'>
		<input type='submit' name='ok' value='save' />
		<input type='submit' name='cancel' value='cancel' />
		<input type='submit' name='defaults' value='reset to defaults' />
	</td>
	</tr>
</table>
</form>
</body>
</html>

<?php
if(isset($_POST[ok]) || isset($_POST[defaults])){
	if(isset($_POST[defaults]))$msg = "Preferences reset to defaults";
	if(isset($_POST[ok]))$msg = "New preferences have been saved";

	fclose($new_file);
	rename("tmp.prefs","../Common/preferences.php");
	header("location: SplashScreen/SplashScreen.html?message={$msg}");
}

function generate_timezone_list() {
	require "../Common/preferences.php";
	static $allRegions = array(
		DateTimeZone::AFRICA,
		DateTimeZone::AMERICA,
		DateTimeZone::ANTARCTICA,
		DateTimeZone::ASIA,
		DateTimeZone::ATLANTIC,
		DateTimeZone::AUSTRALIA,
		DateTimeZone::EUROPE,
		DateTimeZone::INDIAN,
		DateTimeZone::PACIFIC
	);

	// Makes it easier to create option groups next
	$list = array ('AFRICA','AMERICA','ANTARCTICA','ASIA','ATLANTIC','AUSTRALIA','EUROPE','INDIAN','PACIFIC');

	// Make array holding the regions (continents), they are arrays w/ all their cities
	$region = array();
	foreach ($allRegions as $area){
		array_push ($region,DateTimeZone::listIdentifiers( $area ));
	}
	$count = count ($region); $i = 0; $holder = '';

	// Go through each region one by one, sorting and formatting it's cities
	while ($i < $count){
		$chunck = $region[$i];
		// Create the region (continents) option group
		$holder .= '<optgroup label="---------- '.$list[$i].' ----------">';
		$timezone_offsets = array();
		foreach( $chunck as $timezone ){
			$tz = new DateTimeZone($timezone);
			$timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
		}
		asort ($timezone_offsets);
		$timezone_list = array();
		foreach ($timezone_offsets as $timezone => $offset){
			$offset_prefix = $offset < 0 ? '-' : '+';
			$offset_formatted = gmdate( 'H:i', abs($offset) );
			$pretty_offset = "UTC ${offset_prefix}${offset_formatted}";
			$timezone_list[$timezone] = "(${pretty_offset}) $timezone";
		}

		// All the formatting is done, finish and move on to next region
		foreach ($timezone_list as $key => $val){
			$sele = " ";
			if (strpos($val, $TimeZone) !== false) {
				$sele = " selected ";
			}
			if($val )
			//$holder .= '<option value="'.$key.'" >'.$val.'</option>';
			$holder .= '<option value="'.$key.'"'.$sele.'>'.$val.'</option>';
		}
		$holder .= '</optgroup>';
		++$i;
	}
	return $holder;
}


?>
