<?php

namespace App\Http\Controllers\Game;

use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\LogGamecardClick;
use App\Game\Services\OuroGameService;
use App\Game\Services\PlatformService;
use App\Models\AccountsInfo;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use App\Game\Services\AviatrixService;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class AviatrixController extends Controller
{
    protected $aviatrixService;

    public function __construct(AviatrixService $aviatrixService)
    {
        $this->aviatrixService = $aviatrixService;
    }

    /**
     * 健康检查接口，不需要认证
     */
    public function healthCheck()
    {
        Util::WriteLog('24680_aviatri','healthCheck');
        $response = $this->aviatrixService->healthCheck();

        return response()->json($response, 200);
    }

    /**
     * 获取玩家信息
     * 请求参数:
     * - cid: string, 品牌标识
     * - sessionToken: string, 会话令牌
     * - timestamp: integer, 时间戳 (Unix时间格式)
     *  示例请求数据:
     *  {
     *    "cid": "somebrand",
     *    "sessionToken": "abc123",
     *    "timestamp": 1617181723
     *  }
     */
    public function getPlayerInfo(Request $request)
    {
        $post = $request->post();
        $signature = $request->header('X-Auth-Signature');
        if(!$this->aviatrixService->checkSignature($post,$signature)){
           // return response()->json(['message' => 'Invalid authentication signature'], 400);
        }
        $sessionToken = $post['sessionToken'];
        $sessionToken = str_pad(strtr($sessionToken, '-_', '+/'), strlen($sessionToken) % 4, '=', STR_PAD_RIGHT);
        $UserID = Crypt::decryptString($sessionToken);
        if(!$UserID){
            return response()->json(['message' => 'Invalid session token'], 400);
        }
        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = $AccountsInfoModel->Score($UserID);
        $response = ['playerId' => strval($UserID),'country' => 'BR','balance' => intval($score),'currency' => env('CONFIG_24680_CURRENCY')];
        return response()->json($response);
    }

    /**
     * 玩家下注接口
     * 请求参数:
     * - cid: string, 品牌标识
     * - sessionToken: string, 会话令牌
     * - playerId: string, 玩家标识
     * - productId: string, 游戏标识
     * - txId: string, 事务标识
     * - betId: string, 下注标识
     * - roundId: string, 回合标识
     * - amount: integer, 下注金额
     * - currency: string, 货币类型
     * - timestamp: integer, 时间戳 (Unix时间格式)
     * - odds: float, 可选, 赔率
     * - market: string, 可选, 市场类型
     * - outcome: string, 可选, 结果
     * - specifier: string, 可选, 规格
     * - bonusId: string, 可选, 奖金标识
     * - roundClosed: boolean, 可选, 回合是否关闭
     *  示例请求数据:
     *  {
     *    "cid": "somebrand",
     *    "sessionToken": "abc123",
     *    "playerId": "john",
     *    "productId": "nft-aviatrix",
     *    "txId": "4df40f77-2b38-43f4-b264-1d850f5a6715",
     *    "betId": "bet123",
     *    "roundId": "round123",
     *    "amount": 100,
     *    "currency": "EUR",
     *    "timestamp": 1617181723,
     *    "odds": 1.5,
     *    "market": "win",
     *    "outcome": "success",
     *    "specifier": "specifier123",
     *    "bonusId": "bonus123",
     *    "roundClosed": true
     *  }
     */
    public function placeBet(Request $request)
    {
        $post = $request->post();
        $signature = $request->header('X-Auth-Signature');
        if(!$this->aviatrixService->checkSignature($post,$signature)){
            // return response()->json(['message' => 'Invalid authentication signature'], 400);
        }
        $sessionToken = $post['sessionToken'];
        $sessionToken = str_pad(strtr($sessionToken, '-_', '+/'), strlen($sessionToken) % 4, '=', STR_PAD_RIGHT);
        $UserID = Crypt::decryptString($sessionToken);
        if(!$UserID){
            return response()->json(['message' => 'Invalid session token'], 400);
        }

        $res = SetNXLock::getExclusiveLock('bet'.$post['betId'], 86400);
        if (!$res) {
            Util::WriteLog('24680_aviatrix_bet_error',$post);
            return response()->json(['message' => 'Bet limit exceeded'], 403);
        }

        GameCard::$enableStateCheck=false;
        $gamecard=GameCard::where('gid','aviatrix')->first();
        $in_gameid = OuroGameService::getUserInGame($UserID);
        if(!$gamecard){
            $gamecard="notfind :::: ".'aviatrix';
            Util::WriteLog('24680game', compact('in_gameid', 'gamecard', 'UserID'));
        }else {

            if ($in_gameid != intval($gamecard->id)) {
                Util::WriteLog('24680game', compact('in_gameid', 'gamecard', 'UserID'));
//            die;
            }
        }



        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = intval($AccountsInfoModel->Score($UserID));
        $bet = intval($post['amount']);
        if($bet>$score){
            Util::WriteLog('24680_aviatrix_bet_error',[$score,$bet,$UserID]);
            return response()->json(['message' => 'Bet limit exceeded'], 403);
        }

        Redis::set('bet_amount_'.$post['betId'],$bet);
        Redis::expire('bet_amount_'.$post['betId'],120);


        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->decrement('Score', $bet);

        PlatformService::platformBet('aviatrix',$post['productId'],$bet,$UserID);

        $response = ['createdAt' => date('Y-m-d\TH:i:s.vO'),'balance' => intval($score)-$bet];

        Util::WriteLog('24680_aviatrix_bet_res',['createdAt' => date('Y-m-d\TH:i:s.vO'),'balance' => intval($score)-$bet]);

        return response()->json($response);
    }

    /**
     * 处理玩家赢得的奖金
     * 请求参数:
     * - cid: string, 品牌标识
     * - sessionToken: string, 会话令牌
     * - playerId: string, 玩家标识
     * - productId: string, 游戏标识
     * - txId: string, 事务标识
     * - betId: string, 下注标识
     * - roundId: string, 回合标识
     * - amount: integer, 奖金金额
     * - currency: string, 货币类型
     * - timestamp: integer, 时间戳 (Unix时间格式)
     * - operation: string, 操作类型 (例如 SettleBet, CancelBet)
     * - odds: float, 可选, 赔率
     * - market: string, 可选, 市场类型
     * - outcome: string, 可选, 结果
     * - specifier: string, 可选, 规格
     * - bonusId: string, 可选, 奖金标识
     * - roundClosed: boolean, 可选, 回合是否关闭
     *  示例请求数据:
     *  {
     *    "cid": "somebrand",
     *    "sessionToken": "abc123",
     *    "playerId": "john",
     *    "productId": "nft-aviatrix",
     *    "txId": "4df40f77-2b38-43f4-b264-1d850f5a6715",
     *    "betId": "bet123",
     *    "roundId": "round123",
     *    "amount": 500,
     *    "currency": "EUR",
     *    "timestamp": 1617181723,
     *    "operation": "SettleBet",
     *    "odds": 1.5,
     *    "market": "win",
     *    "outcome": "success",
     *    "specifier": "specifier123",
     *    "bonusId": "bonus123",
     *    "roundClosed": true
     */
    public function processWin(Request $request)
    {
        $post = $request->post();
        Util::WriteLog('24680_aviatrix_win',$post);
        $signature = $request->header('X-Auth-Signature');
        if(!$this->aviatrixService->checkSignature($post,$signature)){
            // return response()->json(['message' => 'Invalid authentication signature'], 400);
        }
        $sessionToken = $post['sessionToken'];
        $sessionToken = str_pad(strtr($sessionToken, '-_', '+/'), strlen($sessionToken) % 4, '=', STR_PAD_RIGHT);
        $UserID = Crypt::decryptString($sessionToken);
        if(!$UserID){
            return response()->json(['message' => 'Invalid session token'], 400);
        }


        $res = SetNXLock::getExclusiveLock('win_'.$post['betId'], 86400);
        if (!$res) {
            Util::WriteLog('24680_win_error',$post);
            return response()->json(['message' => 'Invalid session token'], 400);
        }

        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = intval($AccountsInfoModel->Score($UserID));
        $win = intval($post['amount']);
        $bet = Redis::get('bet_amount_'.$post['betId'])?:0;

        //Util::WriteLog('win_data',$post);
        if(true){
            PlatformService::platformWin($UserID,'aviatrix',$post['productId'],$win,$bet,$score+$win);

        }
        $response = ['createdAt' => date('Y-m-d\TH:i:s.vO'),'balance' => intval($score)+$win];
        return response()->json($response);

    }

    /**
     * 处理玩家的促销奖金
     * 请求参数:
     * - cid: string, 品牌标识
     * - sessionToken: string, 会话令牌
     * - playerId: string, 玩家标识
     * - txId: string, 事务标识
     * - amount: integer, 奖金金额
     * - currency: string, 货币类型
     *  示例请求数据:
     *  {
     *    "cid": "somebrand",
     *    "sessionToken": "abc123",
     *    "playerId": "john",
     *    "txId": "4df40f77-2b38-43f4-b264-1d850f5a6715",
     *    "amount": 100,
     *    "currency": "EUR"
     *  }
     */
    public function promoWin(Request $request)
    {
        $data = $request->validate([
            'cid' => 'required|string',
            'sessionToken' => 'required|string',
            'playerId' => 'required|string',
            'txId' => 'required|string',
            'amount' => 'required|integer',
            'currency' => 'required|string',
        ]);

        $response = $this->aviatrixService->promoWin($data);

        return response()->json($response);
    }

    /**
     * 关闭比赛
     * 请求参数:
     * - cid: string, 品牌标识
     * - playerId: string, 玩家标识
     * - productId: string, 游戏标识
     * - matchId: string, 比赛标识
     * - txId: string, 事务标识
     */
    public function closeMatch(Request $request)
    {
        $data = $request->validate([
            'cid' => 'required|string',
            'playerId' => 'required|string',
            'productId' => 'required|string',
            'matchId' => 'required|string',
            'txId' => 'required|string',
        ]);

        $response = $this->aviatrixService->closeMatch($data);

        return response()->json($response);
    }

    public function gameLunch(Request $request)
    {

        $gid=$request->input('gid');
        $level=$request->input('level',1);
        $user = $request->user();
        $userid=$user->UserID;

        GameCard::$enableStateCheck=false;
        $gamecard=GameCard::where('gid',$gid)->first();

        $in_gameid=OuroGameService::getUserInGame($userid,$user->GlobalUID);
        if($in_gameid!=intval($gamecard->id)){
            Util::WriteLog('24680game',compact('in_gameid','gamecard','user'));
//            die;
        }

        $lang=GlobalUserInfo::getLocale();
        $clientLang='en';
        if($lang=='pt')$clientLang='pt';
        else if($lang=='es')$clientLang='es';
        else $clientLang='en';;

        $url = $this->aviatrixService->launchGame($userid, $clientLang);

        LogGamecardClick::recordClick($gamecard->id,$userid);

        echo "<script>
parent.postMessage({cmd:\"closeLoading\"},\"*\");
window.location.href='".$url."';
</script>";
        exit();
    }


    public function lunchGame(Request $request)
    {

        $userid=$request->input('uid',4688302);


        $url = $this->aviatrixService->launchGame($userid, 'pt');


        echo "<script>
parent.postMessage({cmd:\"closeLoading\"},\"*\");
window.location.href='".$url."';
</script>";
        exit();
    }
}

