<?php

namespace App\Http\Middleware;

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

class EnsureUserIsActivated
{
    /**
     * Handle an incoming request.
     * 
     * Check if the user is activated before allowing access to protected routes.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();
        
        if (!$user) {
            return $next($request);
        }

        // Check if activation is required
        $activationRequired = DB::table('settings')
            ->where('key', 'activation_required')
            ->value('value') === '1';
        
        if (!$activationRequired) {
            return $next($request);
        }

        // Check if user is activated
        if (!$user->is_activated) {
            // Allow access to activation-related and guest/auth routes
            if (
                $request->routeIs('activation.*') ||
                $request->routeIs('logout') ||
                $request->routeIs('login') ||
                $request->routeIs('register') ||
                $request->routeIs('password.*') ||
                $request->routeIs('auth.google') ||
                $request->routeIs('auth.google.callback') ||
                $request->routeIs('password.setup') ||
                $request->routeIs('password.setup.store') ||
                $request->routeIs('home')
            ) {
                return $next($request);
            }

            // Also allow by path patterns (fallback for non-named routes)
            if ($request->is('login', 'register', 'forgot-password', 'reset-password/*', 'auth/google', 'auth/google/callback', 'set-password', 'set-password/*')) {
                return $next($request);
            }

            return redirect()->route('activation.pending');
        }

        return $next($request);
    }
}
