<?php

namespace Drupal\miniorange_saml\Form;

use Drupal\Core\Form\FormBase;
use Drupal\miniorange_saml\Utilities;
use Drupal\Core\Form\FormStateInterface;
use Drupal\miniorange_saml\MiniorangeSamlConstant;

/**
 * Class to handle the advanced settings form for the miniorange_saml module.
 */
class MiniorangeAdvanceSettings extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'miniorange_saml_export';
  }

  /**
   * Builds the form for the advanced settings of the module.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $base_url = \Drupal::request()->getSchemeAndHttpHost() . \Drupal::request()->getBaseUrl();

    \Drupal::configFactory()->getEditable('miniorange_saml.settings')->set('miniorange_saml_last_tab_visited', 'ADVANCE SETTINGS')->save();

    $form['miniorange_saml_markup_library'] = [
      '#attached' => [
        'library' => [
          'miniorange_saml/miniorange_saml.admin',
          'core/drupal.dialog.ajax',
        ],
      ],
    ];
    $form['markup_top_1'] = [
      '#markup' => t('<div class="mo_saml_sp_main_container"><div class="mo_saml_sp_container">
                    <div class="mo_saml_font_for_heading">Advance Settings</div><p style="clear: both"></p><hr/>'),
    ];

    /* Create container to hold @moSAMLAdvanseSettings form elements. */
    $form['mo_saml_import_export_configurations'] = [
      '#type' => 'details',
      '#title' => t('Import/Export configurations'),
      '#open' => TRUE,
      '#attributes' => ['style' => 'padding:0% 2%; margin-bottom:2%'],
    ];

    $form['mo_saml_import_export_configurations']['markup_prem_export_plan'] = [
      '#markup' => t('<div class="mo_saml_font_for_sub_heading">Export Configuration</div><hr><br>'),
    ];

    $loginUrl = \Drupal::config('miniorange_saml.settings')->get('miniorange_saml_idp_login_url');
    $acsUrl = \Drupal::config('miniorange_saml.settings')->get('miniorange_saml_idp_issuer');
    $disableButton = FALSE;
    if ($loginUrl == NULL || $acsUrl == NULL) {
      $disableButton = TRUE;
      $form['mo_saml_import_export_configurations']['markup_note'] = [
        '#markup' => t('<div class="mo_saml_configure_message">Please <a href="@base_url">configure module</a> first to download configuration file.</div>', ['@base_url' => $base_url . '/admin/config/people/miniorange_saml/sp_setup']),
      ];
    }
    $form['mo_saml_import_export_configurations']['miniorange_saml_imo_option_exists_export'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => t('Download Module Configuration'),
      '#submit' => ['::miniorangeImportExport'],
      '#disabled' => $disableButton,
    ];

    $form['mo_saml_import_export_configurations']['markup_prem_plan'] = [
      '#markup' => t('<br><br><div class="mo_saml_font_for_sub_heading">Import Configuration <a href="@base_url">[Standard, Premium and Enterprise]</a></div><hr>', ['@base_url' => $base_url . MiniorangeSamlConstant::LICENSING_TAB_URL]),
    ];

    $form['mo_saml_import_export_configurations']['import_Config_file'] = [
      '#type' => 'file',
      '#disabled' => TRUE,
      '#prefix' => '<div class="container-inline">',
    ];
    $form['mo_saml_import_export_configurations']['miniorange_saml_idp_import'] = [
      '#type' => 'submit',
      '#value' => t('Upload'),
      '#disabled' => TRUE,
      '#suffix' => '</div></div>',
    ];

    Utilities::advertiseNetworkSecurity($form, $form_state, 'SCIM');

    return $form;
  }

  /**
   * Handles the import/export of configuration settings.
   */
  public function miniorangeImportExport() {
    $tab_class_name = [
      'Service_Provider_Metadata' => 'mo_options_enum_identity_provider',
      'Identity_Provider_Setup' => 'mo_options_enum_service_provider',
    ];

    $configuration_array = [];
    foreach ($tab_class_name as $key => $value) {
      $configuration_array[$key] = self::miniorangeGetConfigurationArray($value);
    }

    $configuration_array["Version_dependencies"] = self::miniorangeGetVersionInformations();
    header("Content-Disposition: attachment; filename = miniorange_saml_config.json");
    echo(json_encode($configuration_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    exit;
  }

  /**
   * Retrieves the configuration array for a given class name.
   *
   * @param string $class_name
   *   The class name whose configuration settings need to be retrieved.
   *
   * @return array
   *   The configuration array for the given class.
   */
  public function miniorangeGetConfigurationArray($class_name) {
    $class_object = Utilities::getVariableArray($class_name);
    $mo_array = [];
    foreach ($class_object as $key => $value) {
      $mo_option_exists = \Drupal::config('miniorange_saml.settings')->get($value);
      if ($mo_option_exists) {
        $mo_array[$key] = $mo_option_exists;
      }
    }
    return $mo_array;
  }

  /**
   * Retrieves version information about the environment.
   *
   * @return array
   *   An array containing version information about PHP, Drupal,
   *   and various extensions.
   */
  public function miniorangeGetVersionInformations() {
    $array_version = [];
    $array_version["PHP_version"] = phpversion();
    $array_version["Drupal_version"] = Utilities::miniorangeGetDrupalCoreVersion();
    $array_version["OPEN_SSL"] = self::miniorangeSamlIsOpensslInstalled();
    $array_version["CURL"] = self::miniorangeSamlIsCurlInstalled();
    $array_version["ICONV"] = self::miniorangeSamlIsIconvInstalled();
    $array_version["DOM"] = self::miniorangeSamlIsDomInstalled();
    return $array_version;
  }

  /**
   * Checks if the OpenSSL is installed.
   *
   * @return int
   *   1 if OpenSSL is installed, 0 otherwise.
   */
  public function miniorangeSamlIsOpensslInstalled() {
    if (in_array('openssl', get_loaded_extensions())) {
      return 1;
    }
    return 0;
  }

  /**
   * Checks if the cUrl is installed.
   *
   * @return int
   *   1 if cUrl is installed, 0 otherwise.
   */
  public function miniorangeSamlIsCurlInstalled() {
    if (in_array('curl', get_loaded_extensions())) {
      return 1;
    }
    return 0;
  }

  /**
   * Checks if the iconv is installed.
   *
   * @return int
   *   1 if iconv is installed, 0 otherwise.
   */
  public function miniorangeSamlIsIconvInstalled() {
    if (in_array('iconv', get_loaded_extensions())) {
      return 1;
    }
    return 0;
  }

  /**
   * Checks if the dom is installed.
   *
   * @return int
   *   1 if dom is installed, 0 otherwise.
   */
  public function miniorangeSamlIsDomInstalled() {
    if (in_array('dom', get_loaded_extensions())) {
      return 1;
    }
    return 0;
  }

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

  }

}
