<?php

namespace Drupal\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;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Drupal\user_provisioning\moUserProvisioningUtilities;

/**
 * This form manages advanced settings for the user provisioning module.
 */
class MoAdvancedSettings extends FormBase {

  /**
   * The base URL.
   *
   * @var string
   *   The base URL.
   */
  private string $baseUrl;

  /**
   * The config object.
   *
   * @var ImmutableConfig
   *   The config object.
   */
  private ImmutableConfig $config;

  /**
   * Editable module config object.
   *
   * @var Config
   *   Editable config for user provisioning settings.
   */
  protected $configFactory;

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

  /**
   * This method is used to construct the form.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    MessengerInterface $messenger,
    RequestStack $request_stack,
  ) {
    $this->requestStack = $request_stack;
    $request = $this->requestStack->getCurrentRequest();
    $this->baseUrl = $request->getSchemeAndHttpHost() . $request->getBaseUrl();
    $this->config = $config_factory->get('user_provisioning.settings');
    $this->configFactory = $config_factory->getEditable('user_provisioning.settings');
    $this->messenger = $messenger;
  }

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

  /**
   * Gets the form ID.
   *
   * {@inheritDoc}
   *
   * @return string
   *   The form id.
   */
  public function getFormId(): string {
    return "mo_advanced_settings";
  }

  /**
   * {@inheritDoc}
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  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',
        ],
      ],
    ];

    $url = $this->baseUrl . moUserProvisioningConstants::UPGRADE_PLANS;

    $form['header_top_style1'] = [
      '#markup' => $this->t('<div class="mo_user_provisioning_tab_heading">ADVANCED SETTINGS<hr></div>'),
    ];

    /*
     * Build Form For Debug Logs
     */
    $form['mo_user_provision_logs'] = [
      '#type' => 'details',
      '#title' => $this->t('Debug Logs'),
    ];

    $form['mo_user_provision_logs']['mo_user_provisioning_enable_loggers'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable loggers'),
      '#default_value' => $this->config->get('mo_user_provisioning_enable_loggers'),
      '#description' => $this->t('Enabling this checkbox will add the module logs under the default Drupal logger. Please note that these are development logs and are not the same as the logs that you see under the <b>Audit and Logs</b> tab.<br>
                                          <br><b>If you are facing any issues in our module, please follow the below steps:</b>
                                          <ol>
                                              <li>Please check the Enable Loggers checkbox and click on the Save button below.</li>
                                              <li>Now test the flow in which you are facing any issues.</li>
                                              <li>You can view these logs from under the <b>Reports -> Recent Log Messages</b> section of your Drupal site.</li>
                                              <li>Please send us the screenshot of the logs at <a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a> so that we can debug and resolve the issue that you are facing.</li>
                                          </ol>
                                       '),
    ];

    $form['mo_user_provision_logs']['save_log_and_debug_config'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
      '#submit' => ['::saveLogAndDebugConfig'],
      '#suffix' => '<br><br>',
    ];
    /*
     * Import Export Users
     */
    $form['mo_user_provision_import_export_details'] = [
      '#type' => 'details',
      '#title' => $this->t('Import/Export Users'),
      '#open' => TRUE,
      '#attribute' => ['class' => ['mo_user_provisioning_details_css']],
    ];

    // Export users.
    $form['mo_user_provision_import_export_details']['markup_top'] = [
      '#markup' => '<br><strong>Export Users</strong><hr/>',
    ];

    $form['mo_user_provision_import_export_details']['markup_1'] = [
      '#markup' => '<div class="mo_user_provisioning_highlight_background_note"><p> This section will help you to export your users. Click on the below button to export users.</div><br>',
    ];

    $form['mo_user_provision_import_export_details']['export_button'] = [
      '#type' => 'link',
      '#title' => $this->t('Export'),
      '#suffix' => '<div>',
      '#url' => Url::fromRoute('user_provisioning.export'),
      '#attributes' => [
        'class' => ['button', 'button--primary', 'use-ajax'],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => json_encode(['width' => '65%']),
      ],
    ];

    // Import users.
    $form['mo_user_provision_import_export_details']['markup_import'] = [
      '#markup' => $this->t('<br/><br/><br/><strong>Import Users <a href=":url">[PREMIUM]</a></strong><hr/><p>The below section will help you to import users and their fields.</p><p>Choose <b>"json"</b> or <b>"csv"</b> exported user file and upload by clicking on the button given below.</p><br/>', [':url' => $url]),
    ];

    $form['mo_user_provision_import_export_details']['import_Config_file'] = [
      '#type' => 'file',
      '#title' => $this->t('Upload Exported User File'),
      '#disabled' => TRUE,
    ];

    $form['mo_user_provision_import_export_details']['import_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Import'),
      '#button_type' => 'primary',
      '#disabled' => TRUE,
      '#submit' => ['::userProvisioningImportUsers'],
      '#suffix' => '<br><br>',
    ];
    /*
     * Download module configuration
     */
    $form['mo_user_provision_download_module_configuration'] = [
      '#type' => 'details',
      '#title' => $this->t('Download Module Configuration'),
      '#open' => TRUE,
      '#attribute' => ['class' => ['mo_user_provisioning_details_css']],
    ];
    $form['mo_user_provision_download_module_configuration']['markup_download'] = [
      '#markup' => '<div class="mo_user_provisioning_highlight_background_note"><p> This section will help you to download the module configuration. Click on the below button to download the module configuration.</div><br>',
    ];

