<?php

namespace App\Http\Middleware;

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

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 1. Check if user is logged in AND is an admin
        if (! $request->user() || $request->user()->role !== 'admin') {
            
            // If it's an API request, return JSON error
            if ($request->wantsJson() || $request->is('api/*')) {
                return response()->json([
                    'message' => 'Unauthorized. Admin privileges required.'
                ], 403);
            }

            // If it's a Web request (Browser), show 403 Forbidden page
            abort(403, 'User does not have admin access.');
        }

        return $next($request);
    }
}