<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
use App\Models\SecuritySetting;

class CheckTwoFactor
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();
        
        // If not logged in, pass through
        if (!$user) {
            return $next($request);
        }

        // Only enforce for SaaS Admins
        if (!$user->hasRole('Admin')) {
            return $next($request);
        }

        // Check if 2FA is enabled in global settings
        $settings = SecuritySetting::first();
        if (!$settings || !$settings->enable_2fa) {
            return $next($request);
        }

        // Exclude 2FA routes and logout to prevent loop
        if ($request->routeIs('admin.2fa.*') || $request->routeIs('logout')) {
            return $next($request);
        }

        // Check if user has set up 2FA
        if (!$user->two_factor_confirmed_at) {
            return redirect()->route('admin.2fa.setup');
        }

        // Check if session is verified
        if (!session('2fa_verified')) {
            return redirect()->route('admin.2fa.verify');
        }

        return $next($request);
    }
}
