<?php

declare(strict_types=1);

namespace App\Controllers;

use Core\Controller;
use Core\Request;
use Core\Response;
use Cartalyst\Sentinel\Native\Facades\Sentinel;
use Cartalyst\Sentinel\Checkpoints\ThrottlingException;

class AuthController extends Controller
{
    public function showLogin(): Response
    {
        if (Sentinel::check()) {
            return $this->redirect('/');
        }

        return $this->view('auth.login', ['pageTitle' => 'Login']);
    }

    public function login(): Response
    {
        $request = Request::capture();

        if (!verify_csrf_token($request->input('_token'))) {
            return $this->view('auth.login', [
                'pageTitle' => 'Login',
                'error'     => 'Invalid request. Please try again.',
            ]);
        }

        $credentials = [
            'email'    => (string) $request->input('email'),
            'password' => (string) $request->input('password'),
        ];

        $remember = (bool) $request->input('remember');

        try {
            if (Sentinel::authenticate($credentials, $remember)) {
                return $this->redirect('/');
            }
        } catch (ThrottlingException $e) {
            return $this->view('auth.login', [
                'pageTitle' => 'Login',
                'error'     => 'Too many failed attempts. Please wait ' . $e->getDelay() . ' seconds.',
            ]);
        }

        return $this->view('auth.login', [
            'pageTitle' => 'Login',
            'error'     => 'Invalid email or password.',
        ]);
    }

    public function logout(): Response
    {
        $request = Request::capture();

        if (!verify_csrf_token($request->input('_token'))) {
            return $this->redirect('/');
        }

        Sentinel::logout();

        return $this->redirect('/login');
    }
}
