<?php

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


	public function SelectAlarm($params)
	{
		//時間範圍
		$s_start_at = (string) $params["start_at"];
		$s_start_at = trim($s_start_at);
		$s_end_at = (string) $params["end_at"];
		$s_end_at = trim($s_end_at);
		//指定警報點位
		$s_machine_alarm_list = (string) $params["machine_alarm_list"];
		$s_machine_alarm_list = trim($s_machine_alarm_list);




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


		//時間條件
		$a_where_arr[] =  sprintf("_am.Al_Start_Time BETWEEN :start_at AND :end_at");
		$a_where_arr_val["start_at"] = date("Y-m-d 00:00:00", strtotime($s_start_at));
		$a_where_arr_val["end_at"] = date("Y-m-d 23:59:59", strtotime($s_end_at));

		//警報點位條件
		if ($s_machine_alarm_list != "" && $s_machine_alarm_list != "all") {
			$a_where_arr[] =  sprintf(
				"_am.Al_TAG IN (%s)",
				$s_machine_alarm_list
			);
		}


		//sql條件陣列轉換
		if (!empty($a_where_arr)) {
			$s_where_arr = " WHERE " . implode(" AND ", $a_where_arr);
		}



		$sql = sprintf(
			"SELECT 
				_am.Al_Start_Time,
				_am.Al_Norm_Time,
				_am.Message
			FROM 
				[%s].[dbo].[AlarmMSG] AS _am
			%s
			ORDER BY 
				_am.Al_Start_Time DESC",
			$this->database_alarm,
			$s_where_arr
		);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute($a_where_arr_val);
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}
}
