<?php
/* 各API 需有 token_verify() token驗證function ，因各API撈取API金鑰方式不同*/
class WebAPIForMenuPage extends base_class
{

    /**
     * Leo
     * 新增cashiser機器警報
     */
    public function Create_cashier_alarm($params)
    {
        //設定寫入資料
        $s_cashier_id = (string) $params["cashier"];
        $s_create_time = (string) $params["create_at"];
        $n_alarm_code = (int) $params["code"];

        //先查詢機台資訊
        $sql = sprintf(
            "SELECT 
					_c.cashier_id
                    ,_c.store_id
                    ,_s.store_name
			FROM 	
				[%s].[dbo].[cashier] AS _c 
                LEFT JOIN [%s].[dbo].[store] AS _s ON _s.store_id = _c.store_id 
			WHERE
                cashier_id = :cashier_id
			",
            $this->database_trend,
            $this->database_trend
        );

        //準備執行sql
        $sth = $this->pdo_sql->prepare($sql);
        $sth->execute([
            "cashier_id" => $s_cashier_id
        ]);
        $row = $sth->fetch(PDO::FETCH_ASSOC);
        $n_store_id = (int) $row["store_id"];
        $s_store_name = (string) $row["store_name"];

        //查詢異常code資訊
        $sql = sprintf(
            "SELECT 
					_cecl.error_type
                    ,_cecl.error_message
                    ,_cecl.stop_type
			FROM 	
				[%s].[dbo].[cashier_error_code_list] AS _cecl 
			WHERE
                    _cecl.error_code = :error_code
			",
            $this->database_alarm
        );

        //準備執行sql
        $sth = $this->pdo_sql->prepare($sql);
        $sth->execute([
            "error_code" => $n_alarm_code
        ]);
        $row = $sth->fetch(PDO::FETCH_ASSOC);
        $s_alarm_type = $row["error_type"];
        $s_alarm_message = $row["error_message"];
        //判斷是否停機 0:不停機 1:停機 ，根據停機與否來更新cashier_state
        $n_stop_type = $row["stop_type"];
        //cashier_state 當stop_type為0 表示不停機 那此異常訊息為警報類(表示對於現場實際用戶操作影響不大), cashier_state 帶入1
        //當stop_type為1 表示停機 那此異常訊息為異常類(表示現場實際用戶已無法完成取貨操作), cashier_state 帶入2
        // cashier_state 0:正常 1:警報 2:異常 3:未上線
        $n_cashier_state = $n_stop_type == 1 ? 2 : 1;

        //開始 beginTransaction
        $this->pdo_sql->beginTransaction();

        //寫入 cashier_alarm_report 表
        $a_insert_arr = [
            "cashier_id" => $s_cashier_id,
            "store_id" => $n_store_id,
            "create_at" => $s_create_time,
            "alarm_type" => $s_alarm_type,
            "alarm_code" => $n_alarm_code,
            "alarm_message" => $s_alarm_message,
        ];
        //拼接sql字串
        $sql = sprintf(
            "INSERT INTO [%s].[dbo].[cashier_alarm_report](
                cashier_id,
                store_id,
                create_at,
                alarm_type,
                alarm_code,
                alarm_message
            )
            VALUES
            (
                :cashier_id,
                :store_id,
                :create_at,
                :alarm_type,
                :alarm_code,
                :alarm_message
            )
			",
            $this->database_alarm
        );
        //準備執行sql
        $sth = $this->pdo_sql->prepare($sql);
        $sth->execute($a_insert_arr);

        // //更新 cashier 表
        // $a_update_arr = [
        //     "cashier_id" => $s_cashier_id,
        //     "store_id" => $n_store_id,
        //     "cashier_state" => $n_cashier_state,
        // ];
        // //拼接sql字串
        // $sql = sprintf(
        //     "UPDATE [%s].[dbo].[cashier]
        //     SET
        //         cashier_state = :cashier_state
        //     WHERE
        //         cashier_id = :cashier_id AND 
        //         store_id = :store_id           
        // 	",
        //     $this->database_trend
        // );
        // //準備執行sql
        // $sth = $this->pdo_sql->prepare($sql);
        // $sth->execute($a_update_arr);


