<?php

namespace Drupal\azure_ad\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
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\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\azure_ad\MoAzureUtilities;
use Drupal\user_provisioning\moUserProvisioningSupport;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides the customer support request form for Azure AD.
 */
class MoAzureRequestSupportForm extends FormBase {
  /**
   * Configuration object for user provisioning settings.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

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

  /**
   * Creates the class instance.
   */
  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_support';
  }

  /**
   * Builds the form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#prefix'] = '<div id="modal_support_form">';
    $form['#suffix'] = '</div>';
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];

    $form['markup_library'] = [
      '#attached' => [
        'library' => [
          "azure_ad/azure_ad.admin",
        ],
      ],
    ];

    $user_email = $this->config->get('mo_user_provisioning_customer_email');
    $phone = $this->config->get('mo_user_provisioning_customer_phone');

    $form['markup_1'] = [
      '#markup' => $this->t('<p class="mo_azure_background_note">Need any help? We can help you with configuring miniOrange Azure AD Sync module on your site. Just send us a query, and we will get back to you soon.</p>'),
    ];

    $form['mo_user_provisioning_support_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_user_provisioning_support_phone_number'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Phone'),
      '#default_value' => $phone,
      '#attributes' => [
        'placeholder' => $this->t('Enter number with country code Eg. +00xxxxxxxxxx'),
        'style' => 'width:99%;margin-bottom:1%;',
      ],
    ];
    $form['mo_user_provisioning_support_query'] = [
      '#type' => 'textarea',
      '#required' => TRUE,
      '#title' => $this->t('Query'),
      '#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 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();
    $response = new AjaxResponse();
    $email = $form_values['mo_user_provisioning_support_email_address'];
    // If there are any form errors, AJAX replace the form.
    if ($form_state->hasAnyErrors()) {
      $response->addCommand(new ReplaceCommand('#modal_support_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_support_form', $form));
    }
    else {
      $phone = $form_values['mo_user_provisioning_support_phone_number'];
      $query = $form_values['mo_user_provisioning_support_query'];
      $query_type = 'Support';
      $module_name = 'Azure AD Sync';
      $utilities = new MoAzureUtilities();
      $module_version = $utilities->getModuleVersion();

      $support = new moUserProvisioningSupport($email, $phone, $query, $query_type, NULL, $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) {}

}
