<?php

use Dolphy\Plugin\Ajax\Action;
use Dolphy\Plugin\Ajax\Request;
use Dolphy\Plugin\Ajax\Response;
use Dolphy\Plugin\Exceptions\Exception;
use Dolphy\Plugin\Helpers\User;
use Dolphy\Plugin\Security\DPLC;
use Dolphy\Plugin\Security\TwoFA;

defined('DOLPHY_PLUGIN') or die('Access Denied!');

Action::add('post', '2fa', function (Request $request) {
  $code = sanitize_text_field($request->input('code'));
  $dplcCode = sanitize_text_field($request->input('dplc'));

  $remember = $request->input('remember', false);
  if (!is_bool($remember)) $remember = false;

  if (!($dplc = DPLC::findByCode($dplcCode))) {
    throw new Exception('Invalid request', 400);
  }

  if (!($user = User::findBy('id', $dplc->userId))) {
    throw new Exception('No such user', 400);
  }

  if (!TwoFA::verify($user, $code, $dplcCode)) {
    throw new Exception('Invalid Code', 400);
  }

  if ($remember) {
    TwoFA::remember($user->ID);
  }

  Response::send('Two-Factor Authentication Verified!');
});
