<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{
	/**
	 * Leo
	 * 取得機器列表
	 * @param start_date, end_date, store
	 * @return list[]
	 */
	public function SelectCashierList($params)
	{


		$a_where_arr = []; //sql條件陣列 
		$a_where_arr_val = [];
		$s_where_arr = ""; //sql條件字串，用$a_where_arr條件陣列轉換而來

		// 門市判斷條件
		if ($params['store'] != 0) {
			$a_where_arr[] = "_c.store_id = :store";
			$a_where_arr_val["store"] = $params['store'];
		}
		//門市查詢控制項 store_ctrl 0:只顯示營運中門市 1:顯示全門市
		if ($this->store_ctrl == 0) {
			$a_where_arr[] = " _s.store_state = 1 ";
		}
		//sql條件陣列轉換
		if (!empty($a_where_arr)) {
			$s_where_arr = " WHERE " . implode(" AND ", $a_where_arr);
		}
		//拼接sql字串
		$sql = sprintf(
			"SELECT 
				_c.cashier_id,
				_c.cashier_name,
				_c.update_at,
				_s.store_name,
				_s.store_otp,
				_s.store_otp_invalid_at
			FROM 
				[%s].[dbo].[cashier] AS _c
				LEFT JOIN [%s].[dbo].[store] AS _s ON _s.store_id = _c.store_id
			%s
			",
			$this->database_trend,
			$this->database_trend,
			$s_where_arr
		);
		//準備執行sql
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute($a_where_arr_val);
		$row = $sth->fetchAll(PDO::FETCH_ASSOC);
		$res = [];
		foreach ($row as $k => &$v) {
			$n_store_otp_invalid_at = empty($v["store_otp_invalid_at"]) ? 0 : strtotime($v["store_otp_invalid_at"]);
			$v["store_otp"] = time() > $n_store_otp_invalid_at ? "" : $v["store_otp"];
			if (!in_array("otp_show", $_SESSION["user_menu_permissions"]["cashier_manage"]["function"])) {
				unset($v["store_otp"]);
			}
			unset($v["store_otp_invalid_at"]);
			$res[] = $v;
		}
		return $res;
	}
	/**
	 * Leo
	 * 編輯機台(撈取編輯資料)
	 */
	public function SelectEditCashierInfo($params)
	{
		$s_cashier_id = (string) $params["cashier"];
		//拼接sql字串
		$sql = sprintf(
			"SELECT 
				_c.cashier_id,
				_c.cashier_name
			FROM 
				[%s].[dbo].[cashier] AS _c
			WHERE
				_c.cashier_id = :cashier_id
			",
			$this->database_trend
		);
		//準備執行sql
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute([
			"cashier_id" => $s_cashier_id
		]);
		return $sth->fetch(PDO::FETCH_ASSOC);
	}
	/**
	 * Leo
	 * 更新機台
	 */
	public function ChangeUpdateCashierInfo($params)
	{
		$s_cashier_id = (string) $params["cashier"];
		$s_cashier_name = (string) $params["cashier_name"];

		$sql = sprintf(
			"UPDATE [%s].[dbo].[cashier] 
				SET 
				[cashier_name] = :cashier_name
				WHERE
					[cashier_id] = :cashier_id;
				",
			$this->database_trend
		);
		//準備執行sql
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute([
			"cashier_id" => $s_cashier_id,
			"cashier_name" => $s_cashier_name,
		]);
		if ($sth->rowCount() == 0) {
			throw new Exception("cashier資料表更新失敗");
		}
		return true;
	}
}
