<?php
	// List of colors
	$colors = array('red', 'blue', 'green', 'yellow', 'black');
	
	
	
	function generate_color()
	{
		global $colors;
		
		return $colors[mt_rand(0, (count($colors) - 1))];
	}
	
	function score_read()
	{
		$score = array();
		
		$file = fopen('score.txt', 'r');
		while(!feof($file)) {
			// Read and "CVS parse" score file line
			$values = explode(',', fgetss($file));
			if(count($values) !== 2) {
				continue;
			}
			
			// Unpack values and add score entry
			$score[] = array(
				'player' => urldecode($values[0]),
				'level'  => intval($values[1])
			);
		}
		fclose($file);
		
		return $score;
	}
	
	function score_write($score)
	{
		$file = fopen('score.txt', 'w');
		foreach($score as $entry) {
			$player = urlencode($entry['player']);
			$level  = intval($entry['level']);
			
			fwrite($file, "{$player},{$level}\n");
		}
		fclose($file);
	}
	
	
	
	
	// Do not use session cookies (we use URL parameters instead)
	ini_set('session.use_cookies',      0);
	ini_set('session.use_only_cookies', 0);
	
	// Start session
	session_name('user_id');
	session_start();
	
	if(!isset($_SESSION['mode'])) {
		$_SESSION['mode'] = 'start';
	}
	
	if(!isset($_SESSION['colors']) || !is_array($_SESSION['colors']) || count($_SESSION['colors']) < 1) {
		$_SESSION['colors'] = array(generate_color());
	}
	
	if(!isset($_SESSION['position'])) {
		$_SESSION['position'] = 0;
	}
	
	
	
	// Process any chosen color
	if(isset($_POST['action'])) {
		$fragment = null;
		
		switch($_POST['action']) {
			case 'start':
				// Switch to main menu
				$_SESSION['mode'] = 'start';
			break;
			
			case 'play':
				// Switch to in-game mode
				$_SESSION['mode'] = 'play';
			break;
			
			case 'score':
				// Switch to highscore mode
				$_SESSION['mode'] = 'score';
			break;
			
			case 'play-select':
				if($_SESSION['colors'][$_SESSION['position']] == $_POST['color']) {
					// Move to next position in color list
					$_SESSION['position']++;
			
					// Check if the user has reached the end of the current list
					if(count($_SESSION['colors']) <= $_SESSION['position']) {
						// Add color to list of expected colors
						$_SESSION['colors'][] = generate_color();
				
						// Reset position
						$_SESSION['position'] = 0;
					}
				} else {
					// Copy current state for post-game processing
					$_SESSION['old-colors']   = $_SESSION['colors'];
					$_SESSION['old-position'] = $_SESSION['position'];
					
					// Clear current game state
					unset($_SESSION['colors']);
					unset($_SESSION['position']);
					
					// Switch to game over mode
					$_SESSION['mode'] = 'over';
				}
			break;
			
			case 'over-commit':
				if(isset($_POST['player']) && $_SESSION['mode'] === 'over') {
					$player = $_POST['player'];
					$level  = count($_SESSION['old-colors']);
					
					// Load high score list
					$score = score_read();
					
					// Find player score in list
					foreach($score as $index => $entry) {
						if($entry['level'] <= $level) {
							break;
						}
					}
					
					// Insert player entry into list
					array_splice($score, $index, 0,
						array(
							array(
								'player' => $player,
								'level'  => $level
							)
						)
					);
					
					// Save new high score list
					score_write($score);
					
					// Make sure we jump to the player's position within the high score table
					$fragment = "view-score-player-{$index}";
				}
				
				// Switch to highscore mode
				$_SESSION['mode'] = 'score';
			break;
		}
		
		// Redirect to self to convert POST into GET request
		header('303 See Other HTTP/1.0');
		header('Location: ' . $_SERVER['SCRIPT_NAME'] . '?' . SID . ($fragment ? "#{$fragment}" : ''));
		die();
	}
	
	// Retieve next color
	$color = end($_SESSION['colors']);
