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

$maestro_id = $_POST["MaestroID"];
$app_id = $_POST["AppID"];
$player_id = $_POST["PlayerID"];
$date = $_POST["Date"];

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


$replyJSON = get_history_record($maestro_id, $app_id, $player_id, $date);
if($replyJSON.length === 0) {
	send_error_message($replyJSON, "히스토리 기록 없음");
	$db_conn->close();
	exit;
}

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


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

	$query = "
		FROM best_record BR
	    INNER JOIN app AS AA
	    	ON BR.MaestroID = ? AND BR.PlayerID = ? AND DATE(BR.RecordDateTime) <= ? AND BR.AppID = ? AND BR.AppID = AA.AppID
		GROUP BY DATE(BR.RecordDateTime)
		ORDER BY BR.RecordDateTime DESC
		LIMIT 7
	";
	if(is_highest_record_prefer_app($app_id)) {
		$query = "SELECT DATE(BR.RecordDateTime) AS Date, MAX(BR.BestRecord) AS HighScore, AA.AppName AS AppName".$query;
	}
	else {
		$query = "SELECT DATE(BR.RecordDateTime) AS Date, MIN(BR.BestRecord) AS HighScore, AA.AppName AS AppName".$query;
	}
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param('iisi', $maestro_id, $player_id, $date, $app_id);
	$stmt->execute();
	$stmt->bind_result($date, $score, $app_name);

	$history_record_array = array();
	while($stmt->fetch()) {
	    $history_record['Date'] = $date;
	    $history_record['HighScore'] = $score;
	    $history_record['AppName'] = $app_name;
	    array_push($history_record_array, $history_record);
		array_push($return_array, $history_record);
	}
	$return_array['history'] = $history_record_array;

	return $return_array;
}

?>