<?php

namespace Drupal\azure_ad\Form;

use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Url;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Drupal\azure_ad\MoAzureUtilities;
use Drupal\user_provisioning\moUserProvisioningSupport;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides the trial request form for Azure AD.
 */
class MoAzureRequestTrial extends FormBase {

  /**
   * Configuration object for user provisioning settings.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

  /**
   * Constructs a new MoAzureRequestTrial object.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
    $this->setConfigFactory($config_factory);
    $this->setMessenger($messenger);
    $this->config = $config_factory->get('user_provisioning.settings');
  }

  /**
   * {@inheritDoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('config.factory'),
      $container->get('messenger')
    );
  }

  /**
   * Returns the form ID.
   *
   * @return string
   *   The form ID.
   */
  public function getFormId() {
    return 'mo_azure_request_trial';
  }

  /**
   * Builds the form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param mixed $options
   *   (optional) Additional options passed to the form. Defaults to NULL.
   *
   * @return array
   *   The form array.
   */
  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,
    ];

    $user_email = $this->config->get('user_provisioning_customer_admin_email');

    $form['mo_azure_ad_trial_email_address'] = [
      '#type' => 'email',
      '#title' => $this->t('Email'),
      '#default_value' => $user_email,
      '#required' => TRUE,
      '#attributes' => ['placeholder' => $this->t('Enter your email'), 'style' => 'width:99%;margin-bottom:1%;'],
    ];

    $form['mo_azure_ad_trial_method'] = [
      '#type' => 'select',
      '#title' => $this->t('Trial Method'),
      '#attributes' => ['style' => 'width:99%;height:30px;margin-bottom:1%;'],
      '#options' => [
        'Drupal to Azure CRUD operations' => $this->t('Drupal to Azure Sync (Complete CRUD operations)'),
        'Azure to Drupal Sync' => $this->t('Azure to Drupal Sync (Complete CRUD operations)'),
        'Not Sure' => $this->t('Not Sure (We will assist you further)'),
      ],
    ];

    $form['mo_azure_ad_trial_description'] = [
      '#type' => 'textarea',
      '#rows' => 4,
      '#required' => TRUE,
      '#title' => $this->t('Description'),
      '#attributes' => ['placeholder' => $this->t('Describe your use case here!'), 'style' => 'width:99%;'],
    ];

    $form['mo_azure_ad_trial_note'] = [
      '#markup' => $this->t(
            '<div>If you are not sure what to choose, you can get in touch with us on <a href="mailto::email">@email</a> and we will assist you further.</div>',
            [
              ':email' => moUserProvisioningConstants::SUPPORT_EMAIL,
              '@email' => moUserProvisioningConstants::SUPPORT_EMAIL,
            ]
        ),
    ];

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

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

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

  /**
   * Handles AJAX submission for the trial request form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The AJAX response containing form replacement or redirect commands.
   */
  public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $email = $form_values['mo_azure_ad_trial_email_address'];

    $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));
    }
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $this->messenger->addError($this->t('The email address @email is not valid.', ['@email' => $email]));
      $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
    }
    else {
      $trial_method = $form_values['mo_azure_ad_trial_method'];
      $query = $form_values['mo_azure_ad_trial_description'];
      $query_type = 'Trial Request';
      $module_name = 'Azure AD Sync';
      $utilities = new MoAzureUtilities();
      $module_version = $utilities->getModuleVersion();
      $support = new moUserProvisioningSupport($email, NULL, $query, $query_type, $trial_method, '', $module_name, $module_version);
      $support->sendSupportQuery();

      $this->messenger->addStatus($this->t('Support query successfully sent. We will get back to you shortly.'));
      $response->addCommand(new RedirectCommand(Url::fromRoute('azure_ad.overview')->toString()));
    }
    return $response;
  }

  /**
   * Submits the form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {}

}
