<?php
// app/Http/Middleware/SuperAdminMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SuperAdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Check if user is authenticated
        if (!Auth::check()) {
            return redirect()->route('super.admin.login')->with('error', 'Please login first.');
        }

        $user = Auth::user();
        
        // Check if user has super_admin role
        if ($user->role !== 'super_admin') {
            // Log the attempt for security
            \Log::warning('Unauthorized access attempt to super admin area', [
                'user_id' => $user->id,
                'user_email' => $user->email,
                'user_role' => $user->role,
                'ip' => $request->ip(),
                'url' => $request->fullUrl()
            ]);
            
            // Redirect based on user role
            if ($user->role === 'manager' || $user->role === 'staff') {
                return redirect()->route('dashboard')->with('error', 'You do not have permission to access the super admin area.');
            }
            
            // For any other role, logout and redirect to login
            Auth::logout();
            return redirect()->route('super.admin.login')->with('error', 'Unauthorized access. Please login with super admin credentials.');
        }

        return $next($request);
    }
}