<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class IsAdmin
{
    /**
     * 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)
    {
        if (!empty(auth()->user())) {
            if (auth()->user()->status == PENDING_USER) {
                return logUserOut('user.login', 'error', 'Your account is still undergoing verification. Please check back again later');
            } elseif (auth()->user()->status == SUSPENDED_USER) {
                return logUserOut('user.login', 'error', 'Your account has been suspended. Contact customer support.');
            } elseif (auth()->user()->status == DELETED_USER) {
                return logUserOut('user.login', 'error', 'You no longer have an account with us. Contact customer support.');
            } else {
                if (auth()->user()->role == USER_ROLE) {
                    return redirect(route('user.dashboard'));
                }
                if(auth()->user()->role != ADMIN_ROLE){
                    return logUserOut('user.login', 'error', 'You do not have access to this page. Please Try again');
                }
            }
        } else {
            return logUserOut('user.login', 'error', 'Please login to continue');
        }
        return $next($request);
    }
}
