<?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"];
$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;
}
*/

$playerName = get_player_name($maestroID, $playerID);
if($playerName != null && $playerName != "") {
	$sameNamePlayerID = get_same_name_player_id($maestroID, $playerName, $enterCode);
	if($sameNamePlayerID != null && $sameNamePlayerID != 0) {
		set_error_message("입력하신 입장번호를 다른 학생이 사용하고 있습니다.\n다른 입장번호를 입력해주세요.");
		send_result_fail();
		exit;
	}
}

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

set_data("EnterCode", $enterCode);
send_result_success();
exit;


function get_player_name($maestroID, $playerID) {
	global $db_conn;

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

	return $playerName;
}

function get_same_name_player_id($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;
}

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

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

?>