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

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

$maestro_id = $_POST["maestro_id"];
$available_date = $_POST["available_date"];
$new_available_date = $_POST["new_available_date"];
$account_type = $_POST["account_type"];


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

add_maestro_extension($maestro_id, $account_type);

// simplely check if maestro upgrade db added or not
$countUpgrade = count_maestro_extension($maestro_id);
if($countUpgrade === null || $countUpgrade < 1) {
	// $maestro_data = get_maestro_data($maestro_id);
	// set_error_message($maestro_data["name"]." : 알 수 없는 이유로 마에스트로 계정 업그레이드 요청이 취소되었습니다.");
	set_error_message("알 수 없는 이유로 마에스트로 계정 업그레이드 요청이 취소되었습니다.");
	send_result_fail();
	exit;
}

$maestro_data = get_maestro_data($maestro_id);
// $maestro_name, $available_date, $new_available_date, $maestro_email, $registered_account_type
sendMailExtensionBankInfo($maestro_data["name"], $available_date, $new_available_date, $maestro_data["email"], $account_type);

send_result_success();
exit;



function count_maestro_extension($maestro_id) {
	global $db_conn;

	$query = "
		SELECT COUNT(MaestroID)
		FROM maestro_extension
		WHERE MaestroID = ?
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("i", $maestro_id);
	$stmt->execute();
	$stmt->bind_result($countUpgrade);
	// while($stmt->fetch())
	$stmt->fetch();
	$stmt->close();

	return $countUpgrade;
}

function add_maestro_extension($maestro_id, $account_type) {
	global $db_conn;

	$query = "
		INSERT INTO maestro_extension (AccountType, RequestedDateTime, Status, MaestroID)
		VALUES (?, NOW(), 1, ?);
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("ii", $account_type, $maestro_id);
	$stmt->execute();
}

?>