<?php

namespace App\Http\Middleware;

use App\Exceptions\Pouzivatel\PouzivatelJeBlokovany;
use Closure;
use Illuminate\Http\Request;

/**
 * Class UserIsNotBlocked
 */
class UserIsNotBlocked
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     *
     * @throws \App\Exceptions\pouzivatel\PouzivatelJeBlokovany
     */
    public function handle($request, Closure $next)
    {
        if (auth()->check()) {
            $user = $request->user();

            if ($user->jeBlokovany() === true) {
                auth()->logout();
                throw new PouzivatelJeBlokovany($user, $this->redirectTo($request));
            }
        }

        return $next($request);
    }

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     *
     * @return string|null
     */
    protected function redirectTo(Request $request)
    {
        if (! $request->expectsJson()) {
            return route('login.form');
        }
    }
}
