<?php

namespace Drupal\user_provisioning\Form;

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\Url;
use Drupal\user_provisioning\moUserProvisioningSupport;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Customer request form for user provisioning.
 */
class MoUserProvisioningCustomerRequest extends FormBase {

  /**
   * The config object.
   *
   * @var ImmutableConfig
   *   The config object.
   */
  private ImmutableConfig $config;

  /**
   * This method is used to get the form id.
   */
  public function __construct(ConfigFactoryInterface $config_factory, RequestStack $request_stack,) {
    $this->config = $config_factory->get('user_provisioning.settings');
    $this->requestStack = $request_stack;
  }

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

  /**
   * {@inheritDoc}
   *
   * @return string
   *   The form id.
   */
  public function getFormId() {
    return 'mo_provisioning_request_customer_support';
  }

  /**
   * {@inheritDoc}
   */
  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,
    ];

    $user_email = $this->config->get('mo_user_provisioning_customer_email');
    $form['mo_user_provisioning_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_user_provisioning_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_user_provisioning_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;
  }

  /**
   * This method is used to submit the form.
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $form_state
   *   The form state.
   *
   * @return AjaxResponse
   *   The AJAX response.
   */
  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_support_form', $form));
    }
    else {
      $email = $form_values['mo_user_provisioning_customer_support_email_address'];

      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $this->messenger()->addError($this->t('The email address <b><i>@email</i></b> is not valid.', ['@email' => $email]));
        $response->addCommand(new ReplaceCommand('#modal_support_form', $form));
        return $response;
      }
      $support_for = $form_values['mo_user_provisioning_customer_support_method'];
      $query = $form_values['mo_user_provisioning_customer_support_query'];
      $query_type = 'Contact Support';

      $support = new moUserProvisioningSupport($email, $support_for, $query, $query_type);
      $support->sendSupportQuery();
      $referer = $this->requestStack->getCurrentRequest()->headers->get('referer');

      $redirect_to = !empty($referer) ? $referer : Url::fromRoute('user_provisioning.user_provisioning')->toString();
      $this->messenger()->addStatus($this->t('Support query successfully sent. We will get back to you shortly.'));
      $response->addCommand(new RedirectCommand($redirect_to));
    }
    return $response;
  }

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

}
