<?php
trait base_class_api
{

    //Leo 外部API token驗證
    public function shopee_api_token_verify($token, $api_key, $time)
    {
        $res = false;
        $s_local_token = md5("shopee_api_key=" . $api_key . "&time=" . $time);
        //判斷token時間是否逾時
        $n_timeout_sec = time() - $time;
        if (
            // $n_timeout_sec < 30 &&
            $token == $s_local_token
        ) {
            $res = true;
        }
        return $res;
    }
    //Leo 時間格式驗證
    public function check_date_format($s_datetime)
    {
        $res = false;
        $check_datetime = date("Y-m-d H:i:s", strtotime($s_datetime));
        if ($check_datetime == $s_datetime) {
            $res = true;
        } else if (
            substr($check_datetime, 0, 10) == substr($s_datetime, 0, 10)
        ) {
            $res = true;
        }
        return $res;
    }
    //Leo 時間戳格式驗證(單位秒 10位)
    public function check_timestamp_format($s_timestamp)
    {
        $res = false;

        $check_timestamp = strtotime(date("Y-m-d H:i:s", $s_timestamp));
        if (
            strlen($s_timestamp) == 10 &&
            $s_timestamp === strval($check_timestamp)
        ) {
            $res = true;
        }
        return $res;
    }
    //Leo connect time update 更新機台最後呼叫時間
    public function cashier_connect_time_update($store, $cashier, $send_at)
    {
        $res = false;
        //設定寫入資料
        $s_cashier_id = (string) $cashier;
        $n_store_id = (int) $store;
        $n_send_at = (int) $send_at;

        // $d_last_connect_check_at = date("Y-m-d H:i:s", $n_send_at);
        $d_last_connect_check_at = date("Y-m-d H:i:s");
        //先撈取當前機台狀態
        $sql = sprintf(
            "WITH last_ararm AS (
                SELECT TOP 1 
                    alarm_code,
                    store_id
                FROM
                    [%s].[dbo].[store_alarm_report] 
                WHERE
                    store_id = %s 
                    AND cashier_id = '%s'                
                ORDER BY
                    store_alarm_id DESC
                ) SELECT
                    _c.cashier_state,
                    _la.alarm_code
                FROM
                    [%s].[dbo].[cashier] AS _c
                    LEFT JOIN last_ararm AS _la ON _la.store_id = _c.store_id 
                WHERE
                    _c.store_id = %s 
                    AND _c.cashier_id = '%s'",
            $this->database_alarm,
            $n_store_id,
            $s_cashier_id,
            $this->database_trend,
            $n_store_id,
            $s_cashier_id
        );
        //準備執行sql
        $sth = $this->pdo_sql->prepare($sql);
        $sth->execute();
        $row = $sth->fetch(PDO::FETCH_ASSOC);
        //判斷該門市是否有異常紀錄，以及最後一筆異常紀錄是否為連線異常 (alarm_code = 5)，假設為連線異常則賦歸為連線正常
        $b_reconnect = false;
        if (!empty($row) && in_array($row["alarm_code"], [5])) {
            //撈取正常狀態碼資料
            $sql = sprintf(
                "SELECT 
                        error_name,
                        error_handle
                    FROM
                        [%s].[dbo].[store_error_code_list] 
                    WHERE
                        error_code = 0         
                   ",
                $this->database_alarm
            );
            //準備執行sql
            $sth = $this->pdo_sql->prepare($sql);
            $sth->execute();
            $row = $sth->fetch(PDO::FETCH_ASSOC);

            $s_error_name = $row["error_name"];
            $s_error_handle = $row["error_handle"];




            $b_reconnect = true;
        }
        //開始資料庫更新、寫入
        $this->pdo_sql->beginTransaction();
        try {
            //寫入門市異常警報表 (賦歸為連線正常)
            if ($b_reconnect) {
                $a_insert_arr = [
                    "cashier_id" => $s_cashier_id,
                    "store_id" => $n_store_id,
                    "create_at" => date("Y-m-d H:i:s"),
                    "alarm_code" => 0,
                    "alarm_name" => $s_error_name,
                    "alarm_note" => '連線異常自動復歸',
                    "alarm_handle" => $s_error_handle,
                ];
                $sql_insert = sprintf(
                    "INSERT INTO [%s].[dbo].[store_alarm_report] (
                        cashier_id,
                        store_id,
                        create_at,
                        alarm_code,
                        alarm_name,
                        alarm_note,
                        alarm_handle
                    )
                    VALUES
                        (
                            :cashier_id,
                            :store_id,
                            :create_at,
                            :alarm_code,
                            :alarm_name,
                            :alarm_note,
                            :alarm_handle
                        )",
                    $this->database_alarm
                );

                $sth = $this->pdo_sql->prepare($sql_insert);
                $sth->execute($a_insert_arr);
                if ($sth->rowCount() == 0) {
                    $this->pdo_sql->rollBack();
                    throw new Exception("store_alarm_report寫入失敗", 1);
                }
            }

            //更新 cashier 表
            $a_update_arr = [
                "cashier_id" => $s_cashier_id,
                "store_id" => $n_store_id,
                "last_connect_check_at" => $d_last_connect_check_at,
            ];
            if ($b_reconnect) {
                $a_update_arr["cashier_state"] = 0;
            }
            //拼接sql字串
            if ($b_reconnect) {
                $sql = sprintf(
                    "UPDATE [%s].[dbo].[cashier]
                    SET
                        last_connect_check_at = :last_connect_check_at,
                        cashier_state = :cashier_state
                    WHERE
                        cashier_id = :cashier_id AND 
                        store_id = :store_id           
                    ",
                    $this->database_trend
                );
            } else {
                $sql = sprintf(
                    "UPDATE [%s].[dbo].[cashier]
                    SET
                        last_connect_check_at = :last_connect_check_at
                    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);
            if ($sth->rowCount() == 0) {
                $this->pdo_sql->rollBack();
                throw new Exception("cashier更新失敗", 1);
            }
            $this->pdo_sql->commit();
            $res = true;
        } catch (Exception $e) {
            $s_call_log_file_path = dirname(__FILE__) . "/Api_log/function";
            if (!is_dir($s_call_log_file_path)) {
                mkdir($s_call_log_file_path, 0700, true);
            }
            file_put_contents($s_call_log_file_path . "/" . Date('Y_m_d') . ".txt", print_r(array(
                "time_stamp" => date("Y-m-d H:i:s"),
                "function"  => "cashier_connect_time_update",
                "error" => $e->getMessage(),
                "line" => $e->getLine()
            ), true) . "\r\n", FILE_APPEND);
        }
        return $res;
    }
}
