<?php

namespace App\Http\Middleware;

use App\Models\Trace;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;

class RoleChecker
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //A initialiser en fonction
        if (Auth::user() && Auth::user()->status == 1) {

            DB::enableQueryLog();

            Trace::create([
                'ip' => $request->ip(),
                'user_id' => Auth::user()->id,
                'name' => Auth::user()->prenom.' '.Auth::user()->nom,
                'action' => URL::current(),
            ]);

            // $link=$request->path();
            // $check_f = Fonction::where('link',$link)->count() ?? 0;
            // if($check_f!=0){
            //     $fonction_id = Fonction::where('link',$link)->first()->id ?? 0;
            //     $id_user = Auth::user()->id;
            //     $p = Privilege::where('fonction_id',$fonction_id)->where('user_id',$id_user)->count();
            //     if($p!=0){
            //         return $next($request);
            //     }
            //     else{
            //         return redirect('/')->with('error','Vous n\'avez pas le droit d\'access !');
            //     }
            // }
            // else{
            //     return $next($request);

            // }

            return $next($request);

        }

        return redirect('/')->with('error','Vous n\'avez pas le droit d\'access !');
    }
}
//Crée par Baniamey Camara 71417839
