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

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

$maestroID = $_POST["maestro_id"];
$playerID = $_POST["player_id"];
$playerName = $_POST["player_name"];
$enterCode = $_POST["enter_code"];
/*
if(!is_numeric($enterCode)) {
    send_error_code("생년월일이 숫자가 아닙니다. : ".$enterCode);
    exit;
} else if(strlen($enterCode) != 6) {
    send_error_code("6자리 숫자값을 정확히 입력하세요 : YYMMDD (예 : 120131) : ".$enterCode);
    exit;
}
*/


$result = hasSamePlayerData($maestroID, $playerID, $playerName, $enterCode);
if($result > 0) {
	set_error_message("이미 등록된 학생과 입장 코드 정보입니다.");
	send_result_fail();
	exit;
}

editPlayer($maestroID, $playerID, $playerName, $enterCode);

$result = hasPlayerName($maestroID, $playerName, $enterCode);
if($result === null) {
	set_error_message("학생 등록에 실패했습니다.");
	send_result_fail();
	exit;
}

send_result_success();
exit;


function hasSamePlayerData($maestroID, $playerID, $playerName, $enterCode) {
	global $db_conn;

	$query = "SELECT COUNT(PlayerID) FROM player WHERE MaestroID=? AND PlayerID<>? AND Name=? AND EnterCode=?";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("iiss", $maestroID, $playerID, $playerName, $enterCode);
	$stmt->execute();
	$stmt->bind_result($playerCount);
	// while($stmt->fetch())
	$stmt->fetch();
	$stmt->close();

	return $playerCount;
}

function editPlayer($maestroID, $playerID, $playerName, $enterCode) {
	global $db_conn;

	$query = "UPDATE player SET Name=?, EnterCode=? WHERE MaestroID=? AND PlayerID=?";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("ssii", $playerName, $enterCode, $maestroID, $playerID);
	$stmt->execute();
}

function hasPlayerName($maestroID, $playerName, $enterCode) {
	global $db_conn;

	$query = "SELECT PlayerID FROM player WHERE MaestroID=? AND Name=? AND EnterCode=?";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("iss", $maestroID, $playerName, $enterCode);
	$stmt->execute();
	$stmt->bind_result($playerID);
	// while($stmt->fetch())
	$stmt->fetch();
	$stmt->close();

	return $playerID;
}

?>