<?php

namespace Drupal\miniorange_2fa\Plugin\AuthenticationType;

use Drupal\miniorange_2fa\Plugin\AuthenticationTypePluginBase;
use Drupal\miniorange_2fa\Annotation\AuthenticationType;
use Drupal\miniorange_2fa\UsersAPIHandler;
use Drupal\miniorange_2fa\MoAuthUtilities;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * WebAuthn authentication type plugin.
 *
 * @AuthenticationType(
 *   id = "web-authn",
 *   name = @Translation("Web Authentication"),
 *   code = "WEB AUTHN",
 *   type = "OTHER",
 *   description = @Translation("Use your device Password, PIN, FaceID, Fingerprint, TouchID etc to login to your site."),
 *   supported_devices = {"Hardware Token", "Smartphones", "Laptops"},
 *   challenge = false,
 *   oob = false,
 *   doc_link = "",
 *   video_link = ""
 * )
 */
class WebAuthnType extends AuthenticationTypePluginBase {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
    $this->setFormTitle($form, 'web-authn-methods');
    
   
    $utilities = new MoAuthUtilities();
    $session = $utilities->getSession();
    $moMfaSession = $session->get("mo_auth", null);
    
    if ($moMfaSession && isset($moMfaSession['status']) && $moMfaSession['status'] === '1ST_FACTOR_AUTHENTICATED') {

      $form['mo_wenauthn_message'] = [
        '#type' => 'item',
        '#markup' => $this->t('To configure WebAuthn, you must be logged in. Click on "Submit" to proceed and then configure WebAuthn authentication.')
      ];
      
      $form['actions']['#type'] = 'actions';
      $form['actions']['login'] = [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $this->t('Submit'),
      ];
      
      $form['actions']['cancel'] = [
        '#type' => 'submit',
        '#value' => $this->t('Cancel'),
        '#button_type' => 'danger',
        '#submit' => ['::moCancelInlineRegistration'],
        '#limit_validation_errors' => [],
      ];
    } else {
      $form['webauthn_note'] = [
        '#type' => 'item',
        '#markup' => $this->t('Click on proceed to configure Web Authentication as 2FA method.'),
      ];

      $form['action'] = [
        '#type' => 'actions',
      ];

      $form['action']['proceed'] = [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $this->t('Proceed'),
      ];
    }

    $this->addFormSuffix($form);
    return $form;
  }
  
  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state): void {
   
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
    if (!$this->validateUserSession()) {
      $this->handlePostAuthenticationRedirection(
        false,
        '',
        'User session validation failed.',
        $form_state
      );
      return;
    }
    
    $user = $this->getCurrentUser();
    if (!$user) {
      $this->handlePostAuthenticationRedirection(
        false,
        '',
        'User not found.',
        $form_state
      );
      return;
    }

    $user_id = $user->id();
    $session = MoAuthUtilities::getSession();
    $moMfaSession = $session->get('mo_auth');
    $user_email = $this->getUserEmail($user_id) ?: $moMfaSession['email'];
    
    if (empty($user_email)) {
      $this->handlePostAuthenticationRedirection(
        false,
        '',
        'User email not found.',
        $form_state
      );
      return;
    }

    $customer = $this->createCustomerProfile();
    $user_api_handler = new UsersAPIHandler($customer->getCustomerID(), $customer->getAPIKey());
    
    $miniorange_user = $this->createMiniorangeUser($this->getCode());
    if (!$miniorange_user) {
      $this->handlePostAuthenticationRedirection(
        false,
        '',
        'Failed to create user profile.',
        $form_state
      );
      return;
    }

    
    $result = $this->updateUserAuthenticationMethod($this->getCode(), $miniorange_user, $user_api_handler);
   
    $utilities = new MoAuthUtilities();
    $session = $utilities->getSession();
    $moMfaSession = $session->get("mo_auth", null);
    $user = $this->getCurrentUser() ?: $moMfaSession['uid'];
    $custom_attribute = $utilities::get_users_custom_attribute($user->id());
    $has_registered_email = !empty($custom_attribute) && !empty($custom_attribute[0]->miniorange_registered_email);

    if ($result['success']) {
      if($has_registered_email){
        $this->handlePostAuthenticationRedirection(
    true,
          $result['message'],
          '',
          $form_state,
          [
            'success_route' => 'mo_webauthn.register_form',
            'success_route_params' => ['user' => $user_id]
          ]
        );
      }
      else{
        $user = User::load($moMfaSession['uid']);
        user_login_finalize($user);
        $form_state->setRedirect('mo_webauthn.register_form', ['user' => $moMfaSession['uid']]);
      }
    } else {
      $this->handlePostAuthenticationRedirection(
        false,
        '',
        $result['message'],
        $form_state
      );
    }
  }
  public function moCancelInlineRegistration()
    {
        $session = MoAuthUtilities::getSession();
        $moMfaSession = $session->get("mo_auth", null);
        $account = User::load($moMfaSession['uid']);
        //Remove user from MO dashboard created in previous step (Select method submit)
        MoAuthUtilities::delete_user_from_UserAuthentication_table($account);
        $session->remove('mo_auth');
        $url = Url::fromRoute('user.login')->toString();
        $response = new RedirectResponse($url);
        $response->send();
        exit;
    }
}