<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Http\Controllers\Admin\MailController;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;

class is2fa
{
    /**
     * 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)
    {
        if(auth()->user()->is_two_factor == 1){
            if(session('verified_2fa') != true){
                $user = auth()->user();
                $token = random_int(1000, 9999);

                $expiresAt = Carbon::now()->addMinutes(30);
                $user->two_factor_expiry_date = $expiresAt;
                $user->two_factor_code = $token;
                $user->save();
        
                try {
                    $mail = new MailController();
                    $mail->twoFaMail($token, $user->email);
                    return redirect()->route('2fa.verification');
                } catch (\Throwable $th) {
                    return redirect()->route('2fa.verification')->with('error', 'A mail cannot be sent at this time');
                }
            }
        }

        return $next($request);
    }
}
