<?php

namespace App\Http\Controllers\Game;

use App\Facade\TableName;
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\Http\helper\ApiSign;
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 JiliSimController extends Controller
{

    public function __construct()
    {

    }


    public function launch9x(Request $request)
    {

        $gid = $request->input('gid');
        $level=$request->input('level',0);
        $lang=$request->input('lang',env('DEFAULT_LOCALE','pu'));
        $userid = $request->UserID;
        $lang=['pu'=>'pt','en'=>'en','sp'=>'es'][$lang]??$lang;

        $protocol = $request->isSecure() ? 'https://' : 'http://';
        $domain = $protocol . $request->getHost();

        $rid=substr($gid,2);
        $params=[
            'norot'=>1,
            'lang'=>$lang,
            'level'=>$level,
            'gid'=>$rid,
            'UserID'=>$userid,
            't'=>time()
        ];
        $params['sign'] = ApiSign::sign($params);

        $url="$domain/api/pgsoft/lunchorg?".http_build_query($params);
        switch(substr($gid,0,2)){
            //jili
            case "91":
                $url = "$domain/api/jiligames/lunchorg?".http_build_query($params);
                break;
            //pg
            case "90":
                break;
        }

        return redirect($url);
    }
    public function gameLunch(Request $request)
    {

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

        $GlobalUID = $user->GlobalUID;

        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', 'JILI')->first();
        $gamecard->increment('play_num', 1);
        //$this->logGameClick($gamecard->id,$userid);

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

        $lang = GlobalUserInfo::getLocale();



        GameCard::$enableStateCheck = false;

        $supportLang = ['en' => "en-US", 'da' => "da-DK", 'es' => "es-AR", 'id' => "id-ID", 'ja' => "ja-JP", 'ko' => "ko-KR", 'pt' => "pt-BR", 'th' => "th-TH", 'vi' => "vi-VN", 'zh' => "zh-CN", 'my' => "my-MM"];

        if (!in_array($lang, array_keys($supportLang))) {
            $lang = 'en';
        }
        $lang=$supportLang[$lang];

        $cdnserver = 'https://sjj.pgn-nmu2nd.com';
        $LogonPass='123';
        $sign = GlobalUserInfo::genGuuidSign((object)compact('GlobalUID','LogonPass'));
        $or = $this->convertString(env('JILI_GAME_DOMAIN','jj.pgn-nmu2nd.com'));

        $data=['UserID'=>ServerService::GlobalToUserID($GlobalUID)];


//        $gameIdToCodes=[302=>'mcp',51=>'mc',49=>'fullhouse',403=>'fullhouse3',300=>'fg3',223=>'fgp',109=>'fg',35=>'ols2',258=>'dl',47=>'bfs',421=>'lj'];

        $params = ['lang' => $lang, 'ssoKey' => $sign,  'apiId' => 2,'gameId'=>$gid,'gs'=>$or,'domain_platform'=>$or,'domain_gs'=>$or,'be'=>$or];
        $url = $cdnserver . "/{$gid}/index.html?" . http_build_query($params).'&iu=true&legalLang=true';
//        https://jj.pgn-nmu2nd.com/mcp/index.html?ssoKey=1e790573d14d23bf6c3c330e3edeef8a1d8b3cae&lang=en-US&legalLang=true&gameId=302&gs=moc.dn2umn-ngp.jj&domain_platform=moc.dn2umn-ngp.jj&domain_gs=semagilij&be=moc.dn2umn-ngp.jj&iu=true&apiId=2&demo=true




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

    }

    public function leaveOrg(Request $request){

        $UserID = $request->UserID;
        $config = ServerService::GetGlobalServerInfoByCode(ServerService::GetLocalSign());

        $api = [
                   'Bangladesh'=> "bdapi.pgn-nmu2nd.com",
                   'Pakistan'  => "pkapi.pgn-nmu2nd.com",
                   'OrgBrazil' => "orgbr.pgn-nmu2nd.com",
                   'Brazil'    => "brapi.pgn-nmu2nd.com",
                   'Europe'    => "euapi.pgn-nmu2nd.com",
                   'Russia'    => "ruapi.pgn-nmu2nd.com",
                   'Mexico'    => "mxapi.pgn-nmu2nd.com",
                   'Singapore' => "sgapi.pgn-nmu2nd.com",
                   'Latin'     => "saapi.pgn-nmu2nd.com",
               ][$config['Subsite']];

        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)
    {

        $gid = $request->input('gid');
        $level=$request->input('level',0);
        $lang=$request->input('lang',env('DEFAULT_LOCALE','pu'));

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

        $userid = $request->UserID;
        $GlobalUID = 'a1b1c1-b53b-'.ServerService::GetLocalSign().'-' . $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' => "en-US", 'da' => "da-DK", 'es' => "es-AR", 'id' => "id-ID", 'ja' => "ja-JP", 'ko' => "ko-KR", 'pt' => "pt-BR", 'th' => "th-TH", 'vi' => "vi-VN", 'zh' => "zh-CN", 'my' => "my-MM"];

        if (!in_array($lang, array_keys($supportLang))) {
            $lang = 'en';
        }
        $lang=$supportLang[$lang];

        $cdnserver = 'https://sjj.pgn-nmu2nd.com';
        $LogonPass='123';
        $sign = GlobalUserInfo::genGuuidSign((object)compact('GlobalUID','LogonPass'));
        $or = $this->convertString(env('JILI_GAME_DOMAIN','jj.pgn-nmu2nd.com'));
//        $api = $this->convertString('orgbr.pgn-nmu2nd.com');
//        $api = $this->convertString('api.pgn-nmu2nd.com');

        $data=['UserID'=>ServerService::GlobalToUserID($GlobalUID)];


        $gameIdToCodes=[302=>'mcp',51=>'mc',49=>'fullhouse',403=>'fullhouse3',300=>'fg3',223=>'fgp',109=>'fg',35=>'ols2',258=>'dl',47=>'bfs',421=>'lj'];

        $params = ['lang' => $lang, 'ssoKey' => $sign,  'apiId' => 2,'gameId'=>$gid,'gs'=>$or,'domain_platform'=>$or,'domain_gs'=>$or,'be'=>$or];
        $url = $cdnserver . "/{$gameIdToCodes[$gid]}/index.html?" . http_build_query($params).'&iu=true&legalLang=true';
//        https://jj.pgn-nmu2nd.com/mcp/index.html?ssoKey=1e790573d14d23bf6c3c330e3edeef8a1d8b3cae&lang=en-US&legalLang=true&gameId=302&gs=moc.dn2umn-ngp.jj&domain_platform=moc.dn2umn-ngp.jj&domain_gs=semagilij&be=moc.dn2umn-ngp.jj&iu=true&apiId=2&demo=true


        $trans="no-rotated-iframe-container";
        $posClass = "defaultPos";
        $iconClass="widthIcon";
        if(in_array($gid,[49,403])){
            $iconClass="heightIcon";

            if (strpos(strtolower($request->header('User-Agent')), 'iphone') !== false) {
                $posClass = "iosPos";
                $iconClass="widthIcon";
                $trans="rotated-iframe-container";
            }
        }


        $leaveUrl=$request->getSchemeAndHttpHost().'/api/jiligames/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>JiliGames</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;
        }
        .widthIcon{
            width: 13vh; height: 13%;
        }
        .heightIcon{
            width: 13%; height: 13vw;
        }
        .defaultPos{
           position: absolute; top: 10px; left: 10px;  z-index: 9999;
        }
        .iosPos{
           position: absolute; bottom: 10px; left: 10px;  z-index: 9999; transform: rotate(-90deg);
        }
    </style>
</head>
<body>
    <script>
    document.addEventListener("touchstart", (e) => {
    // 确保滑动事件生效
    }, { passive: true });

    document.addEventListener("touchmove", (e) => {
        // 确保惯性滚动生效
    }, { passive: true });

    function backhome(){
        var xhr = new XMLHttpRequest();
        var url = "'.$leaveUrl.'"; // 这里替换成你实际要访问的 URL
        window.location.href=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:#000">${url}</span>`;
    }
</script>
<div class="'.$trans.'">
    <!-- 嵌入的 iframe -->
    <iframe class="rotated-iframe" frameborder="0" src="'.$url.'"></iframe>
</div>
<div  id="game-lobby" style="" class="'.$iconClass.' '.$posClass.'">
 <a href="#" onclick="backhome()" > <img src="https://static2.pgn-nmu2nd.com/0temp/back.png"  style="display: block; width: 100%; height: 100%; margin-left: auto; margin-right: auto;"></a>
 </div>
</body>
</html>';

        return "";
    }

    public function loginSession(Request $request)
    {
        $key=$request->input('key');
        $lang=$request->input('lang');
        if(Redis::exists($key)){
            $session=json_decode(Redis::get($key),true);
        }else {
            try {
                $arr = explode('|', Crypt::decryptString($key));
                $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) {
                $this->log($request, "wrong user");
            }
            if (!isset($GlobalUID) || empty($GlobalUID)) {
                return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];
            }


            $data = ['UserID' => ServerService::GlobalToUserID($GlobalUID)];


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



            $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)$account=$account->toArray();
            else{
                TelegramBot::getDefault()->sendProgramNotify("jili","get account error",compact('GlobalUID','data'));
                return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];
            }
            $data = array_merge($data, $account);

            $session = $data;


