<?php

namespace App\Http\Controllers\Game;

use App\Facade\TableName;
use App\Game\Config\PgSimData;
use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\LogGamecardClick;
use App\Game\Services\OuroGameService;
use App\Game\Services\PgSoftService;
use App\Game\Services\PlatformService;
use App\Game\Services\ServerService;
use App\Models\AccountsInfo;
use App\Notification\TelegramBot;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PgSimController extends Controller
{



    public function __construct()
    {

    }


    public function gameLunch(Request $request)
    {

        $gid = $request->input('gid');
        $level = $request->input('level',0);
        $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;
        }

        $gamecard = GameCard::where('gid', $gid)->where('brand', 'PGSoft')->first();
        $gamecard->increment('play_num', 1);
        //$this->logGameClick($gamecard->id,$userid);

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

        $lang = GlobalUserInfo::getLocale();
        $supportLang = ['en', 'da', 'de', 'es', 'fi', 'fr', 'id', 'it', 'ja', 'ko', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sv', 'th', 'tr', 'vi', 'zh', 'my'];
        if (!in_array($lang, $supportLang)) {
            $lang = 'en';
        }

        $configurls=json_decode(env('CONFIG_GAMES'),true);
        $configurl=$configurls['pg'];

        $cdnserver = 'https://'.$configurl['source'];
        $sign = GlobalUserInfo::genGuuidSign($user);
        $or = $this->convertString($configurl['source']);

        $api = $configurl['api'];
        if($userid==80000140){
            $api="api.pgn-nmu2nd.com";
        }
//        $api = $this->convertString($this->GetApiSite());
//        $api = $this->convertString('api.pgn-nmu2nd.com');

        $params = ['l' => $lang, 'ot' => $sign, 'btt' => $level>0?$level+2:1, 't' => $user->GlobalUID, 'or' => $or, 'api' => $api,'__hv'=>'2fMEQCIFLydRxh8H68maL+JBCLPYwNvVYnfrj2F2sz6vZlvN8RAiBwtO1MPOn3EEGrB37KWtvUkTvvwOE6pUJneC1YekbBjw=='];
        $url = $cdnserver . "/$gid/index.html?" . http_build_query($params);
//        https://static2.pgn-nmu2nd.com/57/index.html?l=zh&ot=&btt=1&t=917c74999c-b53b-eb1a-0004478930&or=static2.pgn-nmu2nd.com&api=api.pgn-nmu2nd.com



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

    public function leaveOrg(Request $request){

        $UserID = $request->UserID;

        $api=$this->GetApiSite();

        try {
            file_get_contents("https://$api/game-api/000/v2/removePlayer/Get?UserID=$UserID");
        }catch (\Exception $e){

        }
        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreLocker')
            ->where('UserID', $UserID)
            ->delete();
        return '<script>
            if(window.parent&&window.parent!=window){
                window.parent.postMessage("backhome","*")
            }else {
                document.location = "game://a=1&b=2";
            }
</script>';
    }
    public function gameLunchOrg(Request $request)
    {
        if(!$request->isSecure()){
            return redirect(env('APP_URL'). $_SERVER['REQUEST_URI']);
        }
        $gid = $request->input('gid');
        $level=$request->input('level',0);
        $lang=$request->input('lang','pu');

        $lang=['pu'=>'pt','en'=>'en','sp'=>'es','ur'=>'en'][$lang]??$lang;

        $userid = $request->UserID;
        $GlobalUID = 'a1b1c1-b53b-'.ServerService::GetLocalSign().'-' . $userid;

        if($userid>10000000&&$userid<20000000){
            $GlobalUID='a1b1c1-b53b-eb1a-'.$userid;
        }

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

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


//        $gamecard = GameCard::where('gid', $gid)->where('brand', 'PGSoft')->first();
//        $gamecard->increment('play_num', 1);
        //$this->logGameClick($gamecard->id,$userid);

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

//        $lang = GlobalUserInfo::getLocale();
        $supportLang = ['en', 'da', 'de', 'es', 'fi', 'fr', 'id', 'it', 'ja', 'ko', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sv', 'th', 'tr', 'vi', 'zh', 'my'];
        if (!in_array($lang, $supportLang)) {
            $lang = 'en';
        }
        $cdnserver = 'https://static4.pgn-nmu2nd.com';
        $LogonPass='123';
        $sign = GlobalUserInfo::genGuuidSign((object)compact('GlobalUID','LogonPass'));
        $or = $this->convertString('static4.pgn-nmu2nd.com');
        $api = $this->GetApiSite($GlobalUID);//$this->convertString($this->GetApiSite());
//        $api = $this->convertString('api.pgn-nmu2nd.com');

        $params = ['l' => $lang, 'ot' => $sign, 'btt' => $level>0?$level+2:1, 't' => $GlobalUID, 'or' => $or, 'api' => $api,'_tt'=>time(),'__hv'=>'2fMEQCIFLydRxh8H68maL+JBCLPYwNvVYnfrj2F2sz6vZlvN8RAiBwtO1MPOn3EEGrB37KWtvUkTvvwOE6pUJneC1YekbBjw=='];
        $url = $cdnserver . "/$gid/index.html?" . http_build_query($params);
//        https://static2.pgn-nmu2nd.com/57/index.html?l=zh&ot=&btt=1&t=917c74999c-b53b-eb1a-0004478930&or=static2.pgn-nmu2nd.com&api=api.pgn-nmu2nd.com
//        dd($url);
        $trans="rotated-iframe-container";


        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($userAgent,"iPhone") || strpos($userAgent,"iPad") || strpos($userAgent,"iPod")){

        }else{
            if($request->input('norot',0)==1){
                $trans="no-rotated-iframe-container";
            }
        }

        $leaveUrl=$request->getSchemeAndHttpHost().'/api/pgsoft/leave?UserID='.$userid;
        echo '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PGSoft</title>
    <style>
       body, html {
            margin: 0;
            padding: 0;
            background: #000;
            height: 100vh;
            overflow: hidden;
            -webkit-overflow-scrolling: touch; /* 启用惯性滚动 */
        }

        .rotated-iframe-container {
            width: 100vh; /* 旋转后高度变为宽度 */
            height: 100vw; /* 旋转后宽度变为高度 */
            transform: rotate(-90deg);
            transform-origin: top right;
            position: absolute;
            top: 0;
            right: 100%;
            overflow: hidden;
        }

        .no-rotated-iframe-container {
            width: 100vw; /* 旋转后高度变为宽度 */
            height: 100vh; /* 旋转后宽度变为高度 */
            position: absolute;
            top: 0;
        }

        .rotated-iframe {
            width: 100%;
            height: 100%;
            transform-origin: top right;
        }
    </style>
</head>
<body>
    <script>
    document.addEventListener("touchstart", (e) => {
    // 确保滑动事件生效
}, { passive: true });

document.addEventListener("touchmove", (e) => {
    // 确保惯性滚动生效
}, { passive: true });
    window.addEventListener("message", ()=>{
        var xhr = new XMLHttpRequest();
        var url = "'.$leaveUrl.'"; // 这里替换成你实际要访问的 URL
        console.log(url);
        xhr.open("GET", url, true);
        xhr.send();
        setTimeout(()=>{
            if(window.parent&&window.parent!=window){
                window.parent.postMessage("backhome","*")
            }else {
                document.location = "game://a=1&b=2";
            }
        },500)
//        document.body.innerHTML=`<span style="color:#fff">${url}</span>`;
    })
</script>
<div class="'.$trans.'">
    <!-- 嵌入的 iframe -->
    <iframe class="rotated-iframe" frameborder="0" src="'.$url.'"></iframe>
</div>
</body>
</html>';

        return "";
    }

    private function convertString($input)
    {
        return "13" . str_rot13($input);
    }


    private function log(Request $request, $addLog = "")
    {
        $post = $request->all();
        Util::WriteLog('pgsim', $post);
        if (!empty($addLog)) Util::WriteLog('pgsim', $addLog);
    }

    public function GetByResourcesTypeIds(Request $request)
    {
        $this->log($request);
        return PgSimData::$typeids;
    }

    public function BetSummary(Request $request)
    {
        $this->log($request);
        ///gid: 1543462
        //dtf: 1722355200000
        //dtt: 1722959999999
        //atk: S2VS1R6P-Q3B7-785R-WBRP-7EBO6LC651V3
        //pf: 4
        //wk: 0_C
        //btt: 1

        $gid = intval($request->gid);
        if ($gid != 1543462) {
            return [
                "dt"  => [
                    "lut" => $request->dtf,
                    "bs"  => [
                        "gid"   => $gid,
                        "bc"    => 8,
                        "btba"  => 4,
                        "btwla" => -3.40,
                        "lbid"  => 12123212211111221,
                    ]
                ],
                "err" => null
            ];

        }
//        Redis::setex($newToken,3600,json_encode($data));
        $user = json_decode(Redis::get($request->atk));
        if (!$user) return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];

        $UserID = $user->UserID;
        $record = DB::connection('mysql')->table('webgame.PgRecords')
            ->where('uid', $UserID)
            ->where('gid', $request->gid)
            ->whereBetween('bt', [$request->dtf, $request->dtt])
            ->selectRaw('count(*) as bc,sum(gtba) as btba,sum(gtwla) as btwla,max(tid) as lbid,max(bt) as lut')->get()->toArray();
        $record = (array)$record[0];
        return [
            "dt"  => [
                "lut" => $record['lut'] ?? $request->dtf,
                "bs"  => [
                    "gid"   => intval($request->gid),
                    "bc"    => $record['bc'] ?? 0,
                    "btba"  => floatval($record['btba'] ?? 0),
                    "btwla" => floatval($record['btwla'] ?? 0),
                    "lbid"  => $record['lbid'] ?? null,
                ]
            ],
            "err" => null
        ];

    }
    public static $readyGames = [1695365, 1543462, 68, 57, 42, 48, 1682240, 126, 98, 89, 104, 1451122, 1492288, 135];
    public function BetHistory(Request $request)
    {
//        $this->log($request);
        ///gid: 1543462
        //dtf: 1722873600000
        //dtt: 1722959999999
        //bn: 1
        //rc: 15
        //atk: 69TN676M-60PU-587G-QKVS-DC319L8RREGJ
        //pf: 4
        //wk: 0_C
        //btt: 1
        $gid = intval($request->gid);
        $beginTime = intval($request->lbt ?? time() * 1000);

        //假数据
        if (!in_array($gid, self::$readyGames)) {
            return $this->returnFakeHistory($gid);
        }


        $user = json_decode(Redis::get($request->atk));
//        if(!$user)return ['dt'=>null,'err'=>'session expired'];
        if (!$user) return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];

        $UserID = $user->UserID;
        $records = DB::connection('mysql')->table('webgame.PgRecords')
            ->where('uid', $UserID)
            ->where('gid', $request->gid)
            ->whereBetween('bt', [$request->dtf, $request->dtt])
            ->where('bt', '<', $beginTime)
            ->selectRaw('tid,gid,cc,gtba,gtwla,bt,gd')
            ->orderBy('id', 'desc')
            ->limit(30)
            ->get()->toArray();
        $items = [];
        foreach ($records as &$record) {
            $record = (array)$record;
            $record['gtba'] = floatval($record['gtba']);
            $record['gtwla'] = floatval($record['gtwla']);
            $record['gd'] = json_decode($record['gd']);
            $bd = [];
            foreach ($record['gd'] as $gd) {
                $gd = (array)$gd;
                $arr = ["tid"  => "1820491964999664640",
                    "tba"  => $gd['tb'],
                    "twla" => $gd['tw'],
                    "bl"   => $gd['bl'],
                    "bt"   => $record['bt'],
                    "gd"   => $gd
                ];
                $bd[] = $arr;
            }
            $ge = $record['gd'][0]->ge;
            if ($ge[0] == 4) $ge[] = 1;

            $items[] = [
                "tid"   => $record['tid'],
                "pid"   => 0,
                "gid"   => $record['gid'],
                "cc"    => $record['cc'],
                "gtba"  => $record['gtba'],
                "gtwla" => $record['gtwla'],
                "bt"    => $record['bt'],
                "ge"    => $ge,
                "mgcc"  => 0,
                "fscc"  => 0,
                "bd"    => $bd
            ];
        }

        $result = [
            "dt"  => [
                "bh" => $items
            ],
            "err" => null
        ];

        return $result;
    }

    private function returnFakeHistory($gid)
    {
        $winitem = [
            "tid"   => "1820491964999664640",
            "pid"   => 0,
            "gid"   => $gid,
            "cc"    => "BRL",
            "gtba"  => 0.5,
            "gtwla" => 0,
            "bt"    => 1722874083597,
            "ge"    => [
                1,
                11
            ],
            "bd"    => [
                [
                    "tid"  => "1820491964999664640",
                    "tba"  => 0.5,
                    "twla" => 0,
                    "bl"   => 310.62,
                    "bt"   => 1722874082006,
                    "gd"   => [
                        "wp"    => [
                            "6" => [
                                1,
                                6,
                                9
                            ],
                            "7" => [
                                1,
                                6,
                                10
                            ]
                        ],
                        "lw"    => [
                            "6" => 0.25,
                            "7" => 0.25
                        ],
                        "orl"   => [
                            5,
                            5,
                            7,
                            99,
                            6,
                            6,
                            5,
                            5,
                            3,
                            5,
                            5,
                            99
                        ],
                        "ift"   => false,
                        "iff"   => false,
                        "cpf"   => [],
                        "cptw"  => 0,
                        "crtw"  => 0,
                        "imw"   => false,
                        "fs"    => null,
                        "gwt"   => -1,
                        "fb"    => null,
                        "ctw"   => 0.5,
                        "pmt"   => null,
                        "cwc"   => 1,
                        "fstc"  => null,
                        "pcwc"  => 1,
                        "rwsp"  => [
                            "6" => 5,
                            "7" => 5
                        ],
                        "hashr" => "0:5;6;3#5;6;5#7;5;5#99;5;99#R#5#011221#MV#0.50#MT#1#R#5#011222#MV#0.50#MT#1#MG#0.50#",
                        "ml"    => 1,
                        "cs"    => 0.05,
                        "rl"    => [
                            5,
                            5,
                            7,
                            99,
                            6,
                            6,
                            5,
                            5,
                            3,
                            5,
                            5,
                            99
                        ],
                        "sid"   => "1820491964999664640",
                        "psid"  => "1820491964999664640",
                        "st"    => 1,
                        "nst"   => 1,
                        "pf"    => 4,
                        "aw"    => 0.5,
                        "wid"   => 0,
                        "wt"    => "C",
                        "wk"    => "0_C",
                        "wbn"   => null,
                        "wfg"   => null,
                        "blb"   => 310.62,
                        "blab"  => 310.12,
                        "bl"    => 310.62,
                        "tb"    => 0.5,
                        "tbb"   => 0.5,
                        "tw"    => 0.5,
                        "np"    => 0,
                        "ocr"   => null,
                        "mr"    => null,
                        "ge"    => [
                            1,
                            11
                        ]
                    ]
                ]
            ],
            "mgcc"  => 0,
            "fscc"  => 0
        ];
        $item = [
            "tid"   => "1820492035749183488",
            "pid"   => 0,
            "gid"   => $gid,
            "cc"    => "BRL",
            "gtba"  => 0.5,
            "gtwla" => -0.5,
            "bt"    => 1722874100124,
            "ge"    => [
                1,
                11
            ],
            "bd"    => [
                [
                    "tid"  => "1820492035749183488",
                    "tba"  => 0.5,
                    "twla" => -0.5,
                    "bl"   => 307.72,
                    "bt"   => 1722874099074,
                    "gd"   => [
                        "wp"    => null,
                        "lw"    => null,
                        "orl"   => [
                            5,
                            5,
                            5,
                            99,
                            6,
                            5,
                            5,
                            7,
                            4,
                            4,
                            6,
                            99
                        ],
                        "ift"   => false,
                        "iff"   => false,
                        "cpf"   => [],
                        "cptw"  => 0,
                        "crtw"  => 0,
                        "imw"   => false,
                        "fs"    => null,
                        "gwt"   => -1,
                        "fb"    => null,
                        "ctw"   => 0,
                        "pmt"   => null,
                        "cwc"   => 0,
                        "fstc"  => null,
                        "pcwc"  => 0,
                        "rwsp"  => null,
                        "hashr" => "0:5;6;4#5;5;4#5;5;6#99;7;99#MV#0.50#MT#1#MG#0#",
                        "ml"    => 1,
                        "cs"    => 0.05,
                        "rl"    => [
                            5,
                            5,
                            5,
                            99,
                            6,
                            5,
                            5,
                            7,
                            4,
                            4,
                            6,
                            99
                        ],
                        "sid"   => "1820492035749183488",
                        "psid"  => "1820492035749183488",
                        "st"    => 1,
                        "nst"   => 1,
                        "pf"    => 4,
                        "aw"    => 0,
                        "wid"   => 0,
                        "wt"    => "C",
                        "wk"    => "0_C",
                        "wbn"   => null,
                        "wfg"   => null,
                        "blb"   => 308.22,
                        "blab"  => 307.72,
                        "bl"    => 307.72,
                        "tb"    => 0.5,
                        "tbb"   => 0.5,
                        "tw"    => 0,
                        "np"    => -0.5,
                        "ocr"   => null,
                        "mr"    => null,
                        "ge"    => [
                            1,
                            11
                        ]
                    ]
                ]
            ],
            "mgcc"  => 0,
            "fscc"  => 0
        ];
        $result = [
            "dt"  => [
                "bh" => [$item, $winitem]
            ],
            "err" => null
        ];

        return $result;
    }

    public function GameWallet(Request $request)
    {
        // Extracted constant for repeated value
        $user = json_decode(Redis::get($request->atk));
//        if(!$user)return ['dt'=>null,'err'=>'session expired'];
        if (!$user||!isset($user->UserID)) return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];

        $score = GlobalUserInfo::getScoreByUserID($user->UserID);
