<?php

namespace App\Http\Middleware;

use App\Http\Response\ResponseJson;
use App\Models\AppVersion;
use App\Models\IosVersion;
use Closure;
use Illuminate\Http\Request;
use App\Models\Banlist;
use Log;
class CheckBanlist
{
    use ResponseJson;
    /**
     * 检查当前账号是否被封号
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //当前版本号
        $current_version = $request->header("version");
        //最新版本号
        $source = $request->header("source");
        $is_server = $request->header("isserver");
        if ($is_server == 1) return $next($request);
        if ($source == "android") {
            $last_version = "3.5.2.2";
        }else {
            $arr = explode(".", $current_version);
            if (count($arr) == 4) {
                $last_version = "1.1.3.2";
            }else {
                $last_version = "1.1.9";
            }

        }
        if (version_compare($current_version, $last_version, '<=')) return $next($request);
        // 是否封Ip
        $headers = $request->header();
        if (isset($headers["x-forwarded-for"]) && count($headers["x-forwarded-for"])) {
            $ip = $headers["x-forwarded-for"][0];
        }else {
            return $this->failure("缺少用户ip");
        }
        if (isset($headers["device-id"]) && $headers["device-id"]) {
            $device_id = $headers["device-id"];
        }else {
            return $this->failure("缺少设备标识");
        }
        $user_id = auth()->id();
        $ban = Banlist::where(function($sql) use($user_id) {
            $sql->where(["type"=>"user", "value"=>$user_id])->where(function($query) {
                $now = date("Y-m-d H:i:s");
                $query->whereNull('expired_at')->orWhere("expired_at", ">", $now);
            });
        })->first();
        if ($ban) return $this->banFail("当前账号已被封, 请联系客服");
        $ban = Banlist::where(function($sql) use($ip) {
            $sql->where(["type"=>"ip", "value"=>$ip])->where(function($query) {
                $now = date("Y-m-d H:i:s");
                $query->whereNull('expired_at')->orWhere("expired_at", ">", $now);
            });
        })->first();
        if ($ban) return $this->banFail("当前ip已被封, 请联系客服");
        $ban = Banlist::where(function($sql) use($device_id) {
            $sql->where(["type"=>"device", "value"=>$device_id])->where(function($query) {
                $now = date("Y-m-d H:i:s");
                $query->whereNull('expired_at')->orWhere("expired_at", ">", $now);
            });
        })->first();
        if ($ban) return $this->banFail("当前设备已被封, 请联系客服");
        
        return $next($request);
    }
}
