<?php

namespace Drupal\user_provisioning\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\user_provisioning\moUserProvisioningSupport;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Trial request form for user provisioning.
 */
class MoUserProvisioningRequestTrial extends FormBase {

  /**
   * ImmutableConfig property.
   *
   * @var Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * Config property.
   *
   * @var Drupal\Core\Config\Config
   */
  protected $configFactory;

  /**
   * Messenger property.
   *
   * @var object
   */
  protected $messenger;

  /**
   * The current user service.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Constructs the trial request form.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    MessengerInterface $messenger,
    AccountInterface $current_user,
  ) {
    $this->config = $config_factory->get('user_provisioning.settings');
    $this->configFactory = $config_factory->getEditable('user_provisioning.settings');
    $this->messenger = $messenger;
    $this->currentUser = $current_user;
  }

  /**
   * Creates the class instance.
   */
  public static function create(ContainerInterface $container): MoUserProvisioningRequestTrial|static {
    return new static(
      $container->get('config.factory'),
      $container->get('messenger'),
      $container->get('current_user'),
    );
  }

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

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
    $drupalVersion = \Drupal::VERSION;

    $form['#prefix'] = '<div id="modal_example_form">';
    $form['#suffix'] = '</div>';
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];

    $form['radio_option'] = [
      '#type' => 'radios',
      '#title' => $this->t('Which type of trial would you prefer?'),
      '#options' => [
        'option1' => $this->t('Sandbox'),
        'option2' => $this->t('On-Premise'),
      ],
      '#default_value' => ($form_state->getValue('radio_option')) ? $form_state->getValue('radio_option') : 'option1',
      '#attributes' => ['class' => ['container-inline']],
      '#ajax' => [
        'callback' => '::updateFormElements',
        'wrapper' => 'user-prov-additional-fields-wrapper',
      ],
    ];

    $form['user_prov_additional_fields_wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'user-prov-additional-fields-wrapper'],
    ];

    $form['mo_user_provisioning_trial_email_address'] = [
      '#type' => 'email',
      '#title' => $this->t('Email'),
      '#default_value' => $this->getEmail(),
      '#required' => TRUE,
      '#attributes' => ['placeholder' => $this->t('Enter your email'), 'style' => 'width:99%;margin-bottom:1%;'],
      '#states' => [
        'visible' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
        'required' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
      ],
    ];

    $form['mo_user_provisioning_trial_method'] = [
      '#type' => 'select',
      '#title' => $this->t('Trial Method'),
      '#attributes' => ['style' => 'width:99%;height:30px;margin-bottom:1%;'],
      '#options' => [
        "Drupal {$drupalVersion} SCIM Client" => $this->t('Drupal @version SCIM CLIENT - Sync information from Drupal', ['@version' => $drupalVersion]),
        "Drupal {$drupalVersion} SCIM SERVER" => $this->t('Drupal @version SCIM SERVER - Sync information into Drupal', ['@version' => $drupalVersion]),
        "Drupal {$drupalVersion} PROVIDER SPECIFIC PROVISIONING" => $this->t('Drupal @version Two-way sync between Drupal and provider', ['@version' => $drupalVersion]),
        'Not Sure' => $this->t('Not Sure (Want to schedule a meeting with Drupal developer for assistance.)'),
      ],
      '#states' => [
        'visible' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
        'required' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
      ],
      '#required' => TRUE,
    ];

    $form['mo_user_provisioning_trial_provider'] = [
      '#type' => 'textarea',
      '#rows' => 1,
      '#title' => $this->t('Provider/Application'),
      '#attributes' => [
        'placeholder' => $this->t('Enter provider name with which you want to sync.'),
        'style' => 'width:99%;',
      ],
      '#states' => [
        'visible' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
        'required' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
      ],
      '#required' => TRUE,
    ];

    $form['mo_user_provisioning_trial_description'] = [
      '#type' => 'textarea',
      '#rows' => 3,
      '#title' => $this->t('Description'),
      '#attributes' => [
        'placeholder' => $this->t('Describe your use case here!'),
        'style' => 'width:99%;',
        'maxlength' => 2000,
      ],
      '#states' => [
        'visible' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
        'required' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
      ],
      '#required' => TRUE,
      '#element_validate' => ['::validateTrialDescription'],
    ];

    $form['mo_user_prov_trial_submit_button_option1'] = [
      '#type' => 'submit',
      '#value' => $this->t('Go to Sandbox'),
      '#attributes' => [
        'class' => ['option1-submit', 'use-ajax', 'button--primary'],
        'formtarget' => '_blank',
      ],
      '#prefix' => '<div class="option1-submit-wrapper">',
      '#suffix' => '</div>',
      '#states' => [
        'visible' => [
          ':input[name="radio_option"]' => ['value' => 'option1'],
        ],
      ],
      '#submit' => ['::goToSandbox'],
      '#limit_validation_errors' => [],
    ];

    $form['mo_user_prov_trial_submit_button_option'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#attributes' => [
        'class' => [
          'use-ajax',
          'button--primary',
        ],
      ],
      '#prefix' => '<div class="other-options-submit-wrapper">',
      '#suffix' => '</div>',
      '#states' => [
        'visible' => [
          ':input[name="radio_option"]' => ['value' => 'option2'],
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

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

  /**
   * Updates form elements on trial option change.
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form wrapper with conditional fields.
   */
  public function updateFormElements(array &$form, FormStateInterface $form_state) {
    return $form['user_prov_additional_fields_wrapper'];
  }

  /**
   * Submits the trial request form using AJAX.
   */
  public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $response = new AjaxResponse();
    // If there are any form errors, AJAX replace the form.
    if ($form_state->hasAnyErrors()) {
      $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
    }
    else {

      $email = $form_values['mo_user_provisioning_trial_email_address'];
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $this->messenger->addMessage($this->t('The email address <b><i>@email</i></b> is not valid.', ['@email' => $email]), 'error');
        $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
        return $response;
      }
      $requested_trial_version = $form_values['mo_user_provisioning_trial_method'];
      $provider = $form_values['mo_user_provisioning_trial_provider'];
      $query = $requested_trial_version . ' : ' . trim($form_values['mo_user_provisioning_trial_description']);
      $query_type = 'Trial Request';

      $support = new moUserProvisioningSupport($email, '', $query, $query_type, $requested_trial_version, $provider);
      $support->sendSupportQuery();

      $this->messenger->addStatus($this->t('Success! Trial query successfully sent. We will provide you with the trial version shortly.'));
      $response->addCommand(new RedirectCommand(Url::fromRoute('user_provisioning.provisioning')->toString()));
    }
    return $response;
  }

  /**
   * Function to redirect user to Sandbox.
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $form_state
   *   The form state.
   *
   * @return void
   *   This method sets a redirect response.
   */
  public function goToSandbox(array $form, FormStateInterface $form_state) {
    $url = Url::fromUri('https://playground.miniorange.com/drupal.php', [
      'query' => [
        'email' => $this->getEmail(),
        'mo_module' => 'user_provisioning',
        'drupal_version' => '10',
      ],
    ])->toString();
    $response = new TrustedRedirectResponse($url);
    $form_state->setResponse($response);
  }

  /**
   * Function to fetch user email.
   *
   * @return array|mixed|string|null
   *   The preferred customer email address.
   */
  public function getEmail(): mixed {
    $user  = $this->currentUser->getEmail();
    $email = $this->config->get('mo_user_provisioning_customer_email');
    $email = !empty($email) ? $email : $user;
    $email = preg_match('/^(?!.*(?:noreply|no-reply)).*$/i', $email) ? $email : '';
    return $email;
  }

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

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

  /**
   * Validates and sanitizes trial description input.
   *
   * @param array $element
   *   The form element.
   * @param FormStateInterface $form_state
   *   The form state.
   * @param array $form
   *   The complete form array.
   */
  public function validateTrialDescription(array &$element, FormStateInterface $form_state, array &$form) {
    $value = $form_state->getValue('mo_user_provisioning_trial_description');

    $clean_value = strip_tags($value);

    if (strlen($clean_value) > 2000) {
      $form_state->setError(
            $element,
            $this->t('Description cannot exceed 20 characters.')
        );
    }
    $form_state->setValue('mo_user_provisioning_trial_description', $clean_value);
  }

}
