<?php
require_once "../Parameters.php";
require_once "../auth/func.php";

/*
    門市異常警報 line推播
*/


$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $DataSource, $DataBase_Trend);
$pdo_mssql = new PDO($dsn, $UserID, $Password);

//查詢各類型警報的發送推播與否判斷項
$sql = sprintf(
    "SELECT 
            _secl.error_code
            ,_secl.notify_state            
    FROM 	
        [%s].[dbo].[store_error_code_list] AS _secl 
    ",
    $DataBase_Alarm
);
//準備執行sql
$sth = $pdo_mssql->prepare($sql);
$sth->execute([]);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
//警報發送基礎設定值陣列
$a_store_alarm_sent_set = [];
foreach ($rows as $k => $v) {
    $a_store_alarm_sent_set[$v["error_code"]] = $v["notify_state"];
}

//查詢當前營運中門市的推播情況
$sql = sprintf(
    "SELECT 
            v_salnc.store_id
            ,v_salnc.last_normal_at
            ,v_salnc.count_alarm_code_1
            ,v_salnc.count_alarm_code_2
            ,v_salnc.count_alarm_code_3
            ,v_salnc.count_alarm_code_4
            ,v_salnc.count_alarm_code_5
            ,v_salnc.count_alarm_code_6
            ,v_salnc.count_alarm_code_7
            ,v_salnc.count_alarm_code_8
            ,v_salnc.count_alarm_code_9
            ,v_salnc.count_alarm_code_10
            ,v_salnc.count_alarm_code_11
            
    FROM 	
        [%s].[dbo].[v_store_alarm_line_notify_check] AS v_salnc 
    ",
    $DataBase_Trend
);
//準備執行sql
$sth = $pdo_mssql->prepare($sql);
$sth->execute([]);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
$a_store_alarm_line_notify_state = [];
foreach ($rows as $k => $v) {
    $a_store_alarm_line_notify_state[$v["store_id"]] = [
        "last_normal_at" => trim($v["last_normal_at"]), //最後一次正常警報時間
        "alarm_code" => [ //異常警報發送狀態判斷 如果不等於0代表已經發送過了
            "1" => $v["count_alarm_code_1"] == 0 ? 0 : 1,
            "2" => $v["count_alarm_code_2"] == 0 ? 0 : 1,
            "3" => $v["count_alarm_code_3"] == 0 ? 0 : 1,
            "4" => $v["count_alarm_code_4"] == 0 ? 0 : 1,
            "5" => $v["count_alarm_code_5"] == 0 ? 0 : 1,
            "6" => $v["count_alarm_code_6"] == 0 ? 0 : 1,
            "7" => $v["count_alarm_code_7"] == 0 ? 0 : 1,
            "8" => $v["count_alarm_code_8"] == 0 ? 0 : 1,
            "9" => $v["count_alarm_code_9"] == 0 ? 0 : 1,
            "10" => $v["count_alarm_code_10"] == 0 ? 0 : 1,
            "11" => $v["count_alarm_code_11"] == 0 ? 0 : 1,
        ]
    ];
}

//取出各門市各類型時間區間內的第一筆門市警報(從最後一次正常警報到當下時間)
//需判斷警報發生時間是否已超過系統設定的延遲時間 Delay_check_alarm (預留緩衝 防止機台自行復歸時 產生不必要的警報發送)

$sql = sprintf(
    "SELECT 
        v_seell.store_alarm_id
        ,v_seell.cashier_id
        ,v_seell.store_id
        ,v_seell.create_at
        ,v_seell.alarm_code
        ,v_seell.alarm_name
        ,v_seell.alarm_note
        ,v_seell.alarm_handle   
        ,_s.store_name                 
    FROM 	
        [%s].[dbo].[v_store_each_errorcode_first_log] AS v_seell
        LEFT JOIN  [%s].[dbo].[store] AS _s ON _s.store_id = v_seell.store_id
    WHERE  
        v_seell.create_at <= :delay_at
    ",
    $DataBase_Trend,
    $DataBase_Trend
);
//準備執行sql
$sth = $pdo_mssql->prepare($sql);
$sth->execute([
    "delay_at" => date("Y-m-d H:i:s", strtotime("-" . Delay_check_alarm . " seconds"))
]);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
$a_store_alarm_sent_line = []; //LINE 推播用陣列
$a_store_alarm_update_id = []; //警報更新用警報id陣列 發過的line推播要更新資料表內的判斷藍位
foreach ($rows as $k => $v) {
    //過濾掉異常代碼2:低水位警報 這有另外一支排程做處理 因為還包含子項目的各幣別警報判斷 而且警報發送判斷依據是根據換補時間來決定
    if ($v["alarm_code"] != 2) {
        //如果還沒有發送過line 才需要發送 另外警報本身也須設定發送才會發送
        if (
            $a_store_alarm_sent_set[$v["alarm_code"]] == 1 &&
            $a_store_alarm_line_notify_state[$v["store_id"]]["alarm_code"][$v["alarm_code"]] == 0
        ) {
            //line通知陣列
            $a_store_alarm_sent_line[] = [
                "門市" => $v["store_name"],
                "時間" => date("Y-m-d H:i:s", strtotime($v["create_at"])),
                "異常代碼" => $v["alarm_code"],
                "異常狀況" => $v["alarm_name"],
                "對應動作" => $v["alarm_handle"],
                "備註" => $v["alarm_note"],
            ];
            //資料更新陣列
            $a_store_alarm_update_id[] = $v["store_alarm_id"];
        }
    }
}

//開始發送與更新 如果資料更新陣列是空的就不用跑 
if (!empty($a_store_alarm_update_id)) {
    //資料庫更新
    $s_update_store_alarm_id = implode(",", $a_store_alarm_update_id);
    $sql_update_alarm = sprintf(
        "UPDATE [%s].[dbo].[store_alarm_report] 
        SET 
            [is_sent_notify] = 1 
        WHERE
            [store_alarm_id] IN (%s);",
        $DataBase_Alarm,
        $s_update_store_alarm_id
    );
    $sth = $pdo_mssql->prepare($sql_update_alarm);
    $sth->execute([]);
    //警報發送
    foreach ($a_store_alarm_sent_line as $k => $v) {
        base_class::line_notify($v);
    }
}
