<?php

namespace App\Http\Middleware;

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

class CheckPermission
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, ...$permissions)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        $user = Auth::user();

        // التحقق من الصلاحيات
        foreach ($permissions as $permission) {
            if ($user->can($permission)) {
                return $next($request);
            }
        }

        // في حالة عدم وجود صلاحية
        if ($request->expectsJson()) {
            return response()->json([
                'message' => __("You are not authorized to access this resource"),
                'code' => 403
            ], 403);
        }

        abort(403, __("You are not authorized to access this page"));
    }
}
