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


    /**
     * Leo
     * 取得門市API金鑰
     */
    public function Select_store_apikey($params)
    {
        //設定查詢資料
        $n_store_id = (int) $params["store"];

        //查詢門市資訊
        $sql = sprintf(
            "SELECT 
                    _s.store_name,
                    _s.store_api_key
			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 異常", 20);
        }
        $res = [
            "store_name" => (string) $row["store_name"],
            "store_api_key" => (string) $row["store_api_key"]
        ];
        return $res;
    }
    /**
     * 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_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);
        }
        //依據Parameters.php內的固定金鑰來進行Token驗證
        $s_api_key = Store_Api_Key;
        if ($this->shopee_api_token_verify($token, $s_api_key, $s_send_at) != true) {
            throw new Exception("Token Verification Failed", 91001);
        }
    }
}
