<?php
/**
 * 第三方接口
 * User: solu
 * Date: 2018/12/10
 * Time: 4:40 PM
 */

class ThirdApi {

    /**
     * 上报游戏结果
     * @author solu
     * @param $gameId
     * @param $betAmount
     * @param $winAmount
     * @param string $appid
     * @return mixed
     */
    public static function reportGameResult($gameId, $betAmount, $winAmount, $appid = 'box') {
        $api = URL_SICBO . 'eos/gameResult';
        $data = [
            'gameid' => $gameId,
            'game_name' => $appid,
            'bet_amount' => $betAmount,
            'win_amount' => $winAmount,
        ];
        $objEosAES = new EosAES($GLOBALS['codeGtAdmin']);
        $objHttp = new dwHttp();

        $seed = "{$appid}|{$gameId}";
        $data['sign'] = $objEosAES->encode($seed);

        $resp = $objHttp->post2($api, $data);
        return json_decode($resp, true);
    }

    /**
     * 推送事件
     * @author solu
     * @param $channel
     * @param $data
     * @param null $objRedis
     * @return int
     */
    public static function event($channel, $data, $objRedis = null) {
        !$objRedis && $objRedis = dwRedis::initNewOne();

        if (is_array($data)) {
            $data = json_encode($data);
        }

        return $objRedis->publish($channel, $data);
    }

    public static function pushPersonEvent($to, array $data) {
        $channel = "chat:person:{$to}";
        !$data['timestamp'] && $data['timestamp'] = Session::getMS();
        return self::event($channel, $data);
    }

    public static function pushGroupEvent($groupId, array $data) {
        $channel = 'chat:group'; // 全局
        !$data['timestamp'] && $data['timestamp'] = Session::getMS();
        $data['group_id'] = (int) $groupId;
        $groupId > 0 && $channel .= ":{$groupId}";

        return self::event($channel, $data);
    }

    /**
     * 校验Telegram数据合法性
     * @param $auth_data
     * @return mixed
     * @throws Exception
     */
    public static function checkTelegramAuthorization($auth_data) {
        $check_hash = $auth_data['hash'];
        unset($auth_data['hash']);

        $hash = self::genTelegramHash($auth_data);
        if (strcmp($hash, $check_hash) !== 0) {
            throw new Exception('Data is NOT from Telegram');
        }
        if ((time() - $auth_data['auth_date']) > 86400) {
            throw new Exception('Data is outdated');
        }

        return $auth_data;
    }

    public static function genTelegramHash($auth_data) {
        $data_check_arr = [];
        foreach ($auth_data as $key => $value) {
            $data_check_arr[] = $key . '=' . $value;
        }
        sort($data_check_arr);
        $data_check_string = implode("\n", $data_check_arr);

        $secret_key = hash('sha256', BOT_TOKEN, true);
        $hash = hash_hmac('sha256', $data_check_string, $secret_key);

        return $hash;
    }

    /**
     * 获取群创建者id
     * @author solu
     * @param $groupId
     * @return int
     */
    public static function getTelegramGroupCreator($groupId) {
        if (!$groupId) {
            return 0;
        }

        $url = TELEGRAM_API_URL . 'getChatAdministrators?chat_id=' . $groupId;
        $resp = (new dwHttp())->get($url);
        $resp = json_decode($resp, true);
        $data = $resp['result'];

        $creatorId = 0;
        foreach ($data as $u) {
            if ($u['status'] == 'creator') {
                $creatorId = intval($u['user']['id']);
                break;
            }
        }

        return $creatorId;
    }

    /**
     * 聊天消息
     * @author solu
     * @param $groupId
     * @return array
     */
    public static function getTelegramChatInfo($groupId) {
        if (!$groupId) {
            return [];
        }

        $url = TELEGRAM_API_URL . 'getChat?chat_id=' . $groupId;
        $resp = (new dwHttp())->get($url);
        $resp = json_decode($resp, true);

        if (!$resp['ok']) {
            return [];
        }

        return $resp['result'];
    }
}