<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if user is authenticated
        if (!$request->user()) {
            return redirect()->route('login')->with('error', 'You must be logged in to access this page');
        }

        // Check if user has admin role
        if (!$request->user()->hasRole('admin')) {
            abort(403, 'You are not authorized to access the admin panel');
        }

        // Additional security: Check if user is active (skip for test emails)
        $email = $request->user()->email;
        $isTestEmail = str_contains($email, '@example.com') || 
                      str_contains($email, '@test.com') || 
                      str_contains($email, '@localhost') ||
                      str_contains($email, '@demo.com');
        
        if (!$request->user()->email_verified_at) {
            if ($isTestEmail) {
                return redirect()->route('test-email-warning');
            } else {
                abort(403, 'You must verify your email address first');
            }
        }

        return $next($request);
    }
}


