<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Helpers\RoleHelper;

class MarketingMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (!auth()->check()) {
            return redirect()->route('admin.login');
        }

        $user = auth()->user();
        
        // Autoriser l'accès si l'admin est en mode impersonate d'un marketing
        if (RoleHelper::isImpersonating() && $user->role === 'marketing') {
            return $next($request);
        }

        if (!RoleHelper::canAccessMarketing($user->role)) {
            return redirect()->route('home')->with('error', 'Accès réservé au service Marketing.');
        }

        return $next($request);
    }
}
