<?php

namespace App\Game\Services;

use App\Util;
use GuzzleHttp\Client;

class AtmosferaService
{
    protected $client;
    protected $baseUrl;
    protected $privateKey;

    protected $contractor;

    public function __construct()
    {
        $this->client = new Client();
        $this->baseUrl = "https://atmob2b.net";
        $this->privateKey = "PqcOolNF5gusaMiQGxzOIrSey3qp0Adw";
        $this->contractor = 105;
//        $this->baseUrl = "https://api-bb.igramba.com:30445";
//        $this->privateKey = "c48BgNi8p8xsebe0wGMGhICfDeyo0Xzx";
//        $this->contractor = 105;
    }

    // 生成SHA256签名
    protected function generateSignature($time, $data)
    {
        return hash('sha256', $time . json_encode($data) . $this->privateKey);
    }

    public function checkSignature($post)
    {
        Util::WriteLog('24680_atmosfera',$post);
        return true;
        $hash =  hash('sha256', $post['time'] . $post['data'] . $this->privateKey);
        return $hash === $post['hash'];
    }

    // 发送POST请求
    protected function postRequest($endpoint, $time, $data)
    {
        $hash = $this->generateSignature($time, $data);
        $post = [
            'contractor' => $this->contractor,
            'version' => 3,
            'time' => $time,
            'data' => json_encode($data),
            'hash' => $hash
        ];
//        echo $this->baseUrl . $endpoint;
//        echo "\r\n";
//        echo "\r\n";
//        echo json_encode($post);
//        echo "\r\n";
//        echo "\r\n";
        Util::WriteLog('24680_atmosfera_req', $this->baseUrl . $endpoint);
        Util::WriteLog('24680_atmosfera_req', $post);
        $rs = Util::curlPost2($this->baseUrl . $endpoint,$post,true);
        Util::WriteLog('24680_atmosfera_req', $rs);
        return json_decode($rs, true);
    }

