<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckApiPermissions
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if ($user) {
            $role = (int) $user->role;
            $path = $request->path();   
            $method = $request->method(); 

            
            $isRestrictedAction =
                str_contains($path, 'add') ||
                str_contains($path, 'edit') ||
                str_contains($path, 'delete') ||
                in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE']);

            if ($isRestrictedAction && $role < 0) {
                return response()->json([
                    'error' => 'You are not authorized to Do  thos operations (Add/Edit/Delete). Please contact admin.'
                ], 403);
            }
        }

        return $next($request);
    }
}
