<?php
session_start();
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_mfa.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/../vendor/autoload.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/login/php/authFunctions.php";


use api\classes\API_mfa;
use RobThree\Auth\TwoFactorAuth;
use RobThree\Auth\Providers\Qr\EndroidQrCodeProvider;

$API_mfa = new API_mfa();

if ($API_mfa->request_method === 'POST') {
    # Set up a new MFA secret its posted from mfaSetup.php where it generated a secret

    if (checkLoginAttempts() > 10) {
        echo 'too many attempts, please try again later.';
        exit;
    }

    # check if the secret is in the session created at the mfaSetup.php file
    if (!isset($_SESSION['mfasetup']['secret'])) {
        $this->apiOutput(400, ['error' => 'secret not found.']);
    }

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

    $API_mfa->postedData['user_uuid'] = $_SESSION['user']['user_uuid'];
    $API_mfa->postedData['user_two_factor_secret'] = $_SESSION['mfasetup']['secret'];
    $API_mfa->postedData['verificationCode'] = linkVerificationPosts(); # The code is entered in six loose posts this wil link it together

    $requiredFields = [
        'user_uuid' => ['type' => 'uuid'],
        'user_two_factor_secret' => ['type' => 'string'],
        'verificationCode' => ['type' => 'string', 'min' => 6, 'max' => 6],
    ];

    $API_mfa->validateData($requiredFields);


    $result = $tfa->verifyCode($API_mfa->postedData['user_two_factor_secret'], $API_mfa->postedData['verificationCode']);
    if (!$result) {
        addLoginAttempts();
        $API_mfa->apiOutput(401, ['error' => 'Invalid verification code.']);
    }

    $API_mfa->enableMFA();

} elseif ($API_mfa->request_method === 'DELETE') {

    # Delete a mfa code for a user

    $API_mfa->return_url = false;

    $requiredFields = [
        'user_uuid' => ['type' => 'uuid'],
    ];

    $API_mfa->validateData($requiredFields);

    $API_mfa->disableMFA();

}