<?php

namespace Drupal\miniorange_2fa\Helper\FormHelper;

use Drupal\miniorange_2fa\Form\miniorange_configure_method;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\miniorange_2fa\AuthenticationType;
use Drupal\miniorange_2fa\MiniorangeUser;


/**
 * @file
 *  This is used to generate Totp fields.
 */
class MoTfaTotp
{
  public function renderTotpForm($form, $totp_method, $qrCode, $secret, $challengeResponse = NULL)
  {
    $form['step_one'] = array(
      '#markup' => '
        <h5>' . t('Step 1 : Download the @method_name app', ['@method_name' => $totp_method['name']]) . '</h5>
        <ul>
            <li class="two-step-verification--app-item--ios">iPhone, iPod Touch, or iPad: <a target="_blank" href="' . $totp_method['ios-link'] . '">' . ('Download') . '</a></li>
            <li class="two-step-verification--app-item--android ">Android devices: <a target="_blank" href="' . $totp_method['android-link'] . '">' . t('Download') . '</a></li>
        </ul><hr>',
    );

    $form['step_two'] = array(
      '#markup' => '<h5>' . t('Step 2: Scan this QR code with the app') . '</h5>'
    );

    $qrCodeString = $challengeResponse->qrCodeData ?? '';
    $qrCode_new = $qrCodeString ? $qrCodeString : $qrCode;
    $form['mo_scan_qr_code_google_authenticator']['actions_qrcode'] = array(
      '#markup' => new FormattableMarkup('<img src="data:image/jpg;base64, ' . $qrCode_new . '"/>', [':src' => $qrCode_new]) ?? '',
      '#prefix' => '<div class="form-item--editor-format">',
      '#suffix' => '	&nbsp;&nbsp;',
    );

    $secret_final = $secret ? $secret : $challengeResponse->secret;
    $secret_next = self::indentSecret($secret_final);
    $form['mo_scan_qr_code_google_authenticator']['secret'] = array(
      '#type' => 'hidden',
      '#value' => $secret_next
    );

    $form['mo_scan_qr_code_google_authenticator']['qrCode'] = array(
      '#type' => 'hidden',
      '#value' => $qrCode_new
    );


    $form['mo_scan_qr_code_google_authenticator']['actions_secret_key'] = array(
      '#markup' => t('<div class="qr_code_text">
                            <p><b>' . t('Can\'t scan the code? ') . '</b>' . t('Add the code to @method_name app manually:', ['@method_name' => $totp_method['name']]) . '</p>
                            <p id="googleAuthSecret"><b>Key: </b> <code class="mo_2fa_highlight_background_note">' . $secret_next . '</code> (Spaces does\'t matter)</p>
                            <p><b>' . t('Time based: ') . '</b>' . t('Yes') . '</p>
                          </div></div><hr>')
    );

    $form['mo_scan_qr_code_google_authenticator']['actions_3'] = array(
      '#markup' => '<h5>' . t('Step 3: Enter the passcode generated by the app') . '</h5>'
    );

    $form['mo_scan_qr_code_google_authenticator']['mo_auth_google_auth_token'] = array(
      '#type' => 'textfield',
      '#title' => t('Passcode:'),
      '#maxlength' => 8,
      '#id' => 'passcode',
      '#attributes' => array(
        'placeholder' => t('Enter passcode'),
        'class' => array(
          'mo2f-textbox',
        ),
      ),
      '#required' => true,
      '#prefix' => '<div class="container-inline">',
      '#suffix' => '&nbsp;&nbsp;',
    );
    return $form;
  }
  public static function indentSecret($secret)
  {
    $strlen = strlen($secret);
    $indented = '';
    for ($i = 0; $i <= $strlen; $i = $i + 4) {
      $indented .= substr($secret, $i, 4) . ' ';
    }
    $indented = trim($indented);
    return $indented;
  }

  public function totpValidate(array &$form, FormStateInterface $form_state, $challengeResponse, $customer, $email, $auth_api_handler, $user)
  {
    $form_values = $form_state->getValues();
    $secret = $challengeResponse->secret;
    $passcode = $form_values['mo_auth_google_auth_token'];
    $miniorange_user = new MiniorangeUser($customer->getCustomerID(), $email, NULL, NULL, AuthenticationType::$GOOGLE_AUTHENTICATOR['code']);
    $response = $auth_api_handler->register($miniorange_user, AuthenticationType::$GOOGLE_AUTHENTICATOR['code'], $secret, $passcode, NULL);
    if (is_object($response) && $response->status == 'SUCCESS') {
      $obj = new miniorange_configure_method;
      $obj->saveAuthenticationMethod($user);
    } elseif (is_object($response) && $response->status == 'FAILED' && $response->message == 'The OTP you have entered is incorrect.') {
      \Drupal::messenger()->addError(t('The passcode(OTP) you have entered is incorrect. Please enter correct passcode.'));
      return;
    }
  }
}
