<?php

namespace App\Http\Middleware;

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

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Debug: Log middleware check
        Log::info('AdminMiddleware Check', [
            'url' => $request->url(),
            'session_id' => session()->getId(),
            'guard_check' => Auth::guard('admin')->check(),
            'has_user' => Auth::guard('admin')->user() !== null,
            'user_id' => Auth::guard('admin')->id(),
        ]);

        // Check if admin is authenticated using admin guard
        if (!Auth::guard('admin')->check()) {
            Log::warning('AdminMiddleware - Not Authenticated', [
                'session_id' => session()->getId(),
            ]);
            return redirect()->route('admin.login')->with('error', 'Please login to access admin panel');
        }

        $user = Auth::guard('admin')->user();

        // Debug: Log user details
        Log::info('AdminMiddleware - User Found', [
            'user_id' => $user->id,
            'email' => $user->email,
            'role' => $user->role,
        ]);

        // Check if user has admin role
        if ($user->role !== 'admin') {
            Auth::guard('admin')->logout();
            Log::warning('AdminMiddleware - Not Admin Role', ['user_id' => $user->id]);
            abort(403, 'Unauthorized access. Admin only.');
        }

        return $next($request);
    }
}
