<?php

namespace Drupal\keycloak_user_provisioning\Form;

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;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class for Import and Export configuration.
 */
class AdvanceSettings extends FormBase {
  /**
   * ImmutableConfig property.
   *
   * @var Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

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

  /**
   * Messenger property.
   *
   * @var object
   */
  protected $messenger;

  /**
   * Request stack service.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a new AdvanceSettings object.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    MessengerInterface $messenger,
    RequestStack $request_stack,
  ) {
    $this->config = $config_factory->get('keycloak_user_provisioning.settings');
    $this->configFactory = $config_factory->getEditable('keycloak_user_provisioning.settings');
    $this->messenger = $messenger;
    $this->requestStack = $request_stack;
  }

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

  /**
   * FormID of the form.
   *
   * @return string
   *   Returns formID of the form.
   */
  public function getFormId() {
    return 'keycloak_user_provisioning_advance_settings';
  }

  /**
   * Build Import and Export configuration form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['markup_first'] = [
      '#attached' => [
        'library' => [
          'keycloak_user_provisioning/keycloak_user_provisioning.admin',
          'core/drupal.dialog.ajax',
        ],
      ],
    ];

    $form['mo_keycloak_user_provisioning_import_export_configurations'] = [
      '#type' => 'details',
      '#title' => $this->t('Import/Export configurations'),
      '#open' => TRUE,
    ];

    $form['mo_keycloak_user_provisioning_import_export_configurations']['markup_top'] = [
      '#type' => 'html_tag',
      '#tag' => 'p',
      '#value' => $this->t('Export and download the full configuration of the module as a json file.'),
    ];

    $form['mo_keycloak_user_provisioning_import_export_configurations']['keycloak_user_provisioning_imo_option_exists_export'] = [
      '#type' => 'submit',
      '#value' => $this->t('Export'),
      '#button_type' => 'primary',
      '#submit' => ['::miniorangeExportConfig'],
    ];

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

    $form['mo_keycloak_user_provisioning_import_export_configurations']['import_Config_file'] = [
      '#type' => 'file',
      '#title' => $this->t('Import module configuration') . ' ' . $mo_premium_tag,
      '#description' => $this->t('Select the json file which contains the module configuration.'),
      '#disabled' => TRUE,
      '#attributes' => ['accept' => 'application/json'],
    ];

    $form['mo_keycloak_user_provisioning_import_export_configurations']['keycloak_user_provisioning_idp_import'] = [
      '#type' => 'submit',
      '#value' => $this->t('Import'),
      '#disabled' => TRUE,
    ];

    return $form;
  }

  /**
   * Handles the export of configuration settings.
   */
  public function miniorangeExportConfig(array &$form, FormStateInterface $form_state) {
    $configuration_array = [];
    $configuration_array["keycloak_user_provisioning_settings"] = $this->config->getRawData();
    if (isset($configuration_array['keycloak_user_provisioning_settings']['_core'])) {
      unset($configuration_array['keycloak_user_provisioning_settings']['_core']);
    }

    $configuration_array["Version_dependencies"] = self::miniorangeGetVersionInformations();
    header("Content-Disposition: attachment; filename = keycloak_user_provisioning_config.json");
    $json_data = json_encode($configuration_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    $response = new Response($json_data);
    $response->headers->set('Content-Type', 'application/json');
    $response->headers->set('Content-Disposition', 'attachment; filename="keycloak_user_provisioning_config.json"');
    $form_state->setResponse($response);
  }

  /**
   * Retrieves version information about the environment.
   *
   * @return array
   *   An array containing version information about PHP, Drupal,
   *   and various extensions.
   */
  public function miniorangeGetVersionInformations() {
    return [
      'PHP_version' => phpversion(),
      'Drupal_version' => \Drupal::VERSION,
      'OPEN_SSL' => (int) extension_loaded('openssl'),
      'CURL' => (int) extension_loaded('curl'),
      'ICONV' => (int) extension_loaded('iconv'),
      'DOM' => (int) extension_loaded('dom'),
    ];
  }

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

}
