<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class {

	public function SelectRoles ($params) {

		$sql = sprintf("SELECT * 
						FROM [%s].[dbo].[roles]
						WHERE [role_ui_hide] = 0 AND [is_ui_visible] = 1"
						,$this->database_trend);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute([]);
		return $sth->fetchAll(PDO::FETCH_ASSOC);

	}

	//	抓角色之前頁面紀錄
	public function SelectMenu ($params) {

		$sql = sprintf("SELECT [menu_id]
						FROM [%s].[dbo].[roles_menu]
						WHERE [role_id] = :role_id;"
						,$this->database_trend);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute([
			'role_id' => $params['role_id'],
		]);
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}


	//	新增，更新 [roles_menu]
	public function ChangeRoleMenu ($params) {

		try {
			
			$this->pdo_sql->beginTransaction();

			//	查詢[roles_menu]有沒有紀錄
			$sql = sprintf("SELECT *
							FROM [%s].[dbo].[roles_menu] 
							WHERE [role_id] = :role_id;"
								, $this->database_trend);
			$sth = $this->pdo_sql->prepare($sql);
			$sth->execute([
				'role_id' => $params['role'],
			]);

			if ( $sth->fetch(PDO::FETCH_BOUND) == 1 ){
				$sql = sprintf("DELETE 
								FROM [%s].[dbo].[roles_menu] 
								WHERE [role_id] = :role_id;"
								, $this->database_trend);
					$sth = $this->pdo_sql->prepare($sql);
					$sth->execute([
						'role_id' => $params['role'],
					]);
					if ( $sth->rowCount() == 0) {
						throw new Exception("roles_menu刪除失敗");
					}
			} else {

			}

			foreach ($params['page_arr'] as $page_name) {
		 		$sql = sprintf("INSERT INTO [%s].[dbo].[roles_menu] (
									 [role_id]
		      						,[menu_id]
								) VALUES (
									 :role_id
									,:page_id
								);", $this->database_trend);
				$sth = $this->pdo_sql->prepare($sql);
				$sth->execute([
					'role_id' => $params['role'],
					'page_id' => $page_name,
				]);

				if ( $sth->rowCount() == 0) {
					throw new Exception("roles_menu資料表建立失敗");
				}
			}


			$this->pdo_sql->commit();
			return true;
		} catch (Exception $mes){
			$this->pdo_sql->rollBack();
			return $mes->getMessage();
		}
	}

}
?>