<?php
session_start();

# includes
require_once "{$_SERVER['DOCUMENT_ROOT']}/../vendor/autoload.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/login/php/authFunctions.php";

use RobThree\Auth\Providers\Qr\EndroidQrCodeProvider;
use RobThree\Auth\TwoFactorAuth;

if (!isset($_POST['verification-1']) && !isset($_SESSION['mfa']['user_secret']) && !isset($_SESSION['mfa']['user_uuid'])) {
    unset($_SESSION['mfa']);
    addLoginAttempts();
    header('Location: /');
    exit;
}

if (checkLoginAttempts() > 3) {
    header('Location: /login/');
    exit;
}

$tfa = new TwoFactorAuth(new EndroidQrCodeProvider());

$secret = $_SESSION['mfa']['user_secret'];
$postedCode = linkVerificationPosts();

if ($postedCode) {
    $result = $tfa->verifyCode($secret, $postedCode);

    if ($result) {
        loginUser($_SESSION['mfa']['user_uuid']);
        unset($_SESSION['mfa']);

    } else {
        addLoginAttempts();
        setcookie('login_error', 'Invalid verification code', time() + 3600, '/');

    }
} else {
    unset($_SESSION['mfa']);

}
header('Location: /');
exit;