<?php

namespace App\Game\Services;


use App\Notification\TelegramBot;
use App\Util;
use Closure;


use App\Game\Services\LZCompressor\LZString as LZ;
use App\Game\Services\LZCompressor\LZUtil;

use Symfony\Component\HttpFoundation\Response as SymfonyResponse; // 新增
use Illuminate\Http\JsonResponse; // 可选，用于数组转 JSON 响应

class GameEncrypt
{
    /**
     * 验证签名 API接口
     * @param \Illuminate\Http\Request $request
     * @param Closure $next
     */
    public function handle($request, Closure $next)
    {
        $hasLz=$request->has('lz');
        $debug=RouteService::isTestSite()||$request->has('_db')&&($request->input('_db')=='g');
        //判定一下，如果路由是/game/registerNew 就输出日志
        if($hasLz) {
            if ($request->path() === 'game/registerNew') {
                // 输出日志逻辑
                //Util::WriteLog('register_params', 'Register new user: ' . json_encode($request->all()));
            }

            try{
                $newarr = \GuzzleHttp\json_decode(self::decrypt($request->input('lz')),true);
                $_REQUEST=array_merge($_REQUEST,$newarr);
                $request->replace($newarr);
            }catch (\Exception $exception){

                try{
                    $newarr = \GuzzleHttp\json_decode(utf8_encode(self::decrypt($request->input('lz'))),true);
                    $_REQUEST=array_merge($_REQUEST,$newarr);
                    $request->replace($newarr);
                }catch (\Exception $exception){
                    TelegramBot::getDefault()->sendMsgWithEnv("Game LZ jsdecode:".$exception->getMessage());
                }

            }

        }
        $response = $next($request);

        // 如果是数组响应，统一转成 JsonResponse，避免后面 getContent() 报错 // 新增
        if (is_array($response)) { // 新增
            $response = response()->json($response); // 新增
        } // 新增



        // 如果不是一个 Symfony Response 对象，直接返回，不再做加密和加头 // 新增
        if (!$response instanceof SymfonyResponse) { // 新增
            return $response; // 新增
        } // 新增



        if($debug&&$hasLz){
            $this->header('req',json_encode($request->all()));
        }

        if($hasLz&&!RouteService::isTestSite()&&!$debug) {
            // 对返回内容进行加密处理
            $content = $response->getContent();

            $encryptedContent = self::encrypt($content);

            // 将加密后的内容设置回响应
            $response->setContent($encryptedContent);
        }

        $origin = $request->server('HTTP_ORIGIN') ?? $request->server('HTTP_REFERER') ?? '*';

        $this->header('Access-Control-Allow-Origin', $origin);
        $this->header('Access-Control-Allow-Headers', 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
        $this->header('Access-Control-Expose-Headers', '*');
        $this->header('Access-Control-Allow-Methods', 'GET, POST');
        $this->header('Access-Control-Allow-Credentials', 'true');

        return $response;
    }
    protected function header($key, $value)
    {
        header(sprintf('%s: %s', $key, $value));
    }


    public static function encrypt($str){
        try {

            $encStr = LZ::compressToBase64($str);


        }catch (\Exception $exception){
            TelegramBot::getDefault()->sendProgramNotify("Game LZ encrypt:", $exception->getTraceAsString());
            $encStr=$str;
        }
        return $encStr;
    }
    public static function decrypt($str){
        if (!isset($str)||!$str||empty($str)) {
            # code...
            return '';
        }
        $str=implode("+",explode(" ",$str));
        try {
            $destr=LZ::decompressFromBase64($str);
        }catch (\Exception $exception){
            Util::WriteLog('gamelz',$str);
            TelegramBot::getDefault()->sendProgramNotify("Game LZ decrypt:".$str);
            TelegramBot::getDefault()->sendProgramNotify("Game LZ decrypt:", $exception->getMessage().$exception->getTraceAsString());
            $destr=$str;
        }
        return $destr;


    }
}
