<?php

namespace App\Http\Middleware;

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

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

            if (true === $user->jeBlokovany()) {
                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.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return string|null
     */
    protected function redirectTo(Request $request)
    {
        if (! $request->expectsJson()) {
            return route('login.form');
        }
    }
}
