<?php
header('Content-Type: application/json');

$maestro_id = $_POST["MaestroID"];
$app_id = $_POST["AppID"];
$date = $_POST["Date"];
$time = $_POST["Time"];

include "./../setup/connect_db.php";
include "./../lib/util_app.php";


$replyJSON = get_ranking_record_day($maestro_id, $date, $app_id);
if($replyJSON.length === 0) {
	send_error_message($replyJSON, "오늘의 랭킹 기록 없음");
	$db_conn->close();
	exit;
}

echo json_encode($replyJSON, JSON_UNESCAPED_UNICODE);
$db_conn->close();


function get_ranking_record_day($maestro_id, $date, $app_id) {
	global $db_conn;

	$query = "
		FROM best_record BR, player U
		WHERE BR.MaestroID = ? AND BR.playerID = U.playerID AND YEAR(BR.RecordDateTime) = YEAR(?) AND MONTH(BR.RecordDateTime) = MONTH(?) AND DAYOFMONTH(BR.RecordDateTime) = DAYOFMONTH(?) AND AppID = ?
		GROUP BY BR.playerID
	";
	if(is_highest_record_prefer_app($app_id)) {
		$query = "SELECT BR.playerID As PlayerID, U.Name AS Name, MAX(BR.BestRecord) AS HighScore".$query;
		$query = $query."ORDER BY MAX(BR.BestRecord) DESC;";
	} else {
		$query = "SELECT BR.playerID As PlayerID, U.Name AS Name, MIN(BR.BestRecord) AS HighScore".$query;
		$query = $query."ORDER BY MIN(BR.BestRecord) ASC;";
	}
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param('isssi', $maestro_id, $date, $date, $date, $app_id);
	$stmt->execute();
	$stmt->bind_result($playerID, $name, $high_score);

	$ranking_record_array = array();
	while($stmt->fetch()) {
	    $ranking_record['PlayerID'] = $playerID;
	    $ranking_record['Name'] = $name;
	    $ranking_record['HighScore'] = $high_score;
	    array_push($ranking_record_array, $ranking_record);
	}
	$return_array['rankingDay'] = $ranking_record_array;

	return $return_array;
}

?>