<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Exception;
use \App\Http\Controllers\LogController;

class LogRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    private $end;

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response){
        $this->end = microtime(true);
        try {

            $user_agent = "";
            if ($request->header('User-Agent')) {
                $user_agent = $request->header('User-Agent');
            } else {
                return sendError("Client User-Agent is missing", 400);
            }

            $route_path = $request->route()->uri();
            $matricule = null;

            if($route_path == null){
                $route_path = "-";
            }
            if ($request->get('User')) {
                $matricule = $request->get('User')->matricule;
            }

            $duration = ($this->end - LARAVEL_START);

            $url = $request->fullUrl();
            $route_details = $request->route();
            $method = $request->getMethod();
            $ip = $request->getClientIp();
            $status = $response->getStatusCode();
            $response = $response->getContent();

            $detail = [
                'REALIP' => $request->ips(),
                'STATUT' => $status,
                'USER_AGENT' => $user_agent,
                'DURATION' => LARAVEL_START." - ".$this->end." => ".$duration. ' secondes',
                'ROUTE_PATH' => $route_path,
                'ROUTE_DETAILS' => $route_details,
                // 'URI' => $request->getUri(),
                'URL' => $url,
                'METHOD' => $method,
                'REQUEST_BODY' => $request->all(),
                // 'RESPONSE' => $response
            ];
            // $detail = "route_path : {$route_path} ::statut: [{$status}] / {$method}@{$url} - {$duration}ms";

            LogController::log($ip, $detail, $response, $matricule);
    
        } catch (Exception $e) {
            return sendError('Error Logging :', $e->getMessage(), 500);  
        }
            
    }
    public static function isJson($string){
        return is_string($string) && is_array(json_decode($string, true)) ? true : false;
     }

     public function getIp(){
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
            if (array_key_exists($key, $_SERVER) === true){
                foreach (explode(',', $_SERVER[$key]) as $ip){
                    $ip = trim($ip); // just to be safe
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                        return $ip;
                    }
                }
            }
        }
    }
    
 
}