<?php

namespace Drupal\miniorange_saml\Form;

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

/**
 * Form for configuring the Identity Provider (IdP) setup for SAML.
 */
class MiniorangeSamlIdpSetup extends FormBase {

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

  /**
   * Builds the IdP setup form.
   *
   * @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) {

    $module_path = \Drupal::service('extension.list.module')->getPath('miniorange_saml');

    \Drupal::configFactory()->getEditable('miniorange_saml.settings')->set('miniorange_saml_last_tab_visited', 'SERVICE PROVIDER METADATA')->save();

    $base_url = Utilities::getBaseUrl();
    $acs_url = $base_url . '/samlassertion';

    $form['miniorange_saml_copy_button'] = [
      '#attached' => [
        'library' => [
          'miniorange_saml/miniorange_saml_copy.icon',
          'miniorange_saml/miniorange_saml.admin',
          'core/drupal.dialog.ajax',
        ],
      ],
    ];

    /* Create container to hold @ServiceProviderMetadata form elements. */
    $form['mo_saml_metadata_option'] = [
      '#markup' => t('<div class="mo_saml_font_for_heading">Service Provider Metadata</div>&nbsp;&nbsp;
                            <a class="button button--small" target="_blank" href="https://faq.miniorange.com/kb/drupal/saml-drupal/">FAQs</a>
                            <a class="button button--small" target="_blank" href="https://www.drupal.org/docs/contributed-modules/saml-sp-single-sign-on-sso-saml-service-provider-by-miniorange">Setup Guides</a><p style="clear: both"></p><hr>'),
    ];

    $form['markup_idp_sp_2'] = [
      '#markup' => t('<br><div class="mo_saml_font_SP_setup_for_heading"><strong>Provide following Service Provider\'s metadata to the Identity Provider.</strong></div>
                          <br><div>
                          <div class="container-inline"><b>a) Metadata URL:</b>
                            <div id="idp_metadata_url">
                               <code><b>
                                    <span>
                                        <a target="_blank" href="' . $base_url . '/saml_metadata">' . $base_url . '/saml_metadata' . '</a>&nbsp;
                                    </span></b>
                                </code></div>
                              <span class ="mo_copy button button--small">&#128461; Copy</span><span><a class="button button--small button--primary" href="' . $base_url . '/saml_metadata?download=true">Download XML Metadata</a></span></div>
                        </div>'),
    ];

    $form['mo_table_info'] = [
      '#markup' => '<div><br><b>b) Metadata details: </b></div>',
    ];

    $copyImage = '<span class ="fa-pull-right mo_copy mo_copy button button--small">&#128461; Copy</span>';

    $spEntity = [
      'data' => Markup::create('<span id="issuer_id">' . Utilities::getIssuer() . '</span>' . $copyImage),
    ];
    $spAcs = [
      'data' => Markup::create('<span id="login_url">' . $acs_url . '</span>' . $copyImage),
    ];
    $audience = [
      'data' => Markup::create('<span id="audience_url">' . Utilities::getIssuer() . '</span>' . $copyImage),
    ];
    $x509Certificate = [
      'data' => Markup::create('Available in <b><a href="' . $base_url . MiniorangeSamlConstant::LICENSING_TAB_URL . '">[Standard, Premium and Enterprise]</a></b> version.'),
    ];
    $customX509Certificate = [
      'data' => Markup::create('Click <a class="use-ajax"  data-dialog-type = "modal"  data-ajax-progress="fullscreen" data-dialog-options="{&quot;width&quot;:&quot;80%&quot;}"  href="' . $base_url . '/admin/config/people/miniorange_saml/generate_certificate">here</a> to generate custom certificate'),
    ];
    $recipient = [
      'data' => Markup::create('<span id="recipientURL">' . $acs_url . '</span>' . $copyImage),
    ];
    $destination = [
      'data' => Markup::create('<span id="destinationURL">' . $acs_url . '</span>' . $copyImage),
    ];
    $singleLogoutUrl = [
      'data' => Markup::create('Available in <b><a href="' . $base_url . MiniorangeSamlConstant::LICENSING_TAB_URL . '">[Premium and Enterprise]</a></b> version.'),
    ];
    $nameIdFormat = [
      'data' => Markup::create('<span id="nameID">' . "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" . '</span>' . $copyImage),
    ];

    $mo_table_content = [
          ['SP Entity ID/Issuer', $spEntity],
          ['SP ACS URL', $spAcs],
          ['Audience URI', $audience],
          ['X.509 Certificate', $x509Certificate],
          ['Custom X.509 Certificate', $customX509Certificate],
          ['Recipient URL', $recipient],
          ['Destination URL', $destination],
          ['Single Logout URL', $singleLogoutUrl],
          ['NameID Format', $nameIdFormat],
    ];

    $form['mo_saml_attrs_list_idp'] = [
      '#type' => 'table',
      '#header' => ['ATTRIBUTE', 'VALUE'],
      '#rows' => $mo_table_content,
      '#id' => 'metadata-table',
      '#empty' => t('Something went wrong. Please run the update script or contact us at <a href="' . MiniorangeSamlConstant::SUPPORT_EMAIL . '">' . MiniorangeSamlConstant::SUPPORT_EMAIL . '</a>'),
      '#responsive' => TRUE,
      '#sticky' => TRUE,
      '#size' => 2,
    ];

    $form['miniorange_saml_update_url_note'] = [
      '#markup' => t('<div class="mo_saml_highlight_background_note_1"><strong>Note: </strong>Updating the following fields will automatically update the SP metadata. Please ensure the IdP is configured with the <strong>latest metadata</strong> for seamless integration.</div>'),
    ];

    $form['miniorange_saml_base_url'] = [
      '#type' => 'textfield',
      '#title' => t('SP Base URL:'),
      '#default_value' => Utilities::getBaseUrl(),
      '#attributes' => ['style' => 'width:70%'],
    ];

    $form['miniorange_saml_entity_id'] = [
      '#type' => 'textfield',
      '#title' => t('SP Entity ID/Issuer:'),
      '#default_value' => Utilities::getIssuer(),
      '#attributes' => ['style' => 'width:70%'],
    ];

    $form['miniorange_saml_idp_config_submit'] = [
      '#type' => 'submit',
      '#value' => t('Update'),
      '#button_type' => 'primary',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $b_url       = $form_values['miniorange_saml_base_url'];
    $issuer_id   = $form_values['miniorange_saml_entity_id'];
    \Drupal::configFactory()->getEditable('miniorange_saml.settings')->set('miniorange_saml_base_url', $b_url)->save();
    \Drupal::configFactory()->getEditable('miniorange_saml.settings')->set('miniorange_saml_entity_id', $issuer_id)->save();
    \Drupal::messenger()->addStatus(t('Base URL and/or Issuer updated successfully.'));
  }

}
