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

include "./../setup/connect_db.php";
include "./../lib/send_reply_json.php";
include "./../lib/maestro_account_info.php";
include "./../lib/db_maestro.php";
include "./../lib/maestro_log.php";
include "./../mail/mail_setting.php";
include "./../mail/send_mail.php";


$maestro_name = $_POST["maestro_name"];
$password = $_POST["password"];
$email = $_POST["email"];
$account_type = $_POST["account_type"];


$maestroID = has_maestro_name($maestro_name);
if($maestroID !== null) {
	set_error_message($maestro_name." : 이미 등록된 마에스트로 계정입니다.");
	send_result_fail();
	exit;
}

add_maestro($maestro_name, $password, $email, $account_type);

$maestroID = has_maestro_name($maestro_name);
if($maestroID === null) {
	set_error_message($maestro_name." : 알 수 없는 이유로 마에스트로 계정 등록이 취소되었습니다.");
	send_result_fail();
	exit;
}

sendMailRegisterBankInfo($maestro_name, $email, $account_type);
insertMaestroLog("add_maestro", $maestroID, $maestro_name." / ".$email." / ".$account_type);

send_result_success();
exit;



function has_maestro_name($maestroName) {
	global $db_conn;

	$query = "
		SELECT MaestroID
		FROM maestro
		WHERE Name = ?
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("s", $maestroName);
	$stmt->execute();
	$stmt->bind_result($maestroID);
	// while($stmt->fetch())
	$stmt->fetch();
	$stmt->close();

	return $maestroID;
}

function add_maestro($maestro_name, $password, $email, $account_type) {
	global $db_conn;

	$query = "
		INSERT INTO maestro (Name, Password, Email, AccountType, ActivateStatus, PlayerCount, AcceptClausesDateTime, MaestroTestID)
		VALUES (?, PASSWORD(?), ?, ?, 0, 0, NOW(), -1)";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("sssi", $maestro_name, $password, $email, $account_type);
	$stmt->execute();
}

?>