<?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\PlatformService;
use App\Game\Services\ServerService;
use App\Game\Services\EvoplayService;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Notification\TelegramBot;
use App\Util;
use App\Utility\SetNXLock;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

class EvoplayController extends Controller
{
    protected $evoplayService;
    protected $projectId;
    protected $secretKey;
    protected $currency;

    public function __construct(EvoplayService $evoplayService)
    {
        $this->evoplayService = $evoplayService;
        $this->projectId = env('EVOPLAY_PROJECT_ID', '');
        $this->secretKey = env('EVOPLAY_SECRET_KEY', '');
        $this->currency = env('CONFIG_24680_CURRENCY');
    }

    /**
     * 游戏启动页面
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function gameLunch(Request $request)
    {
        // 获取请求参数
        $gid = $request->input('gid');
        $user = $request->user();
        $userId = $user->UserID;
        $globalUID = $user->GlobalUID;

        // 检查用户渠道权限 (如果需要)
        if ($user->Channel != 99 && $user->Channel != 44) {
            http_response_code(404);
            exit();
        }

        // 找到游戏卡片
        GameCard::$enableStateCheck = false;
        $gamecard = GameCard::where('gid', $gid)->first();

        // 检查用户当前游戏状态
        $inGameId = OuroGameService::getUserInGame($userId, $globalUID);
        if ($inGameId != intval($gamecard->id)) {
            Util::WriteLog('24680game', compact('inGameId', 'gamecard', 'user'));
        }

        // 记录游戏点击
        $gamecard = GameCard::where('gid', $gid)->where('brand', 'Evoplay')->first();
        $gamecard->increment('play_num', 1);
        LogGamecardClick::recordClick($gamecard->id, $userId);

        // 获取用户语言
        $lang = GlobalUserInfo::getLocale();
        $supportedLangs = ['en', 'zh', 'ru', 'ja', 'ko', 'th', 'vi', 'id', 'ms', 'fr', 'es', 'de', 'tr', 'pt', 'ar'];
        if (!in_array($lang, $supportedLangs)) {
            $lang = 'en';
        }

        // 关闭加载动画
        echo "<script>
parent.postMessage({cmd:\"closeLoading\"},\"*\");
</script>";

        // 设置缓存控制头
        header("Cache-Control: no-cache, no-store, must-revalidate");
        header("Expires: 0");

        try {
            // 使用服务获取游戏启动URL
            $gameUrl = $this->evoplayService->getGameUrl($gid, $globalUID, $lang);

            if ($gameUrl) {
                $htmlContent = "<script>window.location.href='".$gameUrl."';</script>";
                echo $htmlContent;
                exit();
            } else {
                echo "<script>alert('无法获取游戏URL，请稍后再试');</script>";
                exit();
            }

        } catch (\Exception $e) {
            Util::WriteLog('evoplay_error', $e->getMessage());
            echo "<script>alert('系统错误: " . $e->getMessage() . "');</script>";
            exit();
        }
    }

    /**
     * 获取游戏列表
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function gameList(Request $request)
    {
        try {
            // 使用服务获取游戏列表
            $result = $this->evoplayService->getGamesList();
            return response()->json($result);

        } catch (\Exception $e) {
            Util::WriteLog('evoplay_error', $e->getMessage());
            return response()->json([
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 回调接口 - 用户验证
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function verifyPlayer(Request $request)
    {
        $data = $request->all();
        Util::WriteLog('evoplay', [$data, $request->header()]);

        // 验证签名
        if (!$this->verifyRequest($request)) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'INVALID_SIGNATURE',
                    'message' => 'Invalid signature'
                ]
            ], 401);
        }

        $userId = $data['user_id'] ?? null;

        if (!$userId) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'MISSING_PARAMETER',
                    'message' => 'Missing user_id parameter'
                ]
            ], 400);
        }

        if (!ServerService::IsLocalUser($userId)) {
            return $this->evoplayService->callSubApi($userId, $request);
        }

        // 验证用户
        return response()->json($this->evoplayService->validateUser($userId));
    }

    /**
     * 回调接口 - 获取余额
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBalance(Request $request)
    {
        $data = $request->all();
        Util::WriteLog('evoplay', $data);

        // 验证签名
        if (!$this->verifyRequest($request)) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'INVALID_SIGNATURE',
                    'message' => 'Invalid signature'
                ]
            ], 401);
        }

        $userId = $data['user_id'] ?? null;

        if (!$userId) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'MISSING_PARAMETER',
                    'message' => 'Missing user_id parameter'
                ]
            ], 400);
        }

        if (!ServerService::IsLocalUser($userId)) {
            return $this->evoplayService->callSubApi($userId, $request);
        }

        // 获取余额
        return response()->json($this->evoplayService->getBalance($userId));
    }

    /**
     * 回调接口 - 下注
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bet(Request $request)
    {
        $data = $request->all();
        Util::WriteLog('evoplay', $data);

        // 验证签名
        if (!$this->verifyRequest($request)) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'INVALID_SIGNATURE',
                    'message' => 'Invalid signature'
                ]
            ], 401);
        }

        $userId = $data['user_id'] ?? null;
        $gameId = $data['game_id'] ?? null;
        $amount = $data['amount'] ?? 0;
        $transactionId = $data['transaction_id'] ?? null;
        $roundId = $data['round_id'] ?? null;

        // 验证必须的参数
        if (!$userId || !$transactionId || !$gameId || $amount <= 0) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'MISSING_PARAMETER',
                    'message' => 'Missing required parameters'
                ]
            ], 400);
        }

        if (!ServerService::IsLocalUser($userId)) {
            return $this->evoplayService->callSubApi($userId, $request);
        }

        // 处理下注
        return response()->json($this->evoplayService->bet($userId, $gameId, $amount, $transactionId, $roundId));
    }

    /**
     * 回调接口 - 赢钱
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function win(Request $request)
    {
        $data = $request->all();
        Util::WriteLog('evoplay', $data);

        // 验证签名
        if (!$this->verifyRequest($request)) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'INVALID_SIGNATURE',
                    'message' => 'Invalid signature'
                ]
            ], 401);
        }

        $userId = $data['user_id'] ?? null;
        $gameId = $data['game_id'] ?? null;
        $amount = $data['amount'] ?? 0;
        $transactionId = $data['transaction_id'] ?? null;
        $roundId = $data['round_id'] ?? null;
        $betTransactionId = $data['bet_transaction_id'] ?? null;

        // 验证必须的参数
        if (!$userId || !$transactionId || !$gameId || $amount <= 0) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'MISSING_PARAMETER',
                    'message' => 'Missing required parameters'
                ]
            ], 400);
        }

        if (!ServerService::IsLocalUser($userId)) {
            return $this->evoplayService->callSubApi($userId, $request);
        }

        // 处理赢钱
        return response()->json($this->evoplayService->win($userId, $gameId, $amount, $transactionId, $roundId, $betTransactionId));
    }

    /**
     * 回调接口 - 回滚交易
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function rollback(Request $request)
    {
        $data = $request->all();
        Util::WriteLog('evoplay', $data);

        // 验证签名
        if (!$this->verifyRequest($request)) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'INVALID_SIGNATURE',
                    'message' => 'Invalid signature'
                ]
            ], 401);
        }

        $userId = $data['user_id'] ?? null;
        $transactionId = $data['transaction_id'] ?? null;
        $rollbackTransactionId = $data['rollback_transaction_id'] ?? null;

        // 验证必须的参数
        if (!$userId || !$transactionId || !$rollbackTransactionId) {
            return response()->json([
                'status' => 'error',
                'error' => [
                    'code' => 'MISSING_PARAMETER',
                    'message' => 'Missing required parameters'
                ]
            ], 400);
        }

        if (!ServerService::IsLocalUser($userId)) {
            return $this->evoplayService->callSubApi($userId, $request);
        }

        // 处理回滚
        return response()->json($this->evoplayService->rollback($userId, $transactionId, $rollbackTransactionId));
    }

    /**
     * 验证请求的真实性
     *
     * @param Request $request
     * @return bool
     */
    private function verifyRequest(Request $request)
    {
        // 在测试环境可以跳过验证
        if (env('APP_ENV') === 'local' || env('APP_ENV') === 'testing') {
            return true;
        }

        $signature = $request->header('X-Signature');
        if (empty($signature)) {
            Util::WriteLog('evoplay', 'Missing signature header');
            return false;
        }

        // 获取请求数据
        $data = $request->all();

        // 从请求中移除签名字段
        if (isset($data['signature'])) {
            unset($data['signature']);
        }

        // 生成预期的签名
        $expectedSignature = $this->evoplayService->generateSignature($data);

        // 比较签名
        $isValid = ($signature === $expectedSignature);

        Util::WriteLog('evoplay', [
            'received_signature' => $signature,
            'expected_signature' => $expectedSignature,
            'is_valid' => $isValid
        ]);

        return $isValid;
    }
}
