<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\LoginPostRequest;
use App\Models\Pouzivatel\Authentication;
use App\Providers\RouteServiceProvider;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Foundation\Auth\RedirectsUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * @var \App\Models\Pouzivatel\Authentication
     */
    private $authentication;

    /**
     * Create a new controller instance.
     *
     * @param \App\Models\Pouzivatel\Authentication $authentication
     */
    public function __construct(Authentication $authentication)
    {
        $this->authentication = $authentication;
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\View\View
     */
    public function showLoginForm()
    {
        return view('pages.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param \App\Http\Requests\LoginPostRequest $request
     * @param \Illuminate\Contracts\Auth\Guard $guard
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Exception
     */
    public function login(LoginPostRequest $request, Guard $guard)
    {
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (
            method_exists($this, 'hasTooManyLoginAttempts')
            && $this->hasTooManyLoginAttempts($request)
        ) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request, $guard)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Contracts\Auth\Guard $guard
     *
     * @return bool
     * @throws \Exception
     */
    protected function attemptLogin(Request $request, Guard $guard): bool
    {
        try {
            // autentifikuje pouzivatela pomocou autentifikacnej sluzby (AISEK)
            // v pripade uspesnej autentifikacie pouzivatela vytvori pouzivatela v ramci Portalu
            $this->authentication->auth($request->all());
        } catch (Exception $exc) {
            // pouzivatela sa nepodarilo autentifikovat pomocou autentifikacnej sluzby (AISEK)
            if ($exc instanceof AuthenticationException) {
                flash()->error($exc->getMessage());

                return false;
            }

            // autentifikacna sluzba (AISEK) nebola dostupna pre autentifikaciu pouzivatela, pouzivatel nemohol byt autentifikovany
            // v takomto pripade smie byt prihlaseny len existujuci pouzivatel v ramci Portalu ale len ak ma priradenu rolu "admin"
            if (Auth::attempt($this->credentials($request))) {
                /** @var \App\Models\Pouzivatel\Pouzivatel $user */
                $user = Auth::user();
                // odstrani informacnu spravu o uspesnom prihlaseni pouzivatela v prehliadaci
                flash()->clear();

                if (!$user->hasRole('admin')) {
                    flash()
                        ->error('Používateľ nemohol byť autentifikovaný bez použitia autentifikačnej autority.')
                        ->important();
                    Auth::logout();

                    return false;
                }
            }
        }

        return $this->guard()->attempt(
            $this->credentials($request),
            $request->filled('remember'),
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'login';
    }

    /**
     * Log the user out of the application.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        flash()->success('Boli ste odhlásený.')->important();

        if ($response = $this->loggedOut($request)) {
            return $response;
        }

        return $request->wantsJson()
            ? new Response('', 204)
            : redirect($this->redirectTo);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }

    /**
     * The user has logged out of the application.
     *
     * @param \Illuminate\Http\Request $request
     * @return mixed
     */
    protected function loggedOut(Request $request)
    {
        if ($this->guard()->check()) {
            return response()->redirectTo($this->redirectTo);
        }

        return response()->redirectToRoute('login.form');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        if ($response = $this->authenticated($request, $this->guard()->user())) {
            return $response;
        }

        return $request->wantsJson()
            ? new Response('', 204)
            : redirect()->intended($this->redirectTo);
    }

    /**
     * The user has been authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param mixed $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        return redirect()->intended($this->redirectTo);
    }

    /**
     * Get the failed login response instance.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);
    }
}
