<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class Sesion {
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response {
        $usuario = Session::get('usuario');
        $two_fa_verified = Session::get('2fa_verified');
        $google_auth = Session::get('google_auth');
        $token_validacion = $request->input('token_id_usuario');
        $token_por_secciones = $request->input('token_por_secciones');

        if (!$usuario) {
            if (!$token_validacion && !$token_por_secciones) {
                return redirect('/login');
            }
        }
        //
        if ( $two_fa_verified !== true && $google_auth !== true ){
            Session::flush();
            Session::save();
            return redirect('/login');
        }

        return $next($request);
    }
}
