<?php

namespace Drupal\user_provisioning\Form;

use Drupal\Core\Config\Config;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Drupal\user_provisioning\moUserProvisioningUtilities;

/**
 *
 */
class MoAdvancedSettings extends FormBase {
  private string $base_url;
  private ImmutableConfig $config;
  private Config $config_factory;


  /**
   *
   */
  public function __construct() {
    $this->base_url       = \Drupal::request()->getSchemeAndHttpHost() . \Drupal::request()->getBaseUrl();
    $this->config         = \Drupal::config('user_provisioning.settings');
    $this->config_factory = \Drupal::configFactory()->getEditable('user_provisioning.settings');
    $this->messenger      = \Drupal::messenger();
  }

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

  /**
   * {@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',
        ],
      ],
    ];

    $url = $this->base_url . moUserProvisioningConstants::UPGRADE_PLANS;
    $mo_premium_tag = '<a href= "' . $url . '" >[PREMIUM]</a>';

    $form['header_top_style1'] = [
      '#markup' => 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' => t('Save'),
      '#button_type' => 'primary',
      '#submit' => ['::saveLogAndDebugConfig'],
      '#suffix' => '<br><br>',
    ];
    /*
     * Import Export Users
     */
    $form['mo_user_provision_import_export_details'] = [
      '#type' => 'details',
      '#title' => 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' => 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 ' . $mo_premium_tag . '</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/>'),
    ];

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

    $form['mo_user_provision_import_export_details']['import_button'] = [
      '#type' => 'submit',
      '#value' => t('Import'),
      '#button_type' => 'primary',
      '#disabled' => TRUE,
      '#submit' => ['::userProvisioningImportUsers'],
      '#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}
   */
  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 logging and debugging.
   *
   * @param array $form
   * @param FormStateInterface $formState
   *
   * @return void
   */
  public function saveLogAndDebugConfig(array &$form, FormStateInterface $formState): void
  {
    $this->config_factory->set('mo_user_provisioning_enable_loggers', $formState->getValue('mo_user_provisioning_enable_loggers'))->save();
    $this->messenger->addMessage('Logging and Debugger configuration saved successfully.');
  }

}
