<?php
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING)); // 關閉警示及錯誤訊息
// session_write_close();
header("Access-Control-Allow-Origin: *");
// 有些會先進行交握
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
// 處理程序開始
try {
	require_once "Parameters.php";
	require_once "auth/func.php";
	// 存取紀錄
	base_class::WriteLog("web_log", "Access", array(
		"method"  => $_SERVER["REQUEST_METHOD"],
		"request" => array_merge($_GET, $_POST)
	));
	// 定義輸出格式
	$output = [
		"result" => false,
		"data" => [],
		"message" => "unknow"
	];
	// 檢查HTTP方法(只接受GET及POST)
	switch ($_SERVER["REQUEST_METHOD"]) {
		case "OPTIONS": // 有些會先進行交握
			header("Access-Control-Allow-Headers: Access-Control-Allow-Origin, Authorization");
			die();
			break;
		case "GET":
		case "POST":
			$prefix = $_SERVER["REQUEST_METHOD"] == "GET" ? "Select" : "Change";
			$input  = ${"_" . $_SERVER["REQUEST_METHOD"]};
			// 是否為下載
			if (isset($input["is_download"]) && $input["is_download"]) {
				$prefix = "Download";
			}
			break;
		default:
			throw new Exception("Http Method Not Accepted");
	}
	// 是否需要登入驗證(若 class.WebApi_$$allow_anonymous$$.php 則一定不需要驗證)
	if (_Check_Login_Token && $input["menu_page"] != '$$allow_anonymous$$') {
		// 檢查Token
		if (!$jwt_token = parseToken(headerToken())) {
			Unauthorized();
			$output["result"] = false;
			$output["message"] = "授權失敗(Token)";
			die(json_encode($output));
		}

		$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $DataSource, $DataBase_Trend);
		$pdo_mssql = new PDO($dsn, $UserID, $Password);

		$sql = "SELECT user_id FROM dbo.users WHERE user_id=:user_id";
		$sth = $pdo_mssql->prepare($sql);
		$sth->execute(array("user_id" => $jwt_token->getClaim("user_id")));
		if (!$res = $sth->fetchAll(PDO::FETCH_ASSOC)) {
			Unauthorized();
			$output["result"] = false;
			$output["message"] = "授權失敗(Account)";
			die(json_encode($output));
		}
		$user_id  = $jwt_token->getClaim("user_id");
	}
	// 建立物件
	// 會依據 MenuPage 嚐試讀取頁面專屬WebAPI => page_webapi\class.WebApi_xxx.php
	if ($input["menu_page"] == "") {
		throw new Exception("no webapi for menu page");
	}
	$s_filename = "class.WebApi_" . $input["menu_page"] . ".php";
	include_once "page_webapi/$s_filename";
	$api = new WebAPIForMenuPage();
	if ($user_id) {
		$api->user_id = $user_id;
	}
	//設定門市顯示控制項
	$api->store_ctrl = $_SESSION["user_store_ctrl"];
	//檢查頁面權限
	if (
		empty($_SESSION["user_menu_permissions"]) ||
		(isset($_SESSION["user_menu_permissions"][$input["menu_page"]]) &&
			$_SESSION["user_menu_permissions"][$input["menu_page"]]["enabled"] == 0)
	) {
		http_response_code(402);
		throw new Exception("授權失敗", 1);
	}
	// 確認方法
	if (!method_exists($api, $prefix . $input["Action"])) {
		throw new Exception("Action Undefined", 1);
	}

	// 設置資料庫
	$api->SetDataBase($DataSource, $DataBase_Trend, $DataBase_Alarm, $UserID, $Password, true);
	// 執行並回傳結果
	$output["data"]    = $api->{$prefix . $input["Action"]}($api->InputDecode($input["Datas"]));
	// 設置成功
	$output["result"]  = true;
	$output["message"] = "OK";
	if (isset($input["is_download"]) && $input["is_download"]) {
		$filename = $output["data"]; // 下載的api只要回傳檔案路徑
		if ($filename != '') {
			if (!file_exists($filename)) {
				throw new Exception("no file");
			}
			// 打開檔案並讀取內容
			$file = fopen($filename, 'rb');
			$content = fread($file, filesize($filename));
			fclose($file);

			// 設置header
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
			header('Content-Length: ' . filesize($filename));

			// 輸出檔案內容
			die($content);
			return;
		} else {
			// 設置失敗
			$output["result"]  = false;
			$output["message"] = "no file";
		}
	}
} catch (Exception $e) {

	base_class::WriteLog("web_log", "Access", array(
		"method"  => $_SERVER["REQUEST_METHOD"],
		"request" => array_merge($_GET, $_POST),
		"res" => $e->getMessage(),
		"error code" => $e->getCode(),
	));
	if (isset($input["is_download"]) && $input["is_download"]) {
		http_response_code(400);
		die($e->getMessage());
	} else {
		// 設置失敗
		$output["result"]  = false;
		$output["message"] = $e->getMessage();
	}
}
// 輸出結果
die(json_encode($output));
