<?php
    /**
     * This file is part of webman.
     *
     * Licensed under The MIT License
     * For full copyright and license information, please see the MIT-LICENSE.txt
     * Redistributions of files must retain the above copyright notice.
     *
     * @author    walkor<walkor@workerman.net>
     * @copyright walkor<walkor@workerman.net>
     * @link      http://www.workerman.net/
     * @license   http://www.opensource.org/licenses/mit-license.php MIT License
     */

    namespace app\middleware;

    use Illuminate\Support\Arr;
    use Webman\MiddlewareInterface;
    use Webman\Http\Response;
    use Webman\Http\Request;

    /**
     * Class StaticFile
     * @package app\middleware
     */
    class Sign implements MiddlewareInterface
    {
        public function process(Request $request, callable $next): Response
        {
            $sign = $request->header('sign');
            if (empty($sign)) {
                return $this->transfer();
            }
            $transfersecret=$request->header('transfersecret');
            if(empty($transfersecret)){
                return $this->transfer();
            }
            $string_data = openssl_decrypt(base64_decode($transfersecret),'AES-128-ECB',getenv ("JWT_AESKEY"),OPENSSL_RAW_DATA);
            if(!$string_data){
                return $this->transfer();
            }
            $param_data = json_decode($string_data,true);
            if(!$param_data){
                return $this->transfer();
            }
            $param = $param_data;
            if (Arr::get($param, 'time', 0) < (time() - 15)) {
                return $this->transfer();
            }
            if ($sign != $this->sign($param_data)) {
                return $this->transfer();
            }
            /** @var Response $response */
            $response = $next($request);
            return $response;
        }

        public function transfer()
        {
            $arr = [
                0 => 'https://www.baidu.com',
                1 => 'https://weibo.com',
                2 => 'https://www.douyin.com',
                3 => 'https://www.jd.com',
                4 => 'https://uland.taobao.com',
                5 => 'https://news.qq.com',
                6 => 'https://www.toutiao.com',
                7 => 'https://www.kuaishou.com',
                8 => 'https://www.sohu.com',
            ];
            return redirect($arr[mt_rand(0, 8)]);
        }

        public function sign($array)
        {
            ksort($array);                               //ASCII码排序
            $md5str = "";
            foreach ($array as $key => $val) {
                $md5str = $md5str . $key . "=" . $val . "&";
            }
            return md5($md5str . "key=" . getenv('JWT_PRIVATEKEY'));
        }
    }
