<?php

namespace App\Http\Middleware;

use App\Models\System_log;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SystemLogs
{
    /**
     * Handle an incoming request.
     *
     * @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)
    {
        $response = $next($request);


        $log = [
            "USER"=>auth()->user(),
            'URI' => $request->getUri(),
            'IP' => $request->ip(),
            'METHOD' => $request->getMethod(),
            'REQUEST_BODY' => $request->all(),
            'RESPONSE' => $response->getContent()
        ];
        $date = date('Y-m-d', strtotime(now()));
       if($request->getMethod()=="GET"){
           System_log::create([
               "user_id"=> Auth::id()??NULL,
               "url"=>$request->getUri(),
               "ip"=> $request->ip(),
               "agent"=> $request->header('user-agent') !== null ?$request->header('user-agent'):"_SYSTEM_",
               "method"=>$request->getMethod(),
               "request_body"=>json_encode($request->all()),
               'response' => "GET",
               "dated_on" => $date
           ]);
       }else{
           System_log::create([
               "user_id"=> Auth::id()??NULL,
               "url"=>$request->getUri(),
               "ip"=> $request->ip(),
               "method"=>$request->getMethod(),
               "request_body"=>json_encode($request->all()),
               'response' => $response->getContent(),
               'dated_on' => $date
           ]);
       }


    return $response;
    }
}
