<?php

namespace Drupal\user_provisioning\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user_provisioning\moUserProvisioningUtilities;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * User export form for manual exports.
 */
class MoUserProvisioningUserExport extends FormBase {

  /**
   * Config property.
   *
   * @var Drupal\Core\Config\Config
   */
  protected $configFactory;

  /**
   * Constructs the user export form.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory->getEditable('user_provisioning.settings');
  }

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

  /**
   * {@inheritDoc}
   */
  public function getFormId(): string {
    return "mo_export";
  }

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form['mo_user_provision_add_css'] = [
      '#attached' => [
        'library' => [
          'user_provisioning/user_provisioning.admin',
          'core/drupal.dialog.ajax',
        ],
      ],
    ];

    $form['markup_top'] = [
      '#markup' => '<!--<br><br>--><div class="mo_user_provisioning_sp_font_for_sub_heading"><strong>Export Users</strong></div><hr/><p>
                                                Select the users attributes that you want to export.</p>',
    ];

    $form['message'] = [
      '#markup' => '<div id="tester"></div>',
    ];

    $user_attribute = moUserProvisioningUtilities::customUserFields();
    unset($user_attribute['']);
    $user_attribute = array_keys($user_attribute);

    $form['mo_user_provisioning_export_attribute'] = [
      '#type' => 'table',
      '#attributes' => ['style' => 'border-collapse: separate;', 'class' => ['export_user_table']],
    ];

    $count = 0;
    for ($i = 0; $i < (int) count($user_attribute) / 3; $i++) {
      if ($i * 3 + 1 <= count($user_attribute)) {
        $form['mo_user_provisioning_export_attribute'][$i][$user_attribute[$count]] = [
          '#type' => 'checkbox',
          '#disabled' => $user_attribute[$count] != 'name' && $user_attribute[$count] != 'mail',
          '#default_value' => $user_attribute[$count] == 'name' || $user_attribute[$count] == 'mail',
          '#title' => $user_attribute[$count++],
        ];
      }
      if ($i * 3 + 2 <= count($user_attribute)) {
        $form['mo_user_provisioning_export_attribute'][$i][$user_attribute[$count]] = [
          '#type' => 'checkbox',
          '#disabled' => $user_attribute[$count] != 'name' && $user_attribute[$count] != 'mail',
          '#default_value' => $user_attribute[$count] == 'name' || $user_attribute[$count] == 'mail',
          '#title' => $user_attribute[$count++],
        ];
      }
      if ($i * 3 + 3 <= count($user_attribute)) {
        $form['mo_user_provisioning_export_attribute'][$i][$user_attribute[$count]] = [
          '#type' => 'checkbox',
          '#disabled' => $user_attribute[$count] != 'name' && $user_attribute[$count] != 'mail',
          '#default_value' => $user_attribute[$count] == 'name' || $user_attribute[$count] == 'mail',
          '#title' => $user_attribute[$count++],
        ];
      }
    }

    $form['mo_user_provisioning_file_type_option'] = [
      '#type' => 'radios',
      '#title' => $this->t("Please select file extension you want to download"),
      '#attributes' => ["style" => "display:inline"],
      '#default_value' => 'json',
      '#options' => ['json' => $this->t('.json'), 'csv' => $this->t('.csv')],
    ];

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

    $form['mo_user_provisioning_div_close'] = [
      '#markup' => '<br><br></div>',
    ];

    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $command = new CloseModalDialogCommand();

    $file_extension = $form_state->getValue('mo_user_provisioning_file_type_option');

    $user_attribute = [];
    foreach ($form_state->getValues()['mo_user_provisioning_export_attribute'] as $key => $value) {
      foreach ($value as $field_name => $field_value) {
        if (($field_name == 'name' || $field_name == 'mail') && $field_value) {
          $user_attribute[$field_name] = $field_value;
        }
      }
    }

    if (empty($user_attribute)) {
      $response->addCommand(new ReplaceCommand('#tester', '<span style="color: red">Please select at least one attribute.</span>'));
      return $response;
    }

    $this->configFactory->set('mo_user_provisioning_export_config', $user_attribute)->save();
    $this->configFactory->set('mo_user_provisioning_file_extension', $file_extension)->save();

    $response->addCommand($command);
    $response->addCommand(new RedirectCommand(Url::fromRoute('user_provisioning.export_users',)->toString()));

    return $response;

  }

}