    $disabled = $this->config->get('mo_user_provisioning_scim_server_base_url') && $this->config->get('mo_user_provisioning_scim_server_bearer_token');

    $form['mo_user_provision_download_module_configuration']['download_button'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#name' => 'download_module_configuration',
      '#value' => $this->t('Export'),
      '#submit' => ['::downloadModuleConfiguration'],
      '#suffix' => '<br><br>',
      '#disabled' => !$disabled,
    ];

    // Import module configuration (premium).
    $form['mo_user_provision_download_module_configuration']['markup_import_configuration'] = [
      '#markup' => $this->t('<br/><strong>Import Module Configuration <a href=":url">[PREMIUM]</a></strong>', [':url' => $url]),
    ];

    $form['mo_user_provision_download_module_configuration']['import_module_configuration_file'] = [
      '#type' => 'file',
      '#description' => $this->t('Select the json file which contains module configuration.'),
      '#disabled' => TRUE,
    ];

    $form['mo_user_provision_download_module_configuration']['import_module_configuration_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Import'),
      '#button_type' => 'primary',
      '#name' => 'import_module_configuration',
      '#disabled' => TRUE,
      '#submit' => ['::importModuleConfiguration'],
      '#suffix' => '<br><br>',
    ];

    // Debugger section ends here.
    $form['mo_user_provisioning_div_close'] = [
      '#markup' => '<br><br></div></div>',
    ];

    moUserProvisioningUtilities::moProvShowCustomerSupportIcon($form, $form_state);
    return $form;
  }

  /**
   * {@inheritDoc}
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $form_state
   *   The form state.
   *
   * @return void
   *   The form submission.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // @todo Implement submitForm() method.
  }

  /**
   * This function read the given json or csv file.
   *
   * @return void
   */
  public function userProvisioningImportUsers() {
  }

  /**
   * Submit handler for importing module configuration (premium).
   *
   * @return void
   */
  public function importModuleConfiguration() {
  }

  /**
   * Submit handler for logging and debugging.
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $formState
   *   The form state.
   *
   * @return void
   *   The form submission.
   */
  public function saveLogAndDebugConfig(array &$form, FormStateInterface $formState): void {
    $this->configFactory
      ->set('mo_user_provisioning_enable_loggers', $formState->getValue('mo_user_provisioning_enable_loggers'))
      ->save();
    $this->messenger->addMessage('Logging and Debugger configuration saved successfully.');
  }

  /**
   * Submit handler for downloading module configuration.
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $formState
   *   The form state.
   *
   * @return void
   *   The form submission.
   */
  public function downloadModuleConfiguration(array &$form, FormStateInterface $formState): void {
    $config_array = [];
    $config_array["user_provisioning_settings"] = $this->config->getRawData();
    if (isset($config_array['user_provisioning_settings']['_core'])) {
      unset($config_array['user_provisioning_settings']['_core']);
    }
    $config_array["Version_Information"] = self::miniorangeGetVersionInformations();
    $json_data = json_encode($config_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="user_provisioning_config.json"');
    $formState->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' => extension_loaded('openssl'),
      'CURL' => extension_loaded('curl'),
      'ICONV' => extension_loaded('iconv'),
      'DOM' => extension_loaded('dom'),
    ];
  }

}
