<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{
	// 取得 menu
	public function SelectMenuLoad($params)
	{
		// 取得 menu 樹狀結構
		$menuJson = json_decode(file_get_contents("../cfg/menu.json"))->{$params["menu"]};
		// 取得 menu 權限
		$sql = "SELECT
				 menu_id,
				 function_list
				FROM 
					v_roles_users_menus 
				Where user_id=:user_id";
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $this->user_id));
		$list = $sth->fetchAll(PDO::FETCH_ASSOC);
		// 將登入帳號有權限的 menu id 轉成陣列 並整理各頁面function_list
		$menuIdList = [];
		foreach ($list as $row) {
			if (empty($menuIdList[$row["menu_id"]])) {
				$menuIdList[$row["menu_id"]] = [
					"menu_id" => $row["menu_id"],
					"function_list" => []
				];
				if (!empty($row["function_list"])) {
					$a_func = explode(",", $row["function_list"]);
					$menuIdList[$row["menu_id"]]["function_list"] = array_merge($menuIdList[$row["menu_id"]]["function_list"], $a_func);
				}
			} else {
				if (!empty($row["function_list"])) {
					$a_func = explode(",", $row["function_list"]);
					$menuIdList[$row["menu_id"]]["function_list"] = array_merge($menuIdList[$row["menu_id"]]["function_list"], $a_func);
				}
			}
			$menuIdList[$row["menu_id"]]["function_list"] = array_unique($menuIdList[$row["menu_id"]]["function_list"]);
		}
		// 整理回傳值
		$menuList = array();
		foreach ($menuJson as $itm1) {
			$newItm = array();
			$childList = array();
			// 檢查第二層選單的權限
			foreach ($itm1->children as $itm2) {
				if (!empty($menuIdList[$itm2->menu_id])) {
					//頁面功能權限設定，依據 v_roles_users_menus 視圖表的 function_list 欄位來定義有什麼功能權限可以設定
					if (!empty($menuIdList[$itm2->menu_id]["function_list"])) {
						$test =  $menuIdList[$itm2->menu_id]["function_list"];
						$itm2->function = $test;
					}
					array_push($childList, $itm2);
				}
			}

			// 檢查第一層選單的權限(第一層沒有授權, 第二層有授權也沒用)
			if (!empty($menuIdList[$itm1->menu_id])) {
				if (!empty($childList)) {
					$newItm["children"] = $childList;
				}
				if (!empty($menuIdList[$itm1->menu_id]["function_list"])) {
					$newItm["function"] =  $menuIdList[$itm1->menu_id]["function_list"];
				}
				foreach ($itm1 as $key => $val) {
					if ($key != "children") {
						$newItm[$key] = $val;
					}
				}
				array_push($menuList, $newItm);
			}
		}
		return $menuList;
	}
	// 取得門市選項
	public function SelectStoreOption($params)
	{
		//門市查詢控制項 store_ctrl 0:只顯示營運中門市 1:顯示全門市
		if ($this->store_ctrl == 0) {
			$s_where_stroe_ctrl = " AND _s.store_state = 1";
		}

		$sql = "SELECT		
					_s.store_id,
					_s.store_name,
					_s.store_area
				FROM 
					store AS _s
					LEFT JOIN cashier AS _c ON _c.store_id = _s.store_id
				WHERE
					_c.cashier_id IS NOT NULL
				$s_where_stroe_ctrl";
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute();
		$list = $sth->fetchAll(PDO::FETCH_ASSOC);
		$store_list = array();
		//預設一個全門市查詢選項
		$store_list[] = [
			"store_id" => 0,
			"store_name" => "所有門市"
		];
		foreach ($list as $row) {
			$store_list[] = $row;
		}

		return $store_list;
	}
	// 變更密碼
	public function ChangePassword($params)
	{
		// 檢查舊密碼
		$sql = "select count(*) as cnt from users where user_id=:user_id and password=:old_pwd";
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $this->user_id, "old_pwd" => $params["old_pwd"]));
		$row = $sth->fetch(PDO::FETCH_ASSOC);
		if ($row["cnt"] == 0) {
			throw new Exception("old_pwd_error");
		}
		// 更新密碼
		try {
			$sql = "update users set password=:user_pwd where user_id=:user_id";
			$this->pdo_sql->beginTransaction();
			$sth = $this->pdo_sql->prepare($sql);
			$sth->execute(array("user_id" => $this->user_id, "user_pwd" => $params["new_pwd"]));
			$this->pdo_sql->commit();
			// 回傳
			return true;
		} catch (Exception $e) {
			$this->pdo_sql->rollback();
			throw new Exception("other_error");
		}
	}
	// 取得已上線案場city欄位的記錄(Staion+City or Only City)
	// 供 component right_menu.station.vue 使用
	public function SelectStationCityList($params)
	{
		$sql = "select distinct STN,Name,City,City_Name from v_roles_users_stations where Online=1 and user_id=:user_id order by STN;";
		if (isset($params["is_only_city"]) && $params["is_only_city"] == "1") {
			$sql = "select distinct STN,Name,City,City_Name from v_roles_users_stations where Online=1 and user_id=:user_id order by City;";
		}
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $this->user_id));
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}

	// 取得使用者的個人設定
	// 供 component data_table.vue 使用 (使用者自定義各頁面資料表欄位)
	public function SelectUsersSetting($params)
	{
		$sql = "select * from users_page_setting where user_id=:user_id and func='data_table' and menu_page=:menu_page";
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $this->user_id, "menu_page" => $params["menu_page"]));
		$row = $sth->fetch(PDO::FETCH_ASSOC);
		if (!$row) {
			return "[]";
		}
		return $row["setting"]; // 資料表儲存的是 json 字串
	}
	// 變更使用者的個人設定
	// 供 component data_table.vue 使用 (使用者自定義各頁面資料表欄位)
	public function ChangeUsersSetting($params)
	{
		// 新增或修改資料庫記錄
		$sql = "select * from users_page_setting where user_id=:user_id and func='data_table' and menu_page=:menu_page";
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $this->user_id, "menu_page" => $params["menu_page"]));
		$row = $sth->fetchAll(PDO::FETCH_ASSOC);
		if (count($row) == 0) {
			$sql = "insert into users_page_setting (user_id,func,menu_page,setting) values (:user_id,'data_table',:menu_page,:setting);";
		} else {
			$sql = "update users_page_setting set setting=:setting where user_id=:user_id and func='data_table' and menu_page=:menu_page;";
		}
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $this->user_id, "menu_page" => $params["menu_page"], "setting" => json_encode($params["setting"])));
		return $sql;
	}
}