    /**
     * 获取玩家余额
     *
     * @param string $userId 玩家ID，必须是先前传递给create_user_ex方法的值
     * @param int $merchantId 商户ID
     * @param string|null $sessionId 会话ID，可选
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "merchant_id": 0,
     *     "user_id": "123654"
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function getBalance($userId, $merchantId, $sessionId = null)
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'user_id' => $userId,
            'merchant_id' => $merchantId,
            'session_id' => $sessionId
        ];

        return $this->postRequest('/get_balance', $time, $data);
    }

    /**
     * 获取玩家账户详情
     *
     * @param string $userId 玩家ID，必须是先前传递给create_user_ex方法的值
     * @param int $merchantId 商户ID
     * @param string|null $sessionId 会话ID，可选
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "merchant_id": 0,
     *     "user_id": "123654"
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function getAccountDetails($userId, $merchantId, $sessionId = null)
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'user_id' => $userId,
            'merchant_id' => $merchantId,
            'session_id' => $sessionId
        ];

        return $this->postRequest('/get_account_details', $time, $data);
    }

    /**
     * 提现
     *
     * @param string $userId 玩家ID，必须是先前传递给create_user_ex方法的值
     * @param string $transactionId 在ATMOSFERA端的唯一事务标识
     * @param string $currency 货币ISO代码
     * @param float $amount 提现金额
     * @param float $bonusAmount 从玩家的奖金账户中提现的金额
     * @param int $gameType 游戏标识符
     * @param string $gameId 游戏回合标识符
     * @param int $merchantId 商户ID
     * @param string|null $sessionId 会话ID，可选
     * @param bool $bonusGame 如果为true，bonusAmount大于0且amount等于0
     * @param array $betData 包含下注信息的JSON编码数组
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "user_id": "123654",
     *     "transaction_id": "123456_0",
     *     "currency": "EUR",
     *     "amount": 0.25,
     *     "bonus_amount": 0,
     *     "game_type": 70,
     *     "game_id": 1234,
     *     "merchant_id": 1,
     *     "bonus_game": false,
     *     "bet_data": [
     *       {"bet_id": 123, "nominal": 0.15, "content": "{\"numbers\":[34],\"pos\":\"34\"}"},
     *       {"bet_id": 124, "nominal": 0.1, "content": "{\"numbers\":[33],\"pos\":\"33\"}"}
     *     ]
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function withdraw($userId, $transactionId, $currency, $amount, $bonusAmount, $gameType, $gameId, $merchantId, $sessionId = null, $bonusGame = false, $betData = [])
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'user_id' => $userId,
            'transaction_id' => $transactionId,
            'currency' => $currency,
            'amount' => $amount,
            'bonus_amount' => $bonusAmount,
            'game_type' => $gameType,
            'game_id' => $gameId,
            'merchant_id' => $merchantId,
            'session_id' => $sessionId,
            'bonus_game' => $bonusGame,
            'bet_data' => $betData
        ];

        return $this->postRequest('/withdraw', $time, $data);
    }

    /**
     * 存款
     *
     * @param string $userId 玩家ID，必须是先前传递给create_user_ex方法的值
     * @param string $transactionId 在ATMOSFERA端的唯一事务标识
     * @param string $currency 货币ISO代码
     * @param float $amount 存款金额
     * @param string $startOperationId 在withdraw方法中接收到的操作ID
     * @param int $gameType 游戏标识符
     * @param string $gameId 游戏回合标识符
     * @param string $gameData 包含游戏结果信息的字符串或对象
     * @param int $merchantId 商户ID
     * @param string|null $sessionId 会话ID，可选
     * @param bool $bonusGame 如果为true，表示奖金游戏
     * @param array $betData 包含下注信息的JSON编码数组
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "user_id": "123654",
     *     "transaction_id": "123457_0",
     *     "start_operation_id": "123",
     *     "currency": "EUR",
     *     "amount": 1,
     *     "game_type": 70,
     *     "game_id": 1234,
     *     "merchant_id": 1,
     *     "game_data": "{\"balls\":[3],\"cards\":null}",
     *     "bonus_game": false,
     *     "bet_data": [
     *       {"bet_id": 123, "win_amount": 1, "jp_amount": 0},
     *       {"bet_id": 124, "win_amount": 0, "jp_amount": 0}
     *     ]
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function deposit($userId, $transactionId, $currency, $amount, $startOperationId, $gameType, $gameId, $gameData, $merchantId, $sessionId = null, $bonusGame = false, $betData = [])
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'user_id' => $userId,
            'transaction_id' => $transactionId,
            'currency' => $currency,
            'amount' => $amount,
            'start_operation_id' => $startOperationId,
            'game_type' => $gameType,
            'game_id' => $gameId,
            'game_data' => $gameData,
            'merchant_id' => $merchantId,
            'session_id' => $sessionId,
            'bonus_game' => $bonusGame,
            'bet_data' => $betData
        ];

        return $this->postRequest('/deposit', $time, $data);
    }

    /**
     * 回滚
     *
     * @param string $userId 玩家ID，必须是先前传递给create_user_ex方法的值
     * @param string $transactionId 需要回滚的提现事务的唯一标识符
     * @param int $merchantId 商户ID
     * @param string|null $sessionId 会话ID，可选
     * @param bool $bonusGame 如果为true，表示奖金游戏
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "user_id": "123654",
     *     "transaction_id": "123457_0",
     *     "merchant_id": 1
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function rollback($userId, $transactionId, $merchantId, $sessionId = null, $bonusGame = false)
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'user_id' => $userId,
            'transaction_id' => $transactionId,
            'merchant_id' => $merchantId,
            'session_id' => $sessionId,
            'bonus_game' => $bonusGame
        ];

        return $this->postRequest('/rollback', $time, $data);
    }

    // 调用API方法：check_user_ex
    /**
     * 调用API方法：check_user_ex
     *
     * @param string $extUserId 集成商系统中的用户ID
     * @param int|null $merchantId 集成商系统中的商户ID，可选
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "ext_user_id": "test"
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function checkUserEx($extUserId, $merchantId = 0)
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'ext_user_id' => strval($extUserId),
            'merchant_id' => $merchantId
        ];

        return $this->postRequest('/check_user_ex', $time, $data);
    }

    // 调用API方法：create_user_ex
    /**
     * 调用API方法：create_user_ex
     *
     * @param string $extUserId 集成商系统中的用户ID
     * @param int|null $merchantId 集成商系统中的商户ID，可选
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "ext_user_id": "test"
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function createUserEx($extUserId, $merchantId = 0)
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'ext_user_id' => strval($extUserId),
            'merchant_id' => $merchantId
        ];

        return $this->postRequest('/create_user_ex', $time, $data);
    }

    // 调用API方法：register_token_ex
    /**
     * 调用API方法：register_token_ex
     *
     * @param string $extUserId 集成商系统中的用户ID
     * @param int|null $merchantId 集成商系统中的商户ID，可选
     * @param string|null $sessionId 集成商系统中的会话ID，可选
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "ext_user_id": "test",
     *     "merchant_id": 1,
     *     "session_id": "session123"
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function registerTokenEx($extUserId, $merchantId = 0, $sessionId = 'session123')
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'ext_user_id' => strval($extUserId),
            'merchant_id' => $merchantId,
            'session_id' => $sessionId
        ];

        return $this->postRequest('/register_token_ex', $time, $data);
    }

    // 调用API方法：create_demo_user
    /**
     * 调用API方法：create_demo_user
     *
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {},
     *   "hash": "123456789987654321"
     * }
     */
    public function createDemoUser()
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [];

        return $this->postRequest('/create_demo_user', $time, $data);
    }

    // 调用API方法：settings/games_list
    /**
     * 调用API方法：settings/games_list
     *
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {},
     *   "hash": "123456789987654321"
     * }
     */
    public function getGamesList()
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [];

        return $this->postRequest('/settings/games_list', $time, $data);
    }

    // 调用API方法：reports/game/ext_cashback_bets
    /**
     * 调用API方法：reports/game/ext_cashback_bets
     *
     * @param string $startDate UTC起始日期
     * @param string $stopDate UTC结束日期
     * @param int $gameType 游戏类型
     * @param string|null $extUserId 可选，集成商系统中的玩家ID
     * @return array 响应数据
     *
     * 调用示例:
     * {
     *   "time": "31-12-2018 10:35:58",
     *   "data": {
     *     "start_date": "2023-01-01",
     *     "stop_date": "2023-01-31",
     *     "game_type": 70,
     *     "ext_user_id": "123"
     *   },
     *   "hash": "123456789987654321"
     * }
     */
    public function getCashbackBets($startDate, $stopDate, $gameType, $extUserId = null)
    {
        $time = now()->format('d-m-Y H:i:s');
        $data = [
            'start_date' => $startDate,
            'stop_date' => $stopDate,
            'game_type' => $gameType,
            'ext_user_id' => $extUserId
        ];

        return $this->postRequest('/reports/game/ext_cashback_bets', $time, $data);
    }
}

