<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\PotentiallyTranslatedString;
use PHPGangsta_GoogleAuthenticator;

class CorrectTwoFactorCode implements ValidationRule {

    public ?string $twoFactorSecret;
    public ?string $twoFactorCurrentSecret;
    public ?string $twoFactorCode;
    public ?string $requireTwoFactor;

    public function __construct( $requireTwoFactor, $twoFactorSecret, $twoFactorCode, $twoFactorCurrentSecret = '' ) {
        $this->twoFactorSecret        = $twoFactorSecret;
        $this->twoFactorCode          = $twoFactorCode;
        $this->requireTwoFactor       = $requireTwoFactor;
        $this->twoFactorCurrentSecret = $twoFactorCurrentSecret;
    }

    /**
     * Run the validation rule.
     *
     * @param string $attribute
     * @param mixed $value
     * @param Closure(string): PotentiallyTranslatedString $fail
     */
    public function validate( string $attribute, mixed $value, Closure $fail ): void {
        $ga = new PHPGangsta_GoogleAuthenticator();

        if ( $this->twoFactorCurrentSecret == '' || $this->twoFactorCurrentSecret != $this->twoFactorSecret ) {
            if ( $this->requireTwoFactor && ! $ga->verifyCode( $this->twoFactorSecret, $this->twoFactorCode, 2 ) ) {
                $fail( __( 'Incorrect two factor code.' ) );
            }
        }
    }
}
