<?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_extension_id = $_POST["maestro_extension_id"];
$maestro_id = $_POST["maestro_id"];
$maestro_name = $_POST["maestro_name"];
$new_available_date = $_POST["new_available_date"];
$registered_account_type = $_POST["registered_account_type"];

extension_maestro($maestro_id, $new_available_date);

change_extension_request_status_to_close($maestro_id);
change_extension_request_status_to_applied($maestro_extension_id);

$maestro_data = get_maestro_data($maestro_id);
// $maestro_name, $new_available_date, $maestro_email
sendMailExtensionDone($maestro_data["name"], $new_available_date, $maestro_data["email"]);
insertMaestroLog("extension_maestro", $maestro_id, $maestro_name."(".$registered_account_type.")");

// set_data("maestro_extension_id", $maestro_extension_id);
// set_data("maestro_id", $maestro_id);
set_data("maestroName", $maestro_name);
send_result_success();
exit;



function extension_maestro($maestro_id, $new_available_date) {
	global $db_conn;

	// $query = "
	// 	UPDATE maestro
	// 	SET ActivateStatus = 1, AvailableActivateDateTime = DATE_ADD(AvailableActivateDateTime, INTERVAL 1 YEAR)
	// 	WHERE MaestroID = ?;
	// ";
	$query = "
		UPDATE maestro
		SET ActivateStatus = 1, AvailableActivateDateTime = DATE_FORMAT(?, '%Y-%m-%d')
		WHERE MaestroID = ?;
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("si", $new_available_date, $maestro_id);
	$stmt->execute();
}

function change_extension_request_status_to_close($maestro_id) {
	global $db_conn;

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

function change_extension_request_status_to_applied($maestro_extension_id) {
	global $db_conn;

	$query = "
		UPDATE maestro_extension
		SET Status = 3
		WHERE MaestroExtensionID = ?
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("i", $maestro_extension_id);
	$stmt->execute();
}

?>