<?php

namespace Drupal\azure_ad\Form;

use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Config\ConfigFactoryInterface;
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\Messenger\MessengerInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Automatic provisioning of users from Azure AD to Drupal.
 */
class MoAutomaticProvisioning extends FormBase {

  /**
   * Immutable Azure AD module configuration.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

  /**
   * Constructor for MoAutomaticProvisioning.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
    $this->setConfigFactory($config_factory);
    $this->setMessenger($messenger);
    $this->config = $config_factory->get('azure_ad.settings');
  }

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

  /**
   * Get the form ID.
   */
  public function getFormId() {
    return 'mo_azure_review_config';
  }

  /**
   * Build the form.
   */
  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['mo_azure_ad_to_drupal_library'] = [
      '#attached' => [
        'library' => [
          'azure_ad/azure_ad.admin',
        ],
      ],
    ];

    $form['azure_ad_to_drupal_header_style'] = [
      '#markup' => $this->t('<div class="mo_azure_header_container_step10">'),
    ];

    $form['mo_azure_user_operations'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Automatic Provisioning Configurations'),
    ];

    $form['mo_azure_user_operations']['read_user_azure_ad_manual'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Read user'),
      '#default_value' => 1,
      '#disabled' => TRUE,
    ];

    $form['mo_azure_user_operations']['create_user_azure_ad_manual'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Create user'),
      '#default_value' => $this->config->get('azure_ad_automatic_provisioning_checkbox'),
    ];

    $url = Url::fromRoute('azure_ad.azure_upgrade_plans')->toString();
    $mo_premium_tag = '<a href="' . $url . '" class="premium-badge">' . $this->t('PREMIUM') . '</a>';

    $form['mo_azure_user_operations']['update_user_azure_ad'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Update user') . $mo_premium_tag,
      '#disabled' => TRUE,
    ];

    $form['mo_azure_user_operations']['deactivate_user_azure_ad'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Deactivate user') . $mo_premium_tag,
      '#disabled' => TRUE,
    ];

    $form['mo_azure_user_operations']['delete_user_azure_ad'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Delete user') . $mo_premium_tag,
      '#disabled' => TRUE,
    ];

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

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

  /**
   * Submit the form.
   */
  public function submitModalFormAjax(array $form, FormStateInterface $form_state) {

    $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 {
      $form_values = $form_state->getValues();
      $auto_create_user = $form_values['create_user_azure_ad_manual'];

      $this->configFactory()->getEditable('azure_ad.settings')->set('azure_ad_automatic_provisioning_checkbox', $auto_create_user)->save();
      $this->messenger->addStatus($this->t('Configurations saved successfully.'));

      $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.
  }

}
