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

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

$maestroName = $_POST["maestro_name"];


$maestroList = null;
if(strlen($maestroName) === 0)
	$maestroList = get_maestro_list();
else
	$maestroList = get_maestro_list_by_name($maestroName);

if(strlen($maestroList) === 0) {
	set_error_message("오늘의 랭킹 기록 없음");
	send_result_fail();
	exit;
}

set_data("maestroList", $maestroList);
send_result_success();
exit;



function get_maestro_list() {
	global $db_conn;

	$query = "
		SELECT MaestroID, Name, AccountType, ActivateStatus, AvailableActivateDateTime, AcceptClausesDateTime, PlayerCount
		FROM maestro
		ORDER BY MaestroID DESC
	";
	$stmt = $db_conn->prepare($query);
	// $stmt->bind_param("iii", $maestroID, $startNo, $endNo);
	// $stmt->bind_param("ii", $maestroName, $startNo);
	$stmt->execute();
	$stmt->bind_result($maestroID, $name, $accountType, $activateStatus, $availableActivateDateTime	, $acceptClausesDateTime, $playerCount);

	$maestroList = array();
	while($stmt->fetch()) {
		$maestro["maestroID"] = $maestroID;
		$maestro["maestroName"] = $name;
		$maestro["accountType"] = $accountType;
		$maestro["activateStatus"] = $activateStatus;
		$maestro["availableActivateDateTime"] = $availableActivateDateTime;
		$maestro["acceptClausesDateTime"] = $acceptClausesDateTime;
		$maestro["playerCount"] = $playerCount;
	    array_push($maestroList, $maestro);
	}

	return $maestroList;
}

function get_maestro_list_by_name($maestroName) {
	global $db_conn;

	$query = "
		SELECT MaestroID, Name, AccountType, ActivateStatus, AcceptClausesDateTime, PlayerCount
		FROM maestro
		WHERE Name LIKE CONCAT('%', ?, '%')
		ORDER BY MaestroID DESC
	";
	$stmt = $db_conn->prepare($query);
	// $stmt->bind_param("iii", $maestroID, $startNo, $endNo);
	$stmt->bind_param("s", $maestroName);
	$stmt->execute();
	$stmt->bind_result($maestroID, $name, $accountType, $activateStatus, $acceptClausesDateTime, $playerCount);

	$maestroList = array();
	while($stmt->fetch()) {
		$maestro["maestroID"] = $maestroID;
		$maestro["maestroName"] = $name;
		$maestro["accountType"] = $accountType;
		$maestro["activateStatus"] = $activateStatus;
		$maestro["acceptClausesDateTime"] = $acceptClausesDateTime;
		$maestro["playerCount"] = $playerCount;
		array_push($maestroList, $maestro);
	}

	return $maestroList;
}

?>