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

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

$maestroName = $_POST["maestro_name"];


$maestroExtensionList = null;
if(strlen($maestroName) === 0)
	$maestroExtensionList = get_maestro_extension_list();
else
	$maestroExtensionList = get_maestro_extension_list_by_name($maestroName);

if(strlen($maestroExtensionList) === 0) {
	set_error_message("마에스트로 업그레이드 요청 목록 없음");
	send_result_fail();
	exit;
}

set_data("maestroExtensionList", $maestroExtensionList);
send_result_success();
exit;



function get_maestro_extension_list() {
	global $db_conn;

	$query = "
		SELECT E.MaestroExtensionID, E.MaestroID, M.Name, E.AccountType, E.RequestedDateTime, M.AvailableActivateDateTime, E.Status
		FROM maestro_extension E, maestro M
		WHERE E.Status < 2 AND E.MaestroID = M.MaestroID
		ORDER BY E.MaestroExtensionID DESC
	";
	$stmt = $db_conn->prepare($query);
	// $stmt->bind_param("iii", $maestroID, $startNo, $endNo);
	// $stmt->bind_param("ii", $maestroName, $startNo);
	$stmt->execute();
	$stmt->bind_result($maestroExtensionID, $maestroID, $maestroName, $registeredAccountType, $requestedDateTime, $availableActivateDateTime, $status);

	$maestroExtensionList = array();
	while($stmt->fetch()) {
	    $maestro["maestroExtensionID"] = $maestroExtensionID;
	    $maestro["maestroID"] = $maestroID;
	    $maestro["maestroName"] = $maestroName;
	    $maestro["registeredAccountType"] = $registeredAccountType;
	    $maestro["requestedDateTime"] = $requestedDateTime;
	    $maestro["availableActivateDateTime"] = $availableActivateDateTime;
	    $maestro["status"] = $status;
	    array_push($maestroExtensionList, $maestro);
	}

	return $maestroExtensionList;
}

function get_maestro_extension_list_by_name($searchMaestroName) {
	global $db_conn;

	$query = "
		SELECT E.MaestroExtensionID, E.MaestroID, M.Name, E.AccountType, E.RequestedDateTime, M.AvailableActivateDateTime, E.Status
		FROM maestro_extension E, maestro M
		WHERE M.Name LIKE CONCAT('%', ?, '%') AND E.MaestroID = M.MaestroID
		ORDER BY E.MaestroExtensionID DESC
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("s", $searchMaestroName);
	$stmt->execute();
	$stmt->bind_result($maestroExtensionID, $maestroID, $maestroName, $registeredAccountType, $requestedDateTime, $availableActivateDateTime, $status);

	$maestroExtensionList = array();
	while($stmt->fetch()) {
	    $maestro["maestroExtensionID"] = $maestroExtensionID;
	    $maestro["maestroID"] = $maestroID;
	    $maestro["maestroName"] = $maestroName;
	    $maestro["registeredAccountType"] = $registeredAccountType;
	    $maestro["requestedDateTime"] = $requestedDateTime;
	    $maestro["availableActivateDateTime"] = $availableActivateDateTime;
	    $maestro["status"] = $status;
	    array_push($maestroExtensionList, $maestro);
	}

	return $maestroExtensionList;
}

?>