<?php

namespace Drupal\azure_ad\Form;

use Drupal\azure_ad\Helper\moAzureADHelper;
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('azure_ad.settings');
    $this->configFactory = $config_factory->getEditable('azure_ad.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 'azure_ad_advance_settings';
  }

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

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

    $form['mo_azure_ad_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_azure_ad_import_export_configurations']['azure_ad_imo_option_exists_export'] = [
      '#type' => 'submit',
      '#value' => $this->t('Export'),
      '#button_type' => 'primary',
      '#submit' => ['::miniorangeExportConfig'],
    ];

    $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_ad_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_azure_ad_import_export_configurations']['azure_ad_idp_import'] = [
      '#type' => 'submit',
      '#value' => $this->t('Import'),
      '#disabled' => TRUE,
    ];

    $azure_ad_helper = new moAzureADHelper();
    $azure_ad_helper->moAzureShowCustomerSupportIcon($form, $form_state);

    return $form;
  }

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

    $configuration_array["Version_dependencies"] = self::miniorangeGetVersionInformations();
    header("Content-Disposition: attachment; filename = azure_ad_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="azure_ad_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) {}

}