?>
<!DOCTYPE html>
<html class="mode-<?= $_SESSION['mode'] ?>">
	<head>
		<title>Memory - The Game</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
		
		<link rel="stylesheet" type="text/css" href="layout.css" />
		<link rel="stylesheet" type="text/css" href="style.css" />
	</head>
	
	<body>
		<header>
			<h1><span
				class="l1">M</span><span
				class="l2">e</span><span
				class="l3">m</span><span
				class="l4">o</span><span
				class="l5">r</span><span
				class="l6">y</span><span
				class="rest"> – The Game</span></h1>
		
			<article id="header-play">
				<h2>Level</h2>
			
				<p><?= count($_SESSION['colors']) ?></p>
			</article>
			
			<article id="header-score">
				<form method="POST">
					<input type="hidden" name="<?= session_name() ?>" value="<?= session_id() ?>" />
					
					<button type="submit" name="action" value="start">Zum Hautpmenü</button>
				</form>
			</article>
		</header>
		
		<article id="view-start">
			<form method="POST">
				<input type="hidden" name="<?= session_name() ?>" value="<?= session_id() ?>" />
				
				<button type="submit" name="action" value="play">Spielen</button>
				<button type="submit" name="action" value="score">Highscore</button>
			</form>
		</article>
		
		<article id="view-play">
			<h2>Letzte Farbe</h2>
			<div id="color-next" style="background-color: <?= $color ?>"><?= $color ?></div>
			
			<h2>Farbe wählen (<span class="number index"><?= ($_SESSION['position'] + 1) ?></span>/<span class="number total"><?= count($_SESSION['colors']) ?></span>)</h2>
			<form id="color-chooser" method="POST">
				<input type="hidden" name="action" value="play-select" />
				<input type="hidden" name="<?= session_name() ?>" value="<?= session_id() ?>" />
				
<?php
	foreach($colors as $_color) {
		print("\t\t\t\t<button type=\"submit\" name=\"color\" style=\"background-color: {$_color}\" value=\"{$_color}\">{$_color}</button>\n");
	}
?>
			</form>
		</article>
		
		<article id="view-score">
			<table>
				<caption>Highscores</caption>
				
				<thead>
					<tr>
						<th>Spieler</th>
						<th>Level</th>
					</tr>
				</thead>
				
				<tbody>
<?php
	if($_SESSION['mode'] === 'score') {
		foreach(score_read() as $_index => $_entry) {
			$_player = htmlspecialchars($_entry['player']);
			$_level  = intval($_entry['level']);
			
			print("\t\t\t\t\t<tr id=\"view-score-player-{$_index}\">\n");
			print("\t\t\t\t\t\t<td>{$_player}</td>\n");
			print("\t\t\t\t\t\t<td>{$_level}</td>\n");
			print("\t\t\t\t\t</tr>\n");
		}
	}
?>
				</tbody>
			</table>
		</article>
		
		<article id="view-over">
			<h2>Leider falsch!</h2>
			<form method="POST">
				<input type="hidden" name="<?= session_name() ?>" value="<?= session_id() ?>" />
				
				<label for="view-over-player">Bitte gib einen Namen für die Highscore-Tabelle ein:</label>
				<input type="text" name="player" id="view-over-player" /><button type="submit" name="action" value="over-commit">Eintragen!</button>
			</form>
			
			<h2>Richtig wäre gewesen:</h2>
			<ol>
<?php
	foreach($_SESSION['old-colors'] as $_index => $_color) {
		$class = ($_SESSION['old-position'] === $_index) ? 'error' : '';
		
		print("\t\t\t\t<li><span style=\"background-color: {$_color}\" class=\"{$class}\">{$_color}</span></li>\n");
	}
?>
			</ol>
		</article>
	</body>
</html>
