var environment = document.querySelector('#checkout-confirm [data-environment]').getAttribute('data-environment');

var dataEnvironment = '';
if (environment) {
  dataEnvironment = JSON.parse(environment);
}

var dataPaymentMethodId = document
  .querySelector('#checkout-confirm [data-payment-method-id]')
  .getAttribute('data-payment-method-id');

function initFingerPrint() {
  if (window.yapay.FingerPrint) {
    window.yapay.FingerPrint(dataEnvironment);
  } else {
    setTimeout(function() {
      initFingerPrint();
    }, 100);
  }
}

initFingerPrint();

$('#checkout-confirm').on('submit', function(e) {
  if (!$('#yapay-bank_transfer').prop('checked')) {
    return;
  }

  e.preventDefault();

  $('span.form-error').remove();

  var $form = $('#form-yapay'),
    $formerror = $form.find('span.form-error'),
    $this = $(this).find('.ftr-steps__button'),
    data = $form.serializeObject();

  if ($formerror.length > 0) {
    $(window).scrollTop(
      $($formerror[0])
        .parent('label')
        .offset().top
    );
    return false;
  }

  data['cidade'] = $form.find('#codigo_municipio').val();
  data['payment_method_id'] = dataPaymentMethodId;

  $.ajax({
    type: 'POST',
    url: 'index.php?route=payment/yapay/pay_bank_transfer',
    data: data,
    dataType: 'json',
    beforeSend: function() {
      $this.find('.ftr-steps__button').prop('disabled', true);
      $('.ftr-loading-bar').removeClass('ftr-none');
    },
    complete: function() {
      $('.ftr-loading-bar').addClass('ftr-none');
      $this.find('.ftr-steps__button').prop('disabled', false);
    },
    success: function(json) {
      if (json['error']) {
        $('.ftr-field').removeClass('error');
        $('.ftr-field__error').remove();

        $.each(json['error'], function(index, value) {
          $('input[name=' + index + ']')
            .closest('.ftr-field')
            .addClass('error');
          $('input[name=' + index + ']  + .ftr-field__text').after(
            '<span class="ftr-field__error">' + value + '</span>'
          );
          notificationMsg(value, 'error');
        });

        return;
      }

      if (json['redirect']) {
        location.href = json['redirect'];
      }
    },
    error: function(request, status, error) {
      console.log(request.responseText);
    },
  });
});
