<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Traits\HasRoles;
class isUserMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        $user = auth()->user();

        if ($user && $user->roles->contains('name', 'user') && !$user->roles->contains('name', 'admin')) {
            if ($user->status == 'blocked') { 
                return redirect()->route('user.login')->with('error', 'Your account is blocked.');
            }
            return $next($request);
        }

        return redirect()->back()->with('error', 'Unauthorized access.');

    }
}