// Original data with more descriptive keys and organized structure

//        $jsonData = [
//            "details" => [
//                "currency" => "BRL",
//                "totalBalance" => $score,
//                "pendingBalance" => 0.00,
//                "currentBalance" => $score,
//                "totalBetBalance" => 0.00,
//                "totalFreeGameBalance" => 0.00,
//                "remainingFreeGamesCount" => 0,
//                "isBonusEnabled" => false,
//                "isFreeGameEnabled" => false,
//                "isExclusiveBonusEnabled" => false,
//                "isExclusiveFreeGameEnabled" => false,
//                "child" => [
//                    "key" => "0_C",
//                    "childId" => 0,
//                    "childBalance" => $score
//                ],
//                "promotion" => null,
//                "ocr" => null
//            ],
//            "error" => null
//        ];
        $Currency = env("CONFIG_24680_CURRENCY", "BRL");
        $CurrencySymbol = env("CONFIG_24680_DOLLAR", "R$");

        $json = [
            "dt"  => [
                "cc"    => $Currency,
                "tb"    => $score,
                "pb"    => 0,
                "cb"    => $score,
                "tbb"   => 0,
                "tfgb"  => 0,
                "rfgc"  => 0,
                "inbe"  => false,
                "infge" => false,
                "iebe"  => false,
                "iefge" => false,
                "ch"    => [
                    "k"   => "0_C",
                    "cid" => 0,
                    "cb"  => $score
                ],
                "p"     => null,
                "ocr"   => null
            ],
            "err" => null
        ];
