<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Auth;
use Zhuzhichao\IpLocationZh\Ip;

class AdminRequestLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $log=new \App\Models\AdminRequestLog();
        $name='';
        if(Auth::guard('admin')->check()) {
            $name = Auth::guard('admin')->user()->name;
        }
        $ip=$request->ip();
        $address=Ip::find($ip);
        $input=$request->all();
        $ip_arr=$request->header('x-forwarded-for');
        $ip_arr=explode(',',$ip_arr);
        $ddress_arr=[];
        foreach ($ip_arr as $k=>$v){
            $ddress_arr[]=Ip::find(trim($v));
        }
        $log->setAttribute('name',$name );
        $log->setAttribute('path', $request->path());
        $log->setAttribute('method', $request->method());
        $log->setAttribute('ip', $request->ip());
        $log->setAttribute('header', json_encode($request->header(),JSON_UNESCAPED_UNICODE));
        $log->setAttribute('address',json_encode($address,JSON_UNESCAPED_UNICODE));
        $log->setAttribute('address_arr',json_encode($ddress_arr,JSON_UNESCAPED_UNICODE));
        $log->setAttribute('time', Carbon::now()->toDateTimeString());
        $log->setAttribute('ip_arr', $request->header('x-forwarded-for'));
        $log->setAttribute('input', json_encode($input, JSON_UNESCAPED_UNICODE));
        $log->save();
        return $next($request);
    }
}
