<?php

namespace Drupal\rest_api_authentication\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\rest_api_authentication\MiniorangeApiAuthSupport;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Form for the requesting the trial request.
 */
class MiniornageAPIAuthnRequestTrial extends FormBase {
  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  use StringTranslationTrait;

  /**
   * Constructor.
   */
  public function __construct(MessengerInterface $messenger, FormBuilderInterface $form_builder) {
    $this->messenger = $messenger;
    $this->formBuilder = $form_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('messenger'),
      $container->get('form_builder')
    );
  }

  /**
   * {@inheritDoc}
   */
  public function getFormId() {
    return 'rest_api_authentication_request_support';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
    $form['#prefix'] = '<div id="modal_example_form">';
    $form['#suffix'] = '</div>';

    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];

    $trial_type = $form_state->get('trial_type');

    // STEP 1: Trial type selection.
    if (empty($trial_type)) {
      // Sandbox trial (display only)
      $form['sandbox_trial'] = [
        '#type' => 'fieldset',
      ];

      $form['sandbox_trial']['title'] = [
        '#markup' => '<h4>' . $this->t('Sandbox Trial') . '</h4>',
      ];

      $form['sandbox_trial']['description'] = [
        '#markup' => '<p>' . $this->t('Start your free sandbox trial instantly on a ready-to-use Drupal site with full access to all module features.') . '</p>',
      ];

      $form['sandbox_trial']['video'] = [
        '#markup' => '<a class="button button--primary" target="_blank" href="https://playground.miniorange.com/drupal.php?mo_module=rest_api_authentication&drupal_version=10">'
          . $this->t('Start Sandbox Trial') . '</a>',
      ];

      // On-premise trial.
      $form['on_premise_trial'] = [
        '#type' => 'fieldset',
      ];
      $form['on_premise_trial']['title'] = [
        '#markup' => '<h4>' . $this->t('On-Premise Trial') . '</h4>',
      ];

      $form['on_premise_trial']['description'] = [
        '#markup' => '<p>' . $this->t('Request a trial license to install and test the module on your own Drupal site.') . '</p>',
      ];

      $form['on_premise_trial']['select'] = [
        '#type' => 'button',
        '#value' => $this->t('Request On-Premise Trial'),
        '#name' => 'select_on_premise',
        '#attributes' => [
          'class' => ['button', 'button--primary', 'use-ajax'],
        ],
        '#ajax' => [
          'callback' => [$this, 'selectTrialTypeAjax'],
          'wrapper' => 'modal_example_form',
        ],
      ];

      $form['support_markup'] = [
        '#markup' => $this->t(
          '<strong>Looking for something else?</strong> Need a live demo, assistance, or have a unique use case? Reach out to us at <a href="mailto:@email">@email</a>.',
          ['@email' => 'drupalsupport@xecurify.com']
        ),
      ];

      $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
      return $form;
    }

    // STEP 2: On-premise trial form.
    if ($trial_type === 'on_premise') {
      $form['rest_api_authentication_trial_email_address'] = [
        '#type' => 'email',
        '#title' => $this->t('Email'),
        '#required' => TRUE,
        '#attributes' => [
          'placeholder' => $this->t('Enter your email'),
        ],
      ];

      $form['rest_api_authentication_trial_description'] = [
        '#type' => 'textarea',
        '#title' => $this->t('Description'),
        '#rows' => 4,
        '#required' => TRUE,
        '#attributes' => [
          'placeholder' => $this->t('Describe your use case here'),
        ],
      ];

      $form['rest_api_authentication_trial_note'] = [
        '#markup' => $this->t(
          'If you need assistance, contact us at <a href="mailto:@email">@email</a>.',
          ['@email' => 'drupalsupport@xecurify.com']
        ),
      ];

      $form['submit_button'] = [
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#attributes' => [
          'class' => ['use-ajax', 'button--primary'],
        ],
        '#ajax' => [
          'callback' => [$this, 'submitModalFormAjax'],
        ],
      ];
    }

    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    return $form;
  }

  /**
   * AJAX callback for selecting trial type.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The AJAX response.
   */
  public function selectTrialTypeAjax(array $form, FormStateInterface $form_state): AjaxResponse {
    $triggering_element = $form_state->getTriggeringElement();
    $response = new AjaxResponse();

    // Determine which trial type was selected.
    if (isset($triggering_element['#name']) && $triggering_element['#name'] === 'select_on_premise') {
      $form_state->set('trial_type', 'on_premise');
      $form_state->setRebuild(TRUE);
      $form = $this->formBuilder->rebuildForm($this->getFormId(), $form_state, $form);
      $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
    }

    return $response;
  }

  /**
   * Process the 'modal_example_form' Form.
   *
   * @param array $form
   *   Form element of the 'modal_example_form'.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   Object of AjaxResponse.
   */
  public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $response = new AjaxResponse();
    $email = $form_values['rest_api_authentication_trial_email_address'];
    // If there are any form errors, AJAX replace the form.
    if ($form_state->hasAnyErrors()) {
      $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
    }
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $this->messenger->addMessage($this->t('The email address <b><em>%email</em></b> is not valid.', ['%email' => $email]), 'error');
      $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
    }
    else {
      $query = $form_values['rest_api_authentication_trial_description'];
      $query_type = 'trial';

      $support = new MiniorangeApiAuthSupport($email, '', $query, $query_type);
      $support_response = $support->sendSupportQuery();
      $support_response = json_decode($support_response, TRUE);

      if ($support_response['status'] == 'SUCCESS') {
        $message = [
          '#type' => 'item',
          '#markup' => $this->t('Your request for a trial module was sent successfully. Please allow us some time, and we will send you the trial module as soon as possible.<br> You can also reach out to us at <a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a>'),
        ];
        $ajax_form = new OpenModalDialogCommand('Thank you!', $message, ['width' => '50%']);
      }
      elseif ($support_response['status'] == 'ERROR') {
        $error = [
          '#type' => 'item',
          '#markup' => $this->t('The email address entered %email, possibly invalid.
          We discourage the use of disposable emails, please try again with a valid email.
          You can also reach out to us at <a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a>.',

            ['%email' => $email]
          ),
        ];
        $ajax_form = new OpenModalDialogCommand('Error!', $error, ['width' => '50%']);
      }
      else {
        $error = [
          '#type' => 'item',
          '#markup' => $this->t('Error submitting the support query. Please send us your query at
      <a href="mailto:drupalsupport@xecurify.com">
      drupalsupport@xecurify.com</a>.'),
        ];
        $ajax_form = new OpenModalDialogCommand('Error!', $error, ['width' => '50%']);
      }

      $response->addCommand($ajax_form);
    }

    return $response;
  }

  /**
   * {@inheritDoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {}

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {}

}