        //結束 Transaction 執行寫入
        $this->pdo_sql->commit();
        return "OK";
    }
    /**
     * Leo
     * api 驗證
     */
    public function api_verify($token, $params)
    {
        //門市編號
        $n_store_id = (int) $params["store"];
        if ($n_store_id == 0) { //門市編號為空
            throw new Exception("store 欄位不可為空", 91000);
        } else {    //檢查門市是否存在
            $sql = sprintf(
                "SELECT 
                        _s.store_id
                FROM 	
                    [%s].[dbo].[store] AS _s 
                WHERE
                    _s.store_id = :store_id ",
                $this->database_trend
            );
            //準備執行sql
            $sth = $this->pdo_sql->prepare($sql);
            $sth->execute([
                "store_id" => $n_store_id
            ]);
            $row = $sth->fetch(PDO::FETCH_ASSOC);
            if (empty($row)) {
                throw new Exception("store 異常", 91000);
            }
        }
        //機台序號
        $s_cashier_id = (string) $params["cashier"];
        if ($s_cashier_id == "") { //機台編號為空
            throw new Exception("cashier 欄位不可為空", 91000);
        } else { //檢查機台是否存在
            $sql = sprintf(
                "SELECT 
                        _c.cashier_id
                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
            ]);
            $row = $sth->fetch(PDO::FETCH_ASSOC);
            if (empty($row)) {
                throw new Exception("cashier error", 91000);
            }
        }
        //時間戳(單位秒)
        $s_send_at = (string) $params["send_at"];
        if ($s_send_at == "") { //時間戳為空
            throw new Exception("send_at 欄位不可為空", 91000);
        } else if ($this->check_timestamp_format($s_send_at) != true) {
            throw new Exception("send_at format error", 91000);
        }
        //Token
        if (trim($token) == "") { //Token為空
            throw new Exception("token 欄位不可為空", 91000);
        }
        //異常Code
        $n_alarm_code = (int) $params["code"];
        if (!isset($params["code"])) { // 異常Code為空
            throw new Exception("code 欄位不可為空", 91000);
        } else { //檢查異常Code是否存在
            $sql = sprintf(
                "SELECT 
                        _cecl.error_code
                FROM 	
                    [%s].[dbo].[cashier_error_code_list] AS _cecl 
                WHERE
                    _cecl.error_code = :error_code ",
                $this->database_alarm
            );
            //準備執行sql
            $sth = $this->pdo_sql->prepare($sql);
            $sth->execute([
                "error_code" => $n_alarm_code
            ]);
            $row = $sth->fetch(PDO::FETCH_ASSOC);
            if (empty($row)) {
                throw new Exception("code does not exist", 91000);
            }
        }
        //異常create_at
        $s_create_at = (string) $params["create_at"];
        if ($s_create_at == "") { // 異常create_at為空
            throw new Exception("create_at 欄位不可為空", 91000);
        } else if ($this->check_date_format($s_create_at) != true) { //時間格式不正確
            throw new Exception("create_at 時間格式不正確", 91000);
        }

        //依據資料查詢門市API金鑰來進行Token驗證
        $sql = sprintf(
            "SELECT 
                    _s.store_api_key,
                    _c.cashier_id
            FROM 	
                 [%s].[dbo].[cashier] AS _c
                 LEFT JOIN [%s].[dbo].[store] AS _s ON _s.store_id = _c.store_id
            WHERE
                _c.store_id = :store_id AND
                _c.cashier_id = :cashier_id",
            $this->database_trend,
            $this->database_trend
        );
        //準備執行sql
        $sth = $this->pdo_sql->prepare($sql);
        $sth->execute([
            "store_id" => $n_store_id,
            "cashier_id" => $s_cashier_id
        ]);
        $row = $sth->fetch(PDO::FETCH_ASSOC);
        if (!empty($row)) {
            $s_api_key = $row["store_api_key"];
            if ($this->shopee_api_token_verify($token, $s_api_key, $s_send_at) != true) {
                throw new Exception("Token Verification Failed", 91001);
            }
        } else {
            //查詢不到該門市該機台
            throw new Exception("store and cashier not binding", 91000);
        }

        //更新最後連線時間
        $this->cashier_connect_time_update($n_store_id, $s_cashier_id, $s_send_at);
    }
}
