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

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

$adminName = $_POST["admin_name"];
$password = $_POST["password"];


$maestroID = get_admin_id($adminName);
if($maestroID === null) {
	set_error_code("not_registered_id");
	set_error_message("등록되지 않은 서비스 관리자 아이디입니다.");
	send_result_fail();
	exit;
}

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

if($loginData === null) {
	set_error_code("no_data");
	set_error_message("로그인하지 못했습니다.");
	send_result_fail();
	exit;
} else if($loginData[activateStatus] === 0) {
	set_error_code("not_activated");
	set_error_message("서비스 관리자 계정이 아직 활성화되지 않았습니다.");
	send_result_fail();
	exit;
} else if($loginData[adminID] === null) {
	set_error_code("wrong_password");
	set_error_message("비밀번호가 틀렸습니다.");
	send_result_fail();
	exit;
}

set_data("adminID", $loginData[adminID]);
set_data("accountType", $loginData[accountType]);
set_data("activateStatus", $loginData[activateStatus]);
send_result_success();
exit;



function get_admin_id($adminName) {
	global $db_conn;

	$query = "
		SELECT AdminID
		FROM admin
		WHERE Name = ?
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("s", $adminName);
	$stmt->execute();
	$stmt->bind_result($maestroID);
	// while($stmt->fetch()) {
	// 	;
	// }
	$stmt->fetch();
	$stmt->close();

	return $maestroID;
}

function login($adminName, $password) {
	global $db_conn;

	$query = "
		SELECT AdminID, AccountType, ActivateStatus
		FROM admin
		WHERE Name = ? AND Password = PASSWORD(?)
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("ss", $adminName, $password);
	$stmt->execute();
	$stmt->bind_result($adminID, $accountType, $activateStatus);
	// while($stmt->fetch())
	$stmt->fetch();
	$stmt->close();

	$result["adminID"] = $adminID;
	$result["accountType"] = $accountType;
	$result["activateStatus"] = $activateStatus;
	return $result;
}

?>