<?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\Models\AccountsInfo;
use App\Notification\TelegramBot;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Redis;

class HacksawController extends Controller
{
    /** gid => version（与 CDN 静态资源目录一致） */
    private static $gameVersions = [
        '1632' => '1.34.2',   // Speed Crash
        '1624' => '1.43.2',   // Limbo
        '1590' => '1.30.0',   // Dice
        '1446' => '1.59.1',   // Baccarat
        '1416' => '1.30.1',   // Twenty-One
        '1386' => '1.36.2',   // Colors
        '1380' => '1.34.1',   // Blocks
        '1321' => '1.41.0',   // Wheel
        '1334' => '1.41.1',   // Lines
        '1148' => '1.27.3',   // Coins
        '1294' => '1.88.1',   // Plinko
        '1328' => '1.43.0',   // Hi-Lo
        '1126' => '1.135.0',  // Mines
        '1154' => '1.68.1',   // Boxes
    ];

    /**
     * Hacksaw 子游戏载入入口
     * 请求: /game/hacksaw/lunch?gid=1632
     */
    public function gameLunch(Request $request)
    {
        $gid = (string) $request->input('gid');
        $user = $request->user();
        $userid = $user->UserID;

        $version = self::$gameVersions[$gid] ?? null;
        if ($version === null) {
            abort(404, 'Hacksaw game version not configured for gid: ' . $gid);
        }

        GameCard::$enableStateCheck = false;
        $gamecard = GameCard::where('gid', $gid)->where('brand', 'Hacksaw')->first();
        if (!$gamecard) {
            abort(404, 'Game not found');
        }

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

        $gamecard->increment('play_num', 1);
        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['hacksaw'] ?? $configurls['hkg'] ?? null;
        if (!$configurl) {
            $staticHost = 'static.pgn-nmu2nd.com';
            $apiHost = 'api.pgn-nmu2nd.com';
        } else {
            $staticHost = $configurl['source'] ?? 'static.pgn-nmu2nd.com';
            $apiHost = $configurl['api'] ?? 'api.pgn-nmu2nd.com';
        }

        $cdnserver = 'https://' . $staticHost;
        $apiBase = 'https://' . $apiHost . '/api';
        $lobbyurl = $cdnserver;
//        $sign = GlobalUserInfo::genGuuidSign($user);
        $newToken = base64_encode(random_bytes(20));

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


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

        $data['limit_room']=0;

        $account = AccountsInfo::where('UserID', $userid)->first();
        if(!$account){
            TelegramBot::getDefault()->sendMsgWithEnv("hawksaw_ fail11111:" . json_encode([$request->all(),$data]) );
            abort(404, 'User not found');
        }else{
            $account=$account->toArray();
        }
        $data = array_merge($data, $account);

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

        $params = [
            'language'     => $lang,
            'channel'      => 'mobile',
            'gameid'       => $gid,
            'mode'         => 2,
            'token'        => $newToken,
            'lobbyurl'     => $lobbyurl,
            'currency'     => env('CONFIG_24680_CURRENCY', 'EUR'),
            'partner'      => 'demo',
            'env'          => $apiBase,
            'realmoneyenv' => $apiBase,
        ];

        $url = $cdnserver . '/' . $gid . '/' . $version . '/index.html?' . http_build_query($params);


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