<?php

namespace App\Http\Middleware;

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

class CheckPermission
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, ...$permissions): Response
    {
        // Debug logging
        Log::info('CheckPermission middleware triggered', [
            'user_id' => Auth::id(),
            'required_permissions' => $permissions,
            'path' => $request->path(),
        ]);

        // Check if user is authenticated
        if (!Auth::check()) {
            Log::warning('User not authenticated, redirecting to login');
            return redirect()->route('login');
        }

        $user = Auth::user();
        
        // Debug user permissions
        Log::info('User permissions check', [
            'user_id' => $user->id,
            'user_email' => $user->email,
            'user_permissions' => $user->getAllPermissions()->pluck('name')->toArray(),
        ]);
        
        // Check if user has any of the required permissions
        foreach ($permissions as $permission) {
            if ($user->hasPermissionTo($permission)) {
                Log::info('Access granted by permission', [
                    'user_id' => $user->id,
                    'granted_permission' => $permission,
                ]);
                return $next($request);
            }
        }

        // Log unauthorized access attempt
        Log::warning('Unauthorized access attempt - missing permission', [
            'user_id' => $user->id,
            'user_email' => $user->email,
            'required_permissions' => $permissions,
            'user_permissions' => $user->getAllPermissions()->pluck('name')->toArray(),
        ]);

        // If user doesn't have required permission
        return redirect()->route('dashboard')
            ->with('error', 'You do not have permission to access this page.');
    }
}