<?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_log.php";
include "./../lib/maestro_account_info.php";
include "./../mail/mail_setting.php";
include "./../mail/send_mail.php";

$maestro_upgrade_id = $_POST["maestro_upgrade_id"];
$maestro_id = $_POST["maestro_id"];
$registered_account_type = $_POST["registered_account_type"];
$upgrade_account_type = $_POST["upgrade_account_type"];

upgrade_maestro($maestro_id, $upgrade_account_type);

change_upgrade_request_status_to_close($maestro_id);
change_upgrade_request_status_to_applied($maestro_upgrade_id);

$maestro_data = get_maestro_data($maestro_id);
sendMailUpgradeDone($maestro_data["name"], $maestro_data["email"], $registered_account_type, $upgrade_account_type);
insertMaestroLog("upgrade_maestro", $maestro_id, $registered_account_type." -> ".$upgrade_account_type);

// set_data("maestro_upgrade_id", $maestro_upgrade_id);
// set_data("maestro_id", $maestro_id);
// set_data("upgrade_account_type", $upgrade_account_type);
send_result_success();
exit;



function upgrade_maestro($maestro_id, $upgrade_account_type) {
	global $db_conn;

	$query = "
		UPDATE maestro
		SET AccountType = ?, ActivateStatus = 1, AvailableActivateDateTime = DATE_ADD(NOW(), INTERVAL 1 YEAR)
		WHERE MaestroID = ?;
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("ii", $upgrade_account_type, $maestro_id);
	$stmt->execute();
}

function change_upgrade_request_status_to_close($maestro_id) {
	global $db_conn;

	$query = "
		UPDATE maestro_upgrade
		SET Status = 2
		WHERE MaestroID = ? AND Status = 1;
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("i", $maestro_id);
	$stmt->execute();
}

function change_upgrade_request_status_to_applied($maestro_upgrade_id) {
	global $db_conn;

	$query = "
		UPDATE maestro_upgrade
		SET Status = 3
		WHERE MaestroUpgradeID = ?
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("i", $maestro_upgrade_id);
	$stmt->execute();
}

?>