//            $add=Redis::get($newToken);

        }
        if(!isset($session)||empty($session)) return ['dt' => null, 'err' => ['cd' => 1302, 'msg' => 'Invalid player session', 'tid' => $request->traceId]];
        $newToken = md5($key);
        Redis::setex($newToken, 7200, json_encode($session));
        return response()->json([
            'homeUrl'           => '',
            'linecode'          => 0,
            'profile'           => [
                'id'               => '',
                'aid'              => $session['UserID'],
                'apiId'            => 2,
                'transactionMode'  => 0,
                'subAgentCode'     => 0,
                'isLobbyOpen'      => true,
                'meta'             => ['agentAccount' => '<nil>'],
                'platform'         => '<nil>',
                'lobbyMode'        => 0,
                'switchOffs'       => [
                    2, 3, 4, 5, 25,
                    26, 27, 35, 41, 44,
                    49
                ],
                'wallets'          => null,
                'nickname'         => $session['NickName'],
                'newNickname'      => '',
                'siteId'           => 0,
                'account'          => $session['Accounts'],
                'coin'             => 0,
                'isJPEnabled'      => 0,
                'linecode'         => 0,
                'prefix'           => '',
                'clientMode'       => [
                    ['eventId' => 1, 'value' => [50]],
                    ['eventId' => 3, 'value' => [10, 20, 30, 40, 50]],
                    ['eventId' => 7, 'value' => ['400']],
                    ['eventId' => 8, 'value' => [120]]
                ],
                'betLevel'         => -1,
                'license'          => 0,
                'isGiftCodeOpen'   => false,
                'freeSpinBetValue' => 0,
                'apiType'          => 0,
                'walletType'       => 1
            ],
            'token'             => $newToken,
            'response'          => ['error' => 0, 'message' => '', 'time' => time()],
            'platformVersion'   => 'uat.2.0.96',
            'lobbyMode'         => 0,
            'disableFullScreen' => 0,
            'country'           => env('VALID_COUNTRY'),
            'certId'            => 0,
            'certArea'          => 0,
            'clientApiParam'    => [],
            'itaAuthId'         => '',
            'thousandthMode'    => '',
//            'add'=>$add
        ]);
    }

    private function convertString($input)
    {
        return strrev($input);

    }


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

}
