<?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");

$sPath = "";
$s_log_name = "";
// 處理程序開始
try {
	//依據呼叫的API來分類log
	$s_path = $_GET["path"];
	require_once "Parameters.php";
	require_once "auth/func.php";
	// API訪問紀錄
	base_class::WriteLog("Api_log/Call", "Call", array(
		"method"  => $_SERVER["REQUEST_METHOD"],
		"api_name" => $s_path
	));
	// 存取紀錄
	base_class::WriteLog("Api_log/$s_path", $s_path, array(
		"method"  => $_SERVER["REQUEST_METHOD"],
		"request" => array_merge($_GET, $_POST),
		"body" => file_get_contents('php://input'),
		"header" => apache_request_headers(),
	));
	// 定義輸出格式
	$output = [
		"code" => 999,
		"data" => array(),
		"message" => "unknow"
	];
	$params = [];
	// 檢查HTTP方法，設定params傳遞內容
	$params = json_decode(file_get_contents('php://input'), true);
	if ($params == [] && trim(file_get_contents('php://input')) != "") {
		throw new Exception("Json格式錯誤，解析失敗", 9);
	}
	switch ($_SERVER["REQUEST_METHOD"]) {
		case "GET":
			$prefix =  "Select_";
			break;
		case "POST":
			$prefix =  "Create_";
			break;
		case "PUT":
			$prefix =  "Update_";
			break;
		case "DELETE":
			$prefix =  "Delete_";
			break;
		default:
			throw new Exception("Http Method Not Accepted", 8);
	}

	$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $DataSource, $DataBase_Trend);
	$pdo_mssql = new PDO($dsn, $UserID, $Password);
	// 建立物件
	$class_method = "";
	try {
		$s_filename = "api." . $s_path . ".php";
		include_once "shopee_api/$s_filename";
		$api = new WebAPIForMenuPage();
		$class_method = $prefix . $s_path;
		// 確認方法
		if (!method_exists($api, $class_method)) {
			throw new Exception("Action Undefined", 9);
		}
	} catch (Exception $e) {
		if (!method_exists($api, $class_method)) {
			throw new Exception("Action Undefined", 9);
		}
	}
	// 設置資料庫
	$api->SetDataBase($DataSource, $DataBase_Trend, $DataBase_Alarm, $UserID, $Password, true);
	//取得header_token
	$token = headerToken();
	// 驗證資料正確性與Token 成功則繼續執行呼叫，驗證失敗則由函式內進行error throw
	$api->api_verify($token, $params);
	// 執行並回傳結果
	$output["data"]    = $api->{$class_method}($params);
	// 設置成功
	$output["code"]  = 0;
	$output["message"] = "OK";
} catch (Exception $e) {
	$output["code"]  = $e->getCode();
	$output["message"] = $e->getMessage();
	// 存取紀錄
	base_class::WriteLog("Api_log/$s_path", $s_path, array(
		"method"  => $_SERVER["REQUEST_METHOD"],
		"request" => array_merge($_GET, $_POST),
		"body" => file_get_contents('php://input'),
		"header" => apache_request_headers(),
		"error_code" => $e->getCode(),
		"error_message"  => $e->getMessage(),
	));
	session_destroy();
}
session_destroy();
// 輸出結果
die(json_encode($output));
