<?php
// 允許跨網域呼叫
header("Access-Control-Allow-Origin: *");
// 防止session file lock
session_write_close();
require_once ("Parameters.php");

$before_day = 14; // 兩周內的警報資料 for 維持搜尋效能加上時間區間條件

$dsn= sprintf("sqlsrv:Server=%s; Database=%s;", $DataSource, $DataBase_Alarm);
$pdo_sql = new PDO($dsn, $UserID, $Password); 
if (!isset($_GET['ack']) || $_GET['ack'] != "t") {
	$sql = sprintf("SELECT * FROM ( SELECT g_no, Al_Start_Time, Al_Norm_Time, Al_ACK_Time, Al_Type, Al_Tag, Al_Group, Al_Priority, Message, Al_Old, ROW_NUMBER() Over (Partition By Al_Tag Order By Al_Start_Time DESC) AS Sort From %s.dbo.AlarmMSG WHERE Al_Start_Time >= '%s' AND Al_Tag IN ('%s')) as tmp WHERE tmp.Sort = 1 AND tmp.Al_Norm_Time IS NULL AND tmp.Al_Old is NULL", 
		$DataBase_Alarm, date("Y-m-d 00:00:00", strtotime("now -$before_day days")), implode("', '", explode(",", $_GET['tags']))); // AND Al_Old IS NULL 
	$st = $pdo_sql->prepare($sql);
	$st->execute();
	$res = $st->fetchAll(PDO::FETCH_ASSOC);
	//file_put_contents("test.log", print_R($_GET, true)."\r\n".$sql."\r\n".print_r($res, true)."\r\n-----------------\r\n", FILE_APPEND);
	die(json_encode($res));
} else {
	$sql = sprintf("UPDATE %s.dbo.AlarmMSG SET Al_ACK_Time = GETDATE(), user_id = '%s' WHERE g_no IN ('%s')", $DataBase_Alarm, $_GET['uid'], implode("', '", explode(",", $_GET['tags'])));
	$st = $pdo_sql->prepare($sql);
	$st->execute();
	die("Ok");
}
?>