<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\User;

class CheckAdminAuth
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        if (!$request->user() instanceof User) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized. Admin/Staff access required.',
            ], 403);
        }

        $allowedRoles = ['admin', 'teacher', 'staff', 'principal'];
        $hasValidRole = false;

        foreach ($allowedRoles as $role) {
            if ($request->user()->tokenCan($role)) {
                $hasValidRole = true;
                break;
            }
        }

        if (!$hasValidRole) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid token abilities.',
            ], 403);
        }

        return $next($request);
    }
}
