<?php
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING)); // 關閉警示及錯誤訊息
// session_write_close();
include_once 'Parameters.php';
include_once 'auth/func.php';
header('Access-Control-Allow-Origin: *');

if (isset($_POST['user']) && isset($_POST['pwd'])) {
	$user_id  = $_POST['user'];
	$password = $_POST['pwd'];
} else {
	Unauthorized();
	exit;
}

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

	$sql = "SELECT * FROM dbo.users WHERE user_id = :uid AND enabled = 1 AND password = :pwd";
	$st = $pdo_mssql->prepare($sql);
	$st->execute(array("uid" => $user_id, "pwd" => $password));
	$row = $st->fetch();

	$user    = $row['user_id'];
	$user_name = $row['user_name'];
	$pass    = $row['password'];
	$priv_no = $row['priv_no'];

	//登入授權成功
	if ($user_id == $user) {
		$user_id = $row['user_id'];
	} else {
		Unauthorized();
		exit;
	}
} catch (Exception $e) {
	header("HTTP/1.0 500 Internal Server Error");
	exit;
}
// 登入成功 刷新 session_id for 資安檢測 Session Fixation 攻擊 (高風險)
session_regenerate_id();
// 抓取登入者角色清單
$sql = "SELECT * FROM dbo.v_roles_users WHERE user_id = :uid";
$st = $pdo_mssql->prepare($sql);
$st->execute(array("uid" => $user_id));
$list = $st->fetchAll(PDO::FETCH_ASSOC);
$roles = array();
foreach ($list as $row) {
	array_push($roles, $row["role_id"]);
}
// 抓取登入者menu清單
$sql = "SELECT * FROM dbo.v_roles_users_menus WHERE user_id = :uid";
$st = $pdo_mssql->prepare($sql);
$st->execute(array("uid" => $user_id));
$list = $st->fetchAll(PDO::FETCH_ASSOC);
// 抓取目前所有menu
$sql = "SELECT 
			menu_id,
			enabled
		FROM
			menu";
$st = $pdo_mssql->prepare($sql);
$st->execute();
$all_menu_list = $st->fetchAll(PDO::FETCH_ASSOC);
// 抓取登入者的門市顯示控制項
$sql = "SELECT
			MAX(_r.store_ctrl) AS store_ctrl
		FROM
			[dbo].[roles_users] AS _ru
			LEFT JOIN roles AS _r ON _r.role_id = _ru.role_id
		WHERE
		_ru.user_id = :uid";
$st = $pdo_mssql->prepare($sql);
$st->execute(["uid" => $user_id]);
$row = $st->fetch(PDO::FETCH_ASSOC);
$user_store_ctrl = $row["store_ctrl"];

$menus = array();
$page_function = array();
foreach ($list as $row) {
	//整理登入者menu清單
	if (!in_array($row["menu_id"], $menus)) {
		array_push($menus, $row["menu_id"]);
	};
	//判斷為空則，初始化function陣列
	if (empty($page_function[$row["menu_id"]])) {
		$page_function[$row["menu_id"]] = [];
	}
	$a_function_list = [];
	if (!empty($row["function_list"])) {
		$a_function_list = explode(",", $row["function_list"]);
		foreach ($a_function_list as $func) {
			if (!in_array($func, $page_function[$row["menu_id"]])) {
				$page_function[$row["menu_id"]][] = $func;
			};
		}
	}
}
$token = createToken($priv_no, $user_id, $user_name, $roles, $menus, $page_function, $user_store_ctrl, _Login_Auto_Logout_Interval, _Login_Key);
$rtn = array("token" => strval($token), "roles" => $roles, "menus" => $menus);
//session設定登入者ID
$_SESSION["user_id"] = $user_id;
//session設定登入者的門市顯示控制 0:僅顯示營運中門市 1:顯示全門市
$_SESSION["user_store_ctrl"] = $user_store_ctrl;
//session設定頁面權限
$a_menu_permissions = [];
foreach ($all_menu_list as $k => $v) {
	$a_temp_arr = [
		"function" => [],
		"enabled" => 0,
	];
	if (isset($page_function[$v["menu_id"]])) {
		$a_temp_arr["enabled"] = 1;
		$a_temp_arr["function"] = $page_function[$v["menu_id"]];
	}
	$a_menu_permissions[$v["menu_id"]] = $a_temp_arr;
}
$_SESSION['user_menu_permissions'] = $a_menu_permissions;
// 回傳 login.js 的值 {"token":"xxx",}
echo json_encode($rtn);
exit;
