<?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;

class GameEncrypt
{
    /**
     * 验证签名 API接口
     * @param \Illuminate\Http\Request $request
     * @param Closure $next
     */
    public function handle($request, Closure $next)
    {
        $hasLz=$request->has('lz');
        $debug=$request->has('_db')&&($request->input('_db')=='g');
        if($hasLz) {
            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);
        if($debug&&$hasLz&&is_array($response)){
            $response['req']=$request->all();
        }

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

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

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

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


        $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;


    }
}
