<?php
echo("<html>");
echo("<head><meta charset='UTF-8'><title>ランキング</title></head>");
echo("<body>");
$scores = array();
$names = array();
$max_score = -9999;
$min_score = 0;
$newUser = true;

//パラメーターの読み込み
if(isset($_GET['name']))
{
	if(isset($_GET['score']))
	{
		//データを追加
		$postName = urldecode($_GET['name']);
		$postScore = intval($_GET['score']);
	}
}

//データの読み込み
$fp = fopen("./data.txt", "r");
if(!$fp){
	echo "データを開けません";
	exit;
}
for($i = 0; !feof($fp);)
{
	$line = fgets($fp, 4096);
	if($line == "") continue;
	$line = rtrim($line);
	$tkns = split("\t", $line);
	if(isset($tkns[1])){
		$name = $tkns[1];				//これに改行がはいってるかも
		$score = intval($tkns[0]);
		$names[$i] = $name;
		if(isset($postName) && strcmp($name, $postName) == 0){
			$newUser = false;
			if($postScore > $score){
				$scores[$i] = $postScore;
			} else{
				$scores[$i] = $score;
			}
		} else{
			$scores[$i] = $score;
		}
		if($scores[$i] > $max_score){
			$max_score = $scores[$i];
		}
		if($scores[$i] < $min_score){
			$min_score = $scores[$i];
		}
		$i++;
	}
}
//新規ユーザーの登録
if(isset($postName) && isset($postScore) && $newUser){
	$names[$i] = $postName;
	$scores[$i] = $postScore;
	if($scores[$i] > $max_score){
		$max_score = $scores[$i];
	}
	if($scores[$i] < $min_score){
		$min_score = $scores[$i];
	}
	$i++;
}
//ファイルへ書き戻す
$fp = fopen("./data.txt", "w");
$k = $i;
for($i = 0; $i < $k; $i++){
	fputs($fp, $scores[$i] . "\t" . $names[$i] . "\n");
}

//自分の得点表示
if(isset($postName) && isset($postScore)){
	echo($postName . "さんの点数は". $postScore . "点でした！<br>ランキングTOP7:\n");
}

$rankct = 0;
$rankmax = 7;
for($now_score = $max_score; $now_score >= $min_score; $now_score--){
	for($i = 0; $i < $k; $i++){
		if($scores[$i] == $now_score){
			$rankct++;
			echo("<div style='font-size: 32px;");
			if(strcmp($postName, $names[$i]) == 0){
				echo("color: red;");
			}
			echo("'>");
			echo($names[$i] . "\t" . $scores[$i] . "<br></div>");
			$rankct++;
			echo "<hr>\n";
		}
	}
	
	if($rankct > $rankmax){
		break;
	}
}

echo("</body></html>");
?>