// Usage example
        return $json;
    }

    public function GameRule(Request $request)
    {
        $this->log($request);
        return '{"dt":{"rtp":{"Default":{"min":96.75,"max":96.75}},"ows":{"itare":true,"tart":1,"igare":true,"gart":2160},"jws":null},"err":null}';
    }

    public function GameName(Request $request)
    {
        $this->log($request);
        ///lang: zh
        //btt: 1
        //atk: K8ZU75Z5-TC66-8163-6Q4W-7XFBU6NIWTQE
        //pf: 4
        //gid: 1543462
        $token = $request->atk;
        $gameid = $request->gid ?? "57";
        $lang = $request->lang ?? "en";
        $gamenames = json_decode(PgSimData::$gamenames, true);
        $supportLang = array_keys($gamenames);//['en','da','de','es','fi','fr','id','it','ja','ko','nl','no','pl','pt','ro','ru','sv','th','tr','vi','zh','my'];
        if (!in_array($lang, $supportLang)) $lang = 'en';
        return response()->json($gamenames[$lang])->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
//        return json_encode($gamenames[$lang],JSON_UNESCAPED_UNICODE);
    }

    public function verifyOperatorPlayerSession(Request $request)
    {
        $this->log($request);


        ///btt: 1
        //vc: 2
        //pf: 4
        //l: zh
        //gi: 1543462
        //os: 917c74999c-b53b-eb1a-0004478930
        //otk: I-226f37ece4604f19a926c0cd709a995c
        return $this->VerifySession($request);
        return [
            "dt"  => null,
            "err" => [
                "cd"  => "1308",
                "msg" => "Player session is expired",
                "tid" => $request->traceId
            ]
        ];
    }

    public function GetByReferenceIdsResourceTypeIds(Request $request)
    {
        return [
            "dt"  => [
                "0"  => [
                    "rid"  => 0,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/default-e16a5d2e.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "1"  => [
                    "rid"  => 2,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m2-de4b8bd8.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "2"  => [
                    "rid"  => 3,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m3-d31d9b62.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "3"  => [
                    "rid"  => 4,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m4-a6308645.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "4"  => [
                    "rid"  => 5,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m5-8eab7ae3.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "5"  => [
                    "rid"  => 6,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m6-19e7aa37.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "6"  => [
                    "rid"  => 7,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m7-8e038206.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "7"  => [
                    "rid"  => 8,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m8-711d3975.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "8"  => [
                    "rid"  => 9,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m9-21680422.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "9"  => [
                    "rid"  => 10,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m10-51eb1a26.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "10" => [
                    "rid"  => 11,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m11-69f2941d.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "11" => [
                    "rid"  => 12,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/m12-db14d865.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "12" => [
                    "rid"  => 13,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f1-3818e131.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "13" => [
                    "rid"  => 14,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f2-057a3e40.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "14" => [
                    "rid"  => 15,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f3-642d52dc.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "15" => [
                    "rid"  => 16,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f4-f3fc5462.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "16" => [
                    "rid"  => 17,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f5-06141292.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "17" => [
                    "rid"  => 18,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f6-1c66ed0b.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "18" => [
                    "rid"  => 19,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f7-1147f29a.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "19" => [
                    "rid"  => 21,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f9-f835d8e6.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "20" => [
                    "rid"  => 22,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f10-54c3b4a4.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "21" => [
                    "rid"  => 23,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f11-9f9a1767.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ],
                "22" => [
                    "rid"  => 24,
                    "rtid" => 13,
                    "url"  => "https://public.pg-demo.com/pages/static/image/en/SocialProfile/f12-5d493e91.png",
                    "l"    => "en-US",
                    "ut"   => "2019-09-27T10:57:09"
                ]
            ],
            "err" => null
        ];

    }

    public function GameUI(Request $request)
    {
        return PgSimData::$gameuis;
    }

    public function TournamentExistance(Request $request)
    {
        return ['dt' => null, 'err' => null];
    }

    public function InitLite(Request $request)
    {
        return ['dt' => null, 'err' => null];
    }

    public function SocialInitConfig(Request $request)
    {
        return [
            "dt"  => [
                "countries"                     => null,
                "achievements"                  => null,
                "levelActionPermissions"        => null,
                "gameChatEmoticonTemplateDatas" => null,
                "gameSpecificThresholdId"       => null,
                "configurationSetting"          => null,
                "onlinePlayerCounts"            => null,
                "playerFavouriteGamesDatas"     => null,
                "playerProfileInfo"             => null,
                "levelBackground"               => null,
                "onlinePlayerCount"             => null
            ],
            "err" => null
        ];
    }

    private function GetApiSite($GlobalUID=null)
    {

        $configurls=json_decode(env('CONFIG_GAMES'),true);
        $configurl=$configurls['pg'];

        return $configurl['api'];
    }
    public function VerifySession(Request $request)
    {
        $this->log($request);

//        btt: 1
//vc: 2
//pf: 4
//l: zh
//gi: 1543462
//tk: 20bb7d43-1ace-43d8-84f5-afa15981b653
//otk: Zm9saWFiZXQ=

        $changeSign=str_ends_with($request->otk,"@");

        //区域跳转
        try {
            $arr = explode('|', Crypt::decryptString($request->otk));
            $this->log($request, $arr);
            $GlobalUID = $arr[0];


//            if (!ServerService::IsLocalUser($GlobalUID)) {
//                return ServerService::RedirectToSub($GlobalUID);
//            }


            $timestamp = intval($arr[1]);
            if (time() > $timestamp) return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];
//            $user = GlobalUserInfo::getGameUserInfo('GlobalUID', $GlobalUID);
        } catch (\Exception $e) {
            if(isset($request->otk)) {
                TelegramBot::getDefault()->sendMsgWithEnv("redirect fail:" . json_encode($request->all()) . $e->getMessage() . $e->getTraceAsString());
                $this->log($request, "wrong user");
            }
            return "";
        }
        if(!isset($GlobalUID)||empty($GlobalUID)){
            return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];
        }
        //不是本地构造的
//        if(!strstr($GlobalUID,'a1b1c1')) {
//            if (!isset($user) || !$user) return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];
//            $data = $user->toArray();
//        }else{
        $data=['UserID'=>ServerService::GlobalToUserID($GlobalUID)];
//        }
//        $GlobalUID=$request->tk;

        $gameid = $request->gi ?? "57";
        $lang = $request->l ?? "en";

        $Currency = env("CONFIG_24680_CURRENCY", "BRL");
        $CurrencySymbol = env("CONFIG_24680_DOLLAR", "R$");

//        $GlobalUID = $user->GlobalUID;
        $PgPlayerID = md5($GlobalUID);
        $newToken = base64_encode(random_bytes(20));

        $data['currency'] = $Currency;
        $data['dollar'] = $CurrencySymbol;

        $roomlevel=$request->btt??1;
        $data['limit_room']=0;
//        if($roomlevel>1){
//            $data['limit_room']=1;
//        }

        $account = AccountsInfo::where('UserID', $data['UserID'])->first();
        if(!$account){
            TelegramBot::getDefault()->sendMsgWithEnv("VerifySession fail11111:" . json_encode([$request->all(),$data]) );
            return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];
        }else{
            $account=$account->toArray();
        }
        $data = array_merge($data, $account);

        Redis::setex($newToken, 7200, json_encode($data));
//        Redis::set($newToken,json_encode($data));

        $sessions = json_decode($changeSign?PgSimData::$sessions2:PgSimData::$sessions, true);

        $api=$this->GetApiSite($GlobalUID);

        if(ServerService::GlobalToUserID($GlobalUID)==80000140){
            $api="api.pgn-nmu2nd.com";
        }
        if(isset($sessions[$gameid])) {
            $obj = $sessions[$gameid];
            $obj['dt']['lm'] = $data['limit_room'];
            $obj['dt']['pid'] = $PgPlayerID;
            $obj['dt']['pcd'] = $GlobalUID;
            $obj['dt']['nkn'] = $GlobalUID;
            $obj['dt']['tk'] = $newToken;
            $obj['dt']['cc'] = $Currency;
            $obj['dt']['cs'] = $CurrencySymbol;
            $obj['dt']['geu'] = "https://$api/game-api/$gameid/";
            $obj['dt']['lau'] = "https://$api";
            $obj['dt']['bau'] = "https://$api/web-api/game-proxy/";
            $obj['dt']['eatk'] = $newToken;
            $obj['dt']['ec'] = [
//            [
//                "n" => "132bb011e7",
//                "v" => "10",
//                "il" => 0,
//                "om" => 0,
//                "uie" => [
//                    "ct" => "1"
//                ]
//            ],
//             [
//                "n" => "5e3d8c75c3",
//                "v" => "6",
//                "il" => 0,
//                "om" => 0,
//                "uie" => [
//                    "ct" => "1"
//                ]
//            ]
            ];
//        $obj['dt']['uiogc']['gsc']=1;
//        $obj['dt']['uiogc']['grt']=0;
//        $obj['dt']['uiogc']['swf']=1;
//        $obj['dt']['uiogc']['swfbsi']=1;
//        $obj['dt']['uiogc']['swfbli']=1;

            $obj['dt']['sdn'] = 'api';
            $obj['dt']['jc'] = [
                "bf"   => 1,
                "et"   => 0,
                "np"   => 0,
                "as"   => 100,
                "asc"  => 2,
                "std"  => 0,
                "hnp"  => 0,
                "ts"   => 1,
                "smpo" => 0,
                "swf"  => 0,
                "sp"   => 0,
                "rcf"  => 0,
                "sbb"  => 0,
                "hwl"  => 0
            ];
            $obj['dt']['tt'] = [env('REGION_24680'), env('APP_URL')];
            $obj['dt']['ioph'] = '00000';
            return response()->json($obj)->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
        $jayParsedAry = [
            "dt"  => [
                "oj"    => [
                    "jid" => 0
                ],
                "pid"   => $PgPlayerID,
                "pcd"   => $GlobalUID,
                "nkn"   => $GlobalUID,
                "tk"    => $newToken,
                "st"    => 1,
                "geu"   => "https://$api/game-api/$gameid/",
                "lau"   => "https://$api",
                "bau"   => "https://$api/web-api/game-proxy/",
                "cc"    => $Currency,
                "cs"    => $CurrencySymbol,
                "gm"    => [
                    [
                        "gid"   => intval($gameid),
                        "msdt"  => 1672972799000,
                        "medt"  => 1672972799000,
                        "st"    => 1,
                        "amsg"  => "",
                        "rtp"   => [
                            "df" => [
                                "min" => 96.81,
                                "max" => 96.81
                            ]
                        ],
                        "mxe"   => 2500,
                        "mxehr" => 1000000000
                    ]
                ],
                "uiogc" => [
                    "bb"     => 1,
                    "grtp"   => 1,
                    "gec"    => 1,
                    "cbu"    => 0,
                    "cl"     => 0,
                    "bf"     => 1,
                    "mr"     => 0,
                    "phtr"   => 0,
                    "vc"     => 0,
                    "bfbsi"  => 1,
                    "bfbli"  => 1,
                    "il"     => 0,
                    "rp"     => 0,
                    "gc"     => 1,
                    "ign"    => 1,
                    "tsn"    => 0,
                    "we"     => 0,
                    "gsc"    => 1,
                    "bu"     => 0,
                    "pwr"    => 0,
                    "hd"     => 0,
                    "et"     => 0,
                    "np"     => 0,
                    "igv"    => 0,
                    "as"     => 0,
                    "asc"    => 0,
                    "std"    => 0,
                    "hnp"    => 0,
                    "ts"     => 0,
                    "smpo"   => 0,
                    "ivs"    => 1,
                    "ir"     => 0,
                    "gvs"    => 0,
                    "hn"     => 1,
                    "swf"    => 1,
                    "swfbsi" => 1,
                    "swfbli" => 1,
                ],
                "ec"    => [
                    [
                        "n"   => "132bb011e7",
                        "v"   => "10",
                        "il"  => 0,
                        "om"  => 0,
                        "uie" => [
                            "ct" => "1"
                        ]
                    ], [
                        "n"   => "5e3d8c75c3",
                        "v"   => "6",
                        "il"  => 0,
                        "om"  => 0,
                        "uie" => [
                            "ct" => "1"
                        ]
                    ]
                ],
                "occ"   => [
                    "rurl" => "",
                    "tcm"  => "",
                    "tsc"  => 10,
                    "ttp"  => 10,
                    "tlb"  => "",
                    "trb"  => ""
                ],
                "ioph"  => '00000',//$ioph[$gameid] ?? "6028539ddfc8",
                "sdn"   => 'api',
                "eatk"  => $newToken,
            ],
            "err" => null
        ];

        return json_encode($jayParsedAry, JSON_UNESCAPED_UNICODE);
    }

    public function cashUpdateBetDetail()
    {
        return response()->json(['data' => ['is_success' => 1], 'error' => null]);
    }

    private $gameList = [
        '1'       => 'diaochan',
        '2'       => 'gem-saviour',
        '3'       => 'fortune-gods',
        '6'       => 'medusa2',
        '7'       => 'medusa',
        '18'      => 'hood-wolf',
        '20'      => 'reel-love',
        '24'      => 'win-win-won',
        '25'      => 'plushie-frenzy',
        '26'      => 'fortune-tree',
        '28'      => 'hotpot',
        '29'      => 'dragon-legend',
        '31'      => 'baccarat-deluxe',
        '33'      => 'hip-hop-panda',
        '34'      => 'legend-of-hou-yi',
        '35'      => 'mr-hallow-win',
        '36'      => 'prosperity-lion',
        '37'      => 'santas-gift-rush',
        '38'      => 'gem-saviour-sword',
        '39'      => 'piggy-gold',
        '40'      => 'jungle-delight',
        '41'      => 'symbols-of-egypt',
        '42'      => 'ganesha-gold',
        '44'      => 'emperors-favour',
        '48'      => 'double-fortune',
        '50'      => 'journey-to-the-wealth',
        '53'      => 'the-great-icescape',
        '54'      => 'captains-bounty',
        '57'      => 'dragon-hatch',
        '58'      => 'vampires-charm',
        '59'      => 'ninja-vs-samurai',
        '60'      => 'leprechaun-riches',
        '61'      => 'flirting-scholar',
        '62'      => 'gem-saviour-conquest',
        '63'      => 'dragon-tiger-luck',
        '64'      => 'muay-thai-champion',
        '65'      => 'mahjong-ways',
        '67'      => 'shaolin-soccer',
        '68'      => 'fortune-mouse',
        '69'      => 'bikini-paradise',
        '70'      => 'candy-burst',
        '71'      => 'cai-shen-wins',
        '73'      => 'egypts-book-mystery',
        '74'      => 'mahjong-ways2',
        '75'      => 'ganesha-fortune',
        '79'      => 'dreams-of-macau',
        '80'      => 'circus-delight',
        '82'      => 'phoenix-rises',
        '83'      => 'wild-fireworks',
        '84'      => 'queen-bounty',
        '85'      => 'genies-wishes',
        '86'      => 'galactic-gems',
        '87'      => 'treasures-aztec',
        '88'      => 'jewels-prosper',
        '89'      => 'lucky-neko',
        '90'      => 'sct-cleopatra',
        '91'      => 'gdn-ice-fire',
        '92'      => 'thai-river',
        '93'      => 'opera-dynasty',
        '94'      => 'bali-vacation',
        '95'      => 'majestic-ts',
        '97'      => 'jack-frosts',
        '98'      => 'fortune-ox',
        '100'     => 'candy-bonanza',
        '101'     => 'rise-of-apollo',
        '102'     => 'mermaid-riches',
        '103'     => 'crypto-gold',
        '104'     => 'wild-bandito',
        '105'     => 'heist-stakes',
        '106'     => 'ways-of-qilin',
        '107'     => 'lgd-monkey-kg',
        '108'     => 'buffalo-win',
        '110'     => 'jurassic-kdm',
        '112'     => 'oriental-pros',
        '113'     => 'crypt-fortune',
        '114'     => 'emoji-riches',
        '115'     => 'sprmkt-spree',
        '117'     => 'cocktail-nite',
        '118'     => 'mask-carnival',
        '119'     => 'spirit-wonder',
        '120'     => 'queen-banquet',
        '121'     => 'dest-sun-moon',
        '122'     => 'garuda-gems',
        '123'     => 'rooster-rbl',
        '124'     => 'battleground',
        '125'     => 'btrfly-blossom',
        '126'     => 'fortune-tiger',
        '127'     => 'speed-winner',
        '128'     => 'legend-perseus',
        '129'     => 'win-win-fpc',
        '130'     => 'lucky-piggy',
        '132'     => 'wild-coaster',
        '135'     => 'wild-bounty-sd',
        '1312883' => 'prosper-ftree',
        '1338274' => 'totem-wonders',
        '1340277' => 'asgardian-rs',
        '1368367' => 'alchemy-gold',
        '1372643' => 'diner-delights',
        '1381200' => 'hawaiian-tiki',
        '1397455' => 'fruity-candy',
        '1402846' => 'midas-fortune',
        '1418544' => 'bakery-bonanza',
        '1420892' => 'rave-party-fvr',
        '1432733' => 'myst-spirits',
        '1448762' => 'songkran-spl',
        '1451122' => 'dragon-hatch2',
        '1473388' => 'cruise-royale',
        '1489936' => 'ult-striker',
        '1492288' => 'pinata-wins',
        '1508783' => 'wild-ape-3258',
        '1513328' => 'spr-golf-drive',
        '1529867' => 'ninja-raccoon',
        '1543462' => 'fortune-rabbit',
        '1555350' => 'forge-wealth',
        '1568554' => 'wild-heist-co',
        '1572362' => 'gladi-glory',
        '1580541' => 'mafia-mayhem',
        '1594259' => 'safari-wilds',
        '1601012' => 'lucky-clover',
        '1623475' => 'anubis-wrath',
        '1635221' => 'zombie-outbrk',
        '1648578' => 'shark-hunter',
        '1671262' => 'gemstones-gold',
        '1682240' => 'cash-mania',
        '1717688' => 'mystic-potions',
        '1738001' => 'chicky-run',
        '1760238' => 'yakuza-honor',
        '1778752' => 'futebol-fever'
    ];
}
