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

include "./../setup/connect_db.php";
include "./../lib/send_reply_json.php";

$maestroName = $_POST["maestro_name"];
$password = $_POST["password"];


$maestroID = get_maestro_id($maestroName);
if($maestroID === null) {
	set_error_code("not_registered_id");
	set_error_message("등록되지 않았거나 아직 승인되지 않은 마에스트로 아이디입니다.");
	send_result_fail();
	exit;
}

$loginData = login($maestroName, $password);

$date = new DateTime($loginData[availableActivateDateTime]);
$now = new DateTime();
if($loginData === null) {
	set_error_code("no_data");
	set_error_message("로그인하지 못했습니다.");
	send_result_fail();
	exit;
} else if($loginData[activateStatus] === 0) {
	set_error_code("over_date");
	set_error_message("마에스트로 계정이 아직 활성화되지 않았습니다.");
	send_result_fail();
	exit;
	/*
} else if($loginData[activateStatus] === 1 && $date < $now) {
	set_error_code("over_date");
	$date = new DateTime($loginData[availableActivateDateTime]);
	set_error_message("마에스트로 계정의 유효기간이 지났습니다. : ".$date->format("Y-m-d H:i:s"));
	send_result_fail();
	exit;
*/
} else if($loginData[maestroID] === null) {
	set_error_code("wrong_password");
	set_error_message("비밀번호가 틀렸습니다.");
	send_result_fail();
	exit;
}

set_data("maestroID", $loginData[maestroID]);
set_data("maestroAccountType", $loginData[accountType]);
set_data("activateStatus", $loginData[activateStatus]);
set_data("availableActivateDateTime", $loginData[availableActivateDateTime]);
send_result_success();
exit;



function get_maestro_id($maestroName) {
	global $db_conn;

	$query = "
		SELECT MaestroID
		FROM maestro
		WHERE Name = ? AND ActivateStatus = 1
	";
	$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 login($maestroName, $password) {
	global $db_conn;

	$query = "
		SELECT MaestroID, AccountType, ActivateStatus, AvailableActivateDateTime
		FROM maestro
		WHERE Name = ? AND Password = PASSWORD(?)
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("ss", $maestroName, $password);
	$stmt->execute();
	$stmt->bind_result($maestroID, $accountType, $activateStatus, $availableActivateDateTime);
	// while($stmt->fetch())
	$stmt->fetch();
	$stmt->close();

	$result["maestroID"] = $maestroID;
	$result["maestroAccountType"] = $accountType;
	$result["activateStatus"] = $activateStatus;
	$result["availableActivateDateTime"] = $availableActivateDateTime;
	return $result;
}

?>