<?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";
	// 存取紀錄
	file_put_contents("./Api_log/Access_" . date("Ymd") . ".txt", print_r(array(
		"time_stamp" => date("Y-m-d H:i:s"),
		"method"  => $_SERVER["REQUEST_METHOD"],
		"request" => array_merge($_GET, $_POST)
	), true) . "\r\n", FILE_APPEND);
	// 定義輸出格式
	$output = array("result" => false, "data" => array(), "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$$.inc 則一定不需要驗證)
	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");
	}
	// throw new Exception($input["menu_page"]);
	// 建立物件
	try {
		// 會依據 MenuPage 嚐試讀取頁面專屬WebAPI => page_webapi\class.WebApi_xxx.inc, 若沒有才會讀取預設 class.WebApi.inc

		if ($input["menu_page"] == "") {
			throw new Exception("no webapi for menu page");
		}
		include_once "page_webapi/class.WebApi_" . $input["menu_page"] . ".inc";
		$api = new WebAPIForMenuPage();
		if ($user_id) {
			$api->user_id = $user_id;
		}
		// 確認方法
		if (!method_exists($api, $prefix . $input["Action"])) {
			throw new Exception("Action Undefined");
		}
	} catch (Exception $e) {
		require_once "class.WebApi.inc"; // 讀取預設的 class.WebApi.inc
		$api = new WebAPI();
		if ($user_id) {
			$api->user_id = $user_id;
		}
		// 確認方法
		if (!method_exists($api, $prefix . $input["Action"])) {
			throw new Exception("Action Udddndefined");
		}
	}
	// 設置資料庫
	$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) {
	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));
