<?php

namespace App\Http\Controllers\Game;

use App\Game\Config\IgtData;
use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\LogGamecardClick;
use App\Game\Services\ServerService;
use App\Game\Services\IgtUserAgentParser;
use App\Models\AccountsInfo;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class IgtSimController extends Controller
{
    public function __construct()
    {
    }

    public $gameConfig = [];

    public function gameLunch(Request $request)
    {
        $softwareId = $request->input('softwareid', '200-1551-001');


        return $this->renderGateway($request, $softwareId);
    }

    public function gameLunchOrg(Request $request)
    {
        $softwareId = $request->input('softwareid', '200-1551-001');

        return $this->renderGateway($request, $softwareId);
    }

    public function leaveOrg(Request $request)
    {
        $UserID = $request->UserID;
        try {
            DB::connection('write')->table('QPTreasureDB.dbo.GameScoreLocker')
                ->where('UserID', $UserID)
                ->delete();
        } catch (\Throwable $e) {
        }
        return '<script>
            if(window.parent&&window.parent!=window){
                window.parent.postMessage("backhome","*")
            }else {
                document.location = "game://a=1&b=2";
            }
        </script>';
    }

    private function renderGateway(Request $request, string $softwareId)
    {
        if (!strstr($softwareId, '-')) {
            $softwareId = substr($softwareId, 0, 3) . '-' . substr($softwareId, 3, 4) . '-' . substr($softwareId, 7, 3);
        }
        $gid = $request->input('gid');
        $level = $request->input('level', 0);
        $user = $request->user();

        if (!$user) {

            $userid = $request->UserID;

            if (!$userid) {
                $token = $request->deviceInfoString;
                $session = json_decode(Redis::get($token), true);
                $userid = $session['UserID'];
                if ($session['GlobalUID']) {
                    $GlobalUID = $session['GlobalUID'];
                }
            } else {
                $GlobalUID = 'a1b1c1-b53b-' . ServerService::GetLocalSign() . '-' . $userid;
            }

            $user = GlobalUserInfo::getGameUserInfo('UserID', $userid);
            if (!$user) {
                $user = AccountsInfo::find($userid);
            }

        } else {
            $GlobalUID = $user->GlobalUID;
            $userid = $user->UserID;

        }
        $lang = GlobalUserInfo::getLocaleByUserID($userid, $request->input('language', env('DEFAULT_LOCALE', 'en')));


        $gamecard = GameCard::where('gid', $gid)->where('brand', 'IGT')->first();
        if ($gamecard) {
            $gamecard->increment('play_num', 1);
            LogGamecardClick::recordClick($gamecard->id, $userid);

            GameCard::$enableStateCheck = false;
        }


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


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


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


        if (!is_array($user)) $user = $user->toArray();

        $data = array_merge($data, $user);

        $session = $data;


        $token = md5($GlobalUID . '|' . microtime());
        Redis::setex($token, 7200, json_encode($session));


        $global = IgtData::$global;

        /// 'mainSiteUrl'       => 'https://testigt.usgamewin.com/',
        //        'rgsServer'         => 'https://testigt.usgamewin.com/skb',
        //        'rgsCecServer'      => 'https://testigt.usgamewin.com/cec',
        //        'flightdeckUrl'     => 'https://testigt.usgamewin.com/flightdeck/gs/flightdeck',
        //        'consoleBaseUrl'    => 'https://sigt.usgamewin.com/skins/DV13',
        //        'cdnBaseUrl'        => 'https://sigt.usgamewin.com',
        //        //jackpot
        //        'jackpotUrl'        => 'https://testigt.usgamewin.com',

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

        $apiurl=$configurl['api'];
        $cdnurl=$configurl['source'];

        foreach ($global as $key => $value) {

            if(is_string($value))if(strstr($value,'{api}')){
                $global[$key]=str_replace('{api}',$apiurl,$value);
            }else if(strstr($value,'{cdn}')){
                $global[$key]=str_replace('{cdn}',$cdnurl,$value);
            }
        }



        $games = json_decode(file_get_contents(base_path('app/Game/Config/IGTgamesConfig.json')), true);


        if (!isset($games[$softwareId])) {
            http_response_code(500);
        }
        $game = $games[$softwareId];
        $this->gameConfig = $game;
        $lang = in_array($lang, $global['languages']) ? $lang : 'en';

        $ua = $request->header('User-Agent', '');
        $uaParser = new IgtUserAgentParser($ua);
        $deviceConfig = $uaParser->getDeviceConfig();
        $isMobile = $this->isMobileUA($ua);
        $assetPack = $isMobile ? 'mobile' : 'desktop';

        $cdnBase = rtrim($global['cdnBaseUrl'], '/');
        $skbGatewayPath = $global['skbGatewayPath'];
        $gamePath = $game['gamePath'];
        $requireVersion = $global['requireVersion'];

        $denomamount = $game['denomamount'] ?? IgtData::$global['denomamount'];
        $paramGet = [
            'skincode'             => $request->input('skincode', 'MKW'),
            'ipaddress'            => $request->ip(),
            'forcelat'             => $request->input('forcelat', ''),
            'minbet'               => $request->input('minbet', $game['minbet']),
            'deviceInfoString'     => $request->input('deviceInfoString', $token),
            'forcelocationstatus'  => $request->input('forcelocationstatus', '0'),
            'countrycode'          => $request->input('countrycode', 'US'),
            'channel'              => $request->input('channel', $isMobile ? 'MOB' : 'INT'),
            'nscode'               => $request->input('nscode', 'AGLC'),
            'language'             => $lang,
            'technology'           => $request->input('technology', 'HTML'),
            'loadskin'             => $request->input('loadskin', 'IGT'),
            'forcelng'             => $request->input('forcelng', ''),
            'currencycode'         => $request->input('currencycode', 'FPY'),
            'securetoken'          => $request->input('securetoken', 'RGS-DEMO04.SKB'),
            'softwareid'           => $softwareId,
            'forcelocationmessage' => $request->input('forcelocationmessage', '-SUCCESS'),
            'presenttype'          => $request->input('presenttype', 'STD'),
            'denomamount'          => $denomamount,//$request->input('denomamount', '1.0'),
            'uniqueid'             => $request->input('uniqueid', '986'),
        ];

        $paramRGS = [
            'skincode'     => $paramGet['skincode'],
            'minbet'       => $game['minbet'],
            'countrycode'  => $paramGet['countrycode'],
            'channel'      => $paramGet['channel'],
            'language'     => $paramGet['language'],
            'nscode'       => $paramGet['nscode'],
            'technology'   => $paramGet['technology'],
            'currencycode' => $paramGet['currencycode'],
            'securetoken'  => $paramGet['securetoken'],
            'playMode'     => $request->input('playMode', 'real'),
            'softwareid'   => $paramGet['softwareid'],
            'denomamount'  => $paramGet['denomamount'],
            'presenttype'  => $paramGet['presenttype'],
            'uniqueid'     => $paramGet['uniqueid'],
        ];

        // 注入语言文案
        $langMap = json_decode(file_get_contents(base_path('app/Game/Config/IGTlanguages.json')), true);

        $strings = is_array($langMap) && isset($langMap[$lang]) && is_array($langMap[$lang]) ? $langMap[$lang] : [];

        $jackpotUrl = IgtData::$global['jackpotUrl'];
        $jackpotMeterUrl = null;
        if (isset(IgtData::$global['jackpotMeterPath'])) {
            $jackpotMeterUrl = $jackpotUrl . IgtData::$global['jackpotMeterPath'];
        }
        $jackpotWinsUrl = null;
        if (isset(IgtData::$global['jackpotWinsPath'])) {
            $jackpotWinsUrl = $jackpotUrl . IgtData::$global['jackpotWinsPath'];
        }


        $config = [
            'serverConfig'       => [
                'paramGet'             => $paramGet,
                'paramRGS'             => $paramRGS,
                'softwareid'           => $softwareId,
                'nscode'               => 'SKB',
                'skincode'             => $paramGet['skincode'],
                'server'               => $global['rgsServer'],
                'showInitialCashier'   => 'false',
                'autopull'             => 'N',
                'securetoken'          => $paramGet['securetoken'],
                'uniqueid'             => $paramGet['uniqueid'],
                'channel'              => $paramGet['channel'],
                'presenttype'          => $paramGet['presenttype'],
                'buildnumber'          => $global['buildnumber'],
                'gameUrl'              => $cdnBase . $gamePath . '/launcher.html',
                'requestTimeout'       => $global['requestTimeout'],
                'requestRetries'       => $global['requestRetries'],
                'ipaddress'            => $paramGet['ipaddress'],
                'playMode'             => $request->input('playMode', 'real'),
                'denomamount'          => $paramGet['denomamount'],//$game['minbet'],
                'countrycode'          => $paramGet['countrycode'],
                'revisionTag'          => $game['revisionTag'],
                'paramGame'            => [
                    'skincode'     => $paramGet['skincode'],
                    'softwareid'   => $softwareId,
                    'countrycode'  => $paramGet['countrycode'],
                    'assetPack'    => $assetPack,
                    'language'     => $lang,
                    'currencycode' => $paramGet['currencycode'],
                    'playMode'     => $request->input('playMode', 'real'),
                    'revisionTag'  => $game['revisionTag'],
                ],
                'autospin'             => [
                    'winLimit'  => [1, 2, 5, 10, 100],
                    'lossLimit' => [1, 2, 5, 10, 100],
                    'steps'     => [10, 20, 30, 50, 100],
                    'version'   => 2,
                ],
                'cecServerUrl'         => $global['rgsCecServer'],
                'gameVersion'          => $game['gameVersion'],
                'sessionToken'         => 'IGTGSRID=' . $token,
                'dateFormatter'        => [
                    'country'            => $paramGet['countrycode'],
                    'dateFormatterShort' => 'dd/MM/yyyy',
                    'dateFormatterLong'  => 'dd/MM/yyyy HH:mm:ss',
                ],
                'fusionIntegrationInd' => false,
                'pendingGps'           => false,
                'checkPass'            => false,

                'jackpotMeterUrl' => $jackpotMeterUrl,
                'jackpotWinsUrl'  => $jackpotWinsUrl,

                'baseHostUrl'                 => $cdnBase,
                'needShareButton'             => false,
                'nicknameAutoGen'             => true,
                'authorizationId'             => 0,
                'widgetsEnabled'              => true,
                'supportGSPType'              => 'widget',
                'showTournmentWelComeMessage' => false,
                'blockInsufficientFund'       => false,
                'enableCustomGSP'             => false,
                'gameInfoInterval'            => '',
            ],
            'deviceConfig'       => $deviceConfig,
            'kernelConfig'       => [
                'splashUrl'       => $cdnBase . $gamePath . '/splash.html',
                'serverType'      => 'RGS',
                'platformVersion' => $global['platformVersion'],
                'loglevel'        => 'WARN',
                'paramSplash'     => [
                    'skincode'     => $paramGet['skincode'],
                    'softwareid'   => $softwareId,
                    'countrycode'  => $paramGet['countrycode'],
                    'assetPack'    => $assetPack,
                    'language'     => $lang,
                    'currencycode' => $paramGet['currencycode'],
                    'playMode'     => $request->input('playMode', 'real'),
                    'revisionTag'  => $game['revisionTag'],
                ],
                'intVerify'       => false,
                'sentryEnabled'   => false,
                'showSoundPrompt' => true,
                'reportLevels'    => new \stdClass(),
            ],
            'consoleConfig'      => [
                'paramConsole' => [
                    'skincode'     => $paramGet['skincode'],
                    'softwareid'   => $softwareId,
                    'nscode'       => $paramGet['nscode'],
                    'language'     => $lang,
                    'currencycode' => $paramGet['currencycode'],
                    'cashiertype'  => 'N',
                    'securetoken'  => $paramGet['securetoken'],
                    'uniqueid'     => $paramGet['uniqueid'],
                ],
                'lobbyUrl'     => $global['mainSiteUrl'],
                'cashiertype'  => 'N',
                'TCustomView'  => [
                    'consoleUrl' => $global['consoleBaseUrl'] . $game['tCustomPath'],
                    'resizable'  => 'Y',
                    'width'      => '100',
                    'timeout'    => '15000',
                    'height'     => '31',
                ],
                'BCustomView'  => [
//                    'consoleUrl' => $global['consoleBaseUrl'] . $game['bCustomPath'],
//                    'resizable' => 'N',
//                    'width' => '100%',
//                    'timeout' => '15000',
//                    'height' => '0%',
                ],
            ],
            'stringsConfig'      => $strings,
            'forceGetParamNames' => [],
            'gameConfig'         => [
                'studio'            => $game['studio'],
                'gameType'          => $game['gameType'],
                'game'              => $game['game'],
                'gameWindowWidth'   => $game['gameWindowWidth'],
                'spaceBarSpin'      => $game['spaceBarSpin'],
                'minbet'            => $game['minbet'],
                'gameWindowHeight'  => $game['gameWindowHeight'],
                'softDisplay'       => $game['softDisplay'],
                'gameTitle'         => $game['gameTitle'],
                'assetPack'         => $assetPack,
                'language'          => $lang,
                'currencycode'      => $paramGet['currencycode'],
                'denomid'           => $game['denomid'],
                'turboMode'         => $game['turboMode'],
                'speedOption'       => $game['speedOption'],
                'slamStop'          => $game['slamStop'],
                'softwareId'        => $softwareId,
                'dealerVoice'       => $game['dealerVoice'],
                'gleVersion'        => $game['gleVersion'],
                'skbGateWayVersion' => $global['skbGateWayVersion'],
                'autospin'          => [
                    'winLimit'  => [1, 2, 5, 10, 100],
                    'lossLimit' => [1, 2, 5, 10, 100],
                    'steps'     => [10, 20, 30, 50, 100],
                    'version'   => 2,
                ],
                'rgPresentation'    => $game['rgPresentation'],
            ],
            'gameServiceConfig'  => [
                'flightdeck' => [
                    'url' => $global['flightdeckUrl'],
                ],
            ],
            'widgetConfig'       => [
                'dcid'         => 'SF',
                'connectorUrl' => $global['widgetUrl'],
            ],
        ];

        $configJson = htmlspecialchars(json_encode($config, JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8');
        $iconUrl = $cdnBase . $gamePath . '/icons/icon.png';

        $html = '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EDGE">
<meta charset="UTF-8">
<link rel="apple-touch-icon" href="' . $iconUrl . '">
<meta name="apple-mobile-web-app-capable" content="yes">
<script>
(function () {
  var scale = 1;
  if (navigator.userAgent.match(/\s+[789]_[\d_]+\s+like Mac OS X/) && navigator.userAgent.indexOf("7_0") == -1 && /(iPod|iPhone)/.test(navigator.userAgent)) {
    document.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=" + scale + ", minimum-scale=" + scale + ", maximum-scale=" + scale + ", user-scalable=no, minimal-ui\" />");
  } else {
    document.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=" + scale + ", minimum-scale=" + scale + ", maximum-scale=" + scale + ", user-scalable=no, viewport-fit=cover\" />");
  }
})();
window.addEventListener("message", function(e){ if(!e.data||!e.data.message) return; var m=document.getElementById("messageBoxDiv"); if(m){ m.style.visibility="visible"; document.getElementById("message").innerHTML=e.data.message; } var c=document.getElementById("container"); if(c&&c.parentNode){ c.parentNode.removeChild(c); } }, true);
</script>
<meta name="com.igt.skateboard.CLIENTCONFIG" content="' . $configJson . '"/>
<title>' . htmlspecialchars($game['gameTitle']) . '</title>
<script type="text/javascript">var require={"waitSeconds":0,"urlArgs":"v=' . $requireVersion . '"};</script>
<link rel="stylesheet" type="text/css" href="' . $cdnBase . $skbGatewayPath . '/css/style.mob.css?v=' . $requireVersion . '">
</head>
<body>
<img id="loader" class="loader" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==">
<div id="messageBoxDiv" class="messageBoxDiv" style="visibility:hidden"><div id="message" class="message"></div></div>
<script data-main="' . $cdnBase . $skbGatewayPath . '/js/kernel.js" src="' . $cdnBase . $skbGatewayPath . '/js/require.js?v=2.1.20"></script>
<script>

parent.postMessage({cmd:"closeLoading"},"*");
window.document.addEventListener("click", (event) => {
    window.parent.postMessage({cmd:"clickGame"},"*");
});
</script>
</body>
</html>';

        Util::WriteLog('igtsim', ['softwareid' => $softwareId, 'lang' => $lang]);
        return response($html);
    }

    private function isMobileUA(string $ua): bool
    {
        $ua = strtolower($ua);
        $mobiles = ['iphone', 'ipad', 'ipod', 'android', 'mobile'];
        foreach ($mobiles as $m) {
            if (strpos($ua, $m) !== false) return true;
        }
        return false;
    }
}


