<?php

namespace Drupal\azure_ad\Form;

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

/**
 * Provides the customer support request form for Azure AD.
 */
class MoAzureCustomerRequest extends FormBase {

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

  /**
   * Constructor for MoAzureCustomerRequest.
   */
  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) {
    return new static(
          $container->get('config.factory'),
          $container->get('messenger')
      );
  }

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

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $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_customer_support_email_address'] = [
      '#type' => 'email',
      '#title' => $this->t('Email'),
      '#default_value' => $user_email,
      '#required' => TRUE,
      '#attributes' => ['placeholder' => $this->t('Enter valid email'), 'style' => 'width:99%;margin-bottom:1%;'],
    ];

    $form['mo_azure_ad_customer_support_method'] = [
      '#type' => 'select',
      '#title' => $this->t('What are you looking for'),
      '#attributes' => ['style' => 'width:99%;height:30px;margin-bottom:1%;'],
      '#options' => [
        'I need Technical Support' => $this->t('I need Technical Support'),
        'I want to Schedule a Setup Call/Demo' => $this->t('I want to Schedule a Setup Call/Demo'),
        'I have Sales enquiry' => $this->t('I have Sales enquiry'),
        'I have a custom requirement' => $this->t('I have a custom requirement'),
        'My reason is not listed here' => $this->t('My reason is not listed here'),
      ],
    ];

    $form['mo_azure_ad_customer_support_query'] = [
      '#type' => 'textarea',
      '#required' => TRUE,
      '#title' => $this->t('How can we help you?'),
      '#attributes' => ['placeholder' => $this->t('Describe your query here!'), 'style' => 'width:99%'],
    ];

    $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 customer support modal form.
   *
   * @param array $form
   *   The form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current 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();
    $response = new AjaxResponse();
    $email = $form_values['mo_azure_ad_customer_support_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 @email is not valid.', ['@email' => $email]), 'error');
      $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
    }
    else {
      $support_for = $form_values['mo_azure_ad_customer_support_method'];
      $query = $form_values['mo_azure_ad_customer_support_query'];
      $query_type = 'Contact Support';

      $support = new moAzureADSupport($email, $support_for, $query, $query_type);
      $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;
  }

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

}
