{# **
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 * #}
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% import '@PrestaShop/Admin/macros.html.twig' as ps %}
{% trans_default_domain "Modules.resursbank.merchantapi.Config" %}
{% form_theme form '@PrestaShop/Admin/TwigTemplateForm/prestashop_ui_kit.html.twig' %}

{% block content %}
  {{ form_start(form, {'attr' : {'class': 'form'} }) }}
  <div class="row justify-content-center">
    {% block resursbank_merchantapi_api_config %}
      <div class="col-xl-10">
        <div class="card">
          <h3 class="card-header d-flex align-items-center">
                        <span class="flex-grow-1" style="text-align:left;">
                            <i class="material-icons">api</i> API
                        </span>
            <button class="btn btn-primary">{{ 'Save'|trans({}, 'Admin.Actions') }}</button>
          </h3>
          <div class="card-body">
            <div class="form-wrapper">
              <div class="card-text">
                {{ form_row(form.api.environment) }}

                <div class="form-group row">
                  <label class="form-control-label"></label>
                  <div class="col-sm" style="font-weight: bold;">
                    {{ 'credentials-test'|ecom_trans }}
                  </div>
                </div>

                <div class="form-group row">
                  <label class="form-control-label">{{ 'client-id'|ecom_trans }}</label>
                  <div class="col-sm">
                    {{ form_widget(form.api.client_id_test) }}
                  </div>
                </div>

                <div class="form-group row">
                  <label class="form-control-label">{{ 'client-secret'|ecom_trans }}</label>
                  <div class="col-sm">
                    {{ form_widget(form.api.client_secret_test, {'attr': {'data-has-secret': hasSecretTest ? '1' : '0'}}) }}
                  </div>
                </div>

                <div class="form-group row">
                  <label class="form-control-label"></label>
                  <div class="col-sm" style="font-weight: bold;">
                    {{ 'credentials-prod'|ecom_trans }}
                  </div>
                </div>

                <div class="form-group row">
                  <label class="form-control-label">{{ 'client-id'|ecom_trans }}</label>
                  <div class="col-sm">
                    {{ form_widget(form.api.client_id_prod) }}
                  </div>
                </div>

                <div class="form-group row">
                  <label class="form-control-label">{{ 'client-secret'|ecom_trans }}</label>
                  <div class="col-sm">
                    {{ form_widget(form.api.client_secret_prod, {'attr': {'data-has-secret': hasSecretProd ? '1' : '0'}}) }}
                  </div>
                </div>

                <hr>

                {{ form_row(form.api.store_id) }}

                <div class="form-group row">
                  <label class="form-control-label"></label>
                  <div class="col-sm" style="font-weight: bold;">
                    {{ form_row(form.api.fetch_stores) }}
                  </div>
                </div>

                {{ form_row(form.api.aftershop_enabled) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    {% endblock %}

    <!-- Payment method listing -->
    <div class="col-xl-10">
      <div class="card">
        <h3 class="card-header">
          <i class="material-icons">payment</i> {{ 'payment-methods'|ecom_trans }}
        </h3>
        <div class="card-body">
          <div class="card-text">
            {% if paymentMethodsWidget is null %}
              {{ 'no-payment-methods'|ecom_trans }}
            {% else %}
              {{ paymentMethodsWidget.content|raw }}
            {% endif %}
          </div>
        </div>
      </div>
    </div>

    <!-- Callbacks -->
    {% block resursbank_merchantapi_callbacks %}
      <div class="col-xl-10">
        <div class="card">
          <h3 class="card-header d-flex align-items-center">
                          <span class="flex-grow-1" style="text-align:left;">
                              <i class="material-icons">tune</i> {{ 'callback-settings'|ecom_trans }}
                          </span>
            <button class="btn btn-primary">{{ 'Save'|trans({}, 'Admin.Actions') }}</button>
          </h3>

          <div class="card-body">
            <div class="form-wrapper">
              <!-- Callback TTL value. -->
              {{ form_row(form.callbacks.ttl) }}

              <!-- Separation line. -->
              <div style="border-bottom:1px dashed #888; height:1px; width: 100%; margin: 5px 0 20px 0;"></div>

              <!-- Test callbacks -->
              <div style="text-align:left;">
                {{ form_row(form.callbacks.callback_test) }}
              </div>

              <!-- Callback test results -->
              <div class="card-text">
                <span style="font-weight:bold;">{{ 'test-last-triggered-at'|ecom_trans }}:&nbsp;</span>
                {{ callbackTestTriggered|raw }}
              </div>
              <div class="card-text">
                <span style="font-weight:bold;">{{ 'test-last-received-at'|ecom_trans }}:&nbsp;</span>
                {{ callbackTestReceived|raw }}
              </div>

              <!-- Callback URL info -->
              <div class="card-text">
                                <span class="font-weight-bold">
                                {{ 'callbacks'|ecom_trans }}
                                </span><br/>

                {% if callbackWidget is null %}
                  {{ 'no-callback-widget'|ecom_trans }}
                {% else %}
                  {{ callbackWidget.content|raw }}
                {% endif %}
              </div>
            </div>
          </div>
        </div>
      </div>
    {% endblock %}

    <!-- Part payment -->
    {% block resursbank_merchantapi_partpayment_config %}
      <div class="col-xl-10">
        <div class="card">
          <h3 class="card-header d-flex align-items-center">
                  <span class="flex-grow-1" style="text-align:left;">
                      <i class="material-icons">build</i>{{ 'part-payment-widget'|ecom_trans }}
                  </span>
            <button class="btn btn-primary">{{ 'Save'|trans({}, 'Admin.Actions') }}</button>
          </h3>
          <div class="card-body">
            <div class="form-wrapper">
              {{ form_row(form.partpayment.enabled) }}
              {{ form_row(form.partpayment.payment_method) }}
              {{ form_row(form.partpayment.annuity_period) }}
              {{ form_row(form.partpayment.threshold) }}
            </div>
          </div>
        </div>
      </div>
    {% endblock %}

    <!-- Advanced -->
    {% block resursbank_merchantapi_advanced_config %}
      <div class="col-xl-10">
        <div class="card">
          <h3 class="card-header d-flex align-items-center">
                        <span class="flex-grow-1" style="text-align:left;">
                            <i class="material-icons">build</i> {{ 'Advanced Settings'|trans }}
                        </span>
            <button class="btn btn-primary">{{ 'Save'|trans({}, 'Admin.Actions') }}</button>
          </h3>
          <div class="card-body">
            <div class="form-wrapper">
              {% block resursbank_merchantapi_advanced_config_form %}
                {{ form_widget(form.advanced) }}
              {% endblock %}
            </div>
          </div>
        </div>
      </div>
    {% endblock %}

    <!-- Support info -->
    <div class="col-xl-10">
      <div class="card">
        <h3 class="card-header">
          <i class="material-icons">build</i> {{ 'support-info'|ecom_trans }}
        </h3>
        <div class="card-body">
          <div class="card-text">
            {% if supportInfoWidget is null %}
              {{ 'content-render-failed'|ecom_trans }}
            {% else %}
              <style>
                {{ supportInfoWidget.css|raw }}
              </style>
              <div class="rb-si">
                {{ supportInfoWidget.html|raw }}
              </div>
            {% endif %}
          </div>
        </div>
      </div>
    </div>
  </div>
{% endblock %}

{% block javascripts %}
  {{ parent() }}

  <!-- Callback integration. -->
  <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
      function ajax(
        params,
        responseCallback
      ) {
        fetch('{{ url('resursbank_admin_config_callback_test') }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(params)
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status} (please check log for more info)`);
            }
            return response.json();
          })
          .then(response => {
            if (response.error) {
              alert(response.error);
            }
            return response;
          })
          .then(response => responseCallback(response))
          .catch((e) => {
            alert(e.message);
          });
      }

      document.getElementById('form_callbacks_callback_test').addEventListener('click', function () {
        ajax({}, function (response) {
          alert(JSON.parse(response).message);
          location.reload();
        });
      });

      const envSelect = document.getElementById('form_api_environment');

      const testFields = [
        document.getElementById('form_api_client_id_test')?.closest('.form-group'),
        document.getElementById('form_api_client_secret_test')?.closest('.form-group')
      ];
      const prodFields = [
        document.getElementById('form_api_client_id_prod')?.closest('.form-group'),
        document.getElementById('form_api_client_secret_prod')?.closest('.form-group')
      ];

      const testHeader = Array.from(document.querySelectorAll('div.col-sm'))
        .find(el => el.textContent?.includes('(test)'))?.closest('.form-group');
      const prodHeader = Array.from(document.querySelectorAll('div.col-sm'))
        .find(el => el.textContent?.includes('(produktion)'))?.closest('.form-group');

      function toggleCredentials() {
        const env = envSelect?.value;
        if (!env) return;
        const showTest = env === 'test';

        testFields.forEach(el => el && (el.style.display = showTest ? '' : 'none'));
        prodFields.forEach(el => el && (el.style.display = showTest ? 'none' : ''));

        if (testHeader) testHeader.style.display = showTest ? '' : 'none';
        if (prodHeader) prodHeader.style.display = showTest ? 'none' : '';
      }

      if (envSelect) {
        envSelect.addEventListener('change', toggleCredentials);
        toggleCredentials();
      }

      ['test', 'prod'].forEach(env => {
        const input = document.getElementById(`form_api_client_secret_${env}`);
        if (!input) return;

        if (input.dataset.hasSecret === '1') {
          input.placeholder = '**********';
        }

        input.form.addEventListener('submit', function () {
          if (/^[\s\*]*$/.test(input.value)) {
            input.value = '';
          }
        });
      });

    });
  </script>

  <!-- Fetch stores integration. -->
  <script type="text/javascript">
    {{ getStoresWidget|raw }}

    document.addEventListener('DOMContentLoaded', function () {
      if (typeof Resursbank_FetchStores !== 'function') {
        return;
      }

      const fetcher = new Resursbank_FetchStores({
        /**
         * @todo Check if there is a prettier popup we can use.
         */
        errorHandler: function (message) {
          alert(message);

          if (fetcher.fetching) {
            fetcher.toggleFetch(false);
          }
        },

        /**
         * @todo Check if there is a prettier popup we can use.
         */
        onComplete: function () {
          alert("{{ 'please-select-store'|ecom_trans }}");
        },

        getClientIdElement: function () {
          let el = document.getElementById(
            'form_api_client_id_' +
            this.getSelectEnvironmentElement().value
          );

          if (el === null) {
            throw new Error("{{ 'get-stores-missing-client-id-input'|ecom_trans }}");
          }

          return el;
        },

        getClientSecretElement: function () {
          let el = document.getElementById(
            'form_api_client_secret_' +
            this.getSelectEnvironmentElement().value
          );

          if (el === null) {
            throw new Error("{{ 'get-stores-missing-client-secret-input'|ecom_trans }}");
          }

          return el;
        },

        getUrl: function () {
          return "{{ path('resursbank_admin_config_get_stores') }}";
        }
      });

      $('#resursbank_fetch_stores_btn').on('click', fetcher.fetchStores.bind(fetcher));

      fetcher.setupEventListeners();
    });
  </script>

  <!-- Part payment integration. -->
  <script type="text/javascript">
    {{ getPeriodsWidget|raw }}
  </script>
{% endblock %}
