<?php
  
  namespace Main\Controllers\TFA;
  
  use Main\Core\Controller;
  use Main\Core\Redirect;
  use Main\Services\SeoService;
  use RobThree\Auth\TwoFactorAuth;
  use RobThree\Auth\TwoFactorAuthException;
  
  class SetupController extends Controller
  {
	  protected string $route_type = 'tfa';
		
	  public function __construct()
		{
			// Check if the user has already enabled TFA
			$checkTfaKeys = db()->prepare("SELECT * FROM AccountTfaKeys WHERE accountID = ?");
			$checkTfaKeys->execute([auth()->user()->id()]);
			if ($checkTfaKeys->rowCount() > 0) abort_404();
		}
		
	  /**
	   * @throws TwoFactorAuthException
	   */
	  public function index()
    {
	    SeoService::set('tfa.index');
			
	    $tfa = new TwoFactorAuth(settings('serverName'));
	    $secretKey = session()->has('tfaSecretKey') ? session()->get('tfaSecretKey') : $tfa->createSecret();
			$qrCode = $tfa->getQRCodeImageAsDataUri(settings('serverName') . ": " . auth()->user()->displayName(), $secretKey);
	    
	    session()->set('tfaSecretKey', $secretKey);
			
	    return $this->view('tfa.setup', compact('qrCode', 'secretKey'));
    }
	  
	  /**
	   * @throws TwoFactorAuthException
	   */
	  public function setup()
	  {
			validate([
				'code' => 'required',
			]);
		  $secretKey = session()->get('tfaSecretKey');
		  $code = input('code');
		  $tfa = new TwoFactorAuth(settings('serverName'));
		  
		  if ($tfa->verifyCode($secretKey, $code) !== true) {
			  return back()->flash('error', t__('Wrong code!'));
			}
		  
		  // Add the secret key
		  $insertSecretKey = db()->prepare("INSERT INTO AccountTfaKeys (accountID, secretKey) VALUES (?, ?)");
		  $insertSecretKey->execute([auth()->user()->id(), $secretKey]);
		  
		  // Clear the session
		  session()->remove('tfaSecretKey');
		  
		  // Redirect to the profile page
		  $redirect = new Redirect(url('account.settings.security'));
		  return $redirect->flash('success', t__('Two Factor Authentication has been enabled!'));
	  }
  }