amount_cents = 0;
jQuery(function ($) {


  $(".chama-form").validate();
  $(document.body).on('change paste keyup', '#chama_payment_amount', function (event) {
    var symbol = $(this).data("symbol");
    var type = $(this).data("type");
    amount = $(this).val();
    var currency_min = $(this).data("currency-min");
    var formatted_amount = symbol + amount;
    amount_cents = parseFloat(amount) * parseFloat(currency_min);
    //console.log(formatted_amount);
    //$(this).data('amount-cents',  amount_cents );
    $(this).attr('data-amount-cents', amount_cents);
    $('.chama-' + type + ' .chama-summary-amount').text(formatted_amount);
  });

  //initialize stripe elements
  const publishable_key = $('#chama_pub_key').val();
  const stripe = Stripe(publishable_key);


  amount_cents = $('#chama_payment_amount').data('amount-cents');
  var currency = $('#chama_payment_amount').data('currency').toLowerCase();
  var stripe_configuration_id = $('#chama_stripe_configuration_id').val();
  var stripe_customer_session_client_secret = $('#chama_stripe_customer_session_client_secret').val();
  if ($('#chama_stripe_customer_session_client_secret').val()) {
    stripe_customer_session_client_secret = $('#chama_stripe_customer_session_client_secret').val();
  }
  const options = {
    mode: 'payment',
    setup_future_usage: 'on_session',
    customerSessionClientSecret: stripe_customer_session_client_secret,
    payment_method_configuration: stripe_configuration_id,
    amount: amount_cents,
    currency: currency,
    loader: 'always',
    layout: {
      type: 'tabs',
      defaultCollapsed: false,
    },
    // Fully customizable with appearance API.
    appearance: {
      variables: {
        labels: 'floating',
        fontLineHeight: '1.4',
        fontSizeBase: '16px',
        colorText: '#000000',
        colorPrimary: '#3867d6',
        colorDanger: '#eb3b5a',
        focusBoxShadow: '0 0 0 1px #3867d6',
        borderRadius: '7px',
        borderColor: '#000000'
      },
      rules: {
        '.Input': {
          border: '1px solid #000000',
          boxShadow: 'none',
        }
      }
    },
  };

  // Set up Stripe.js and Elements to use in checkout form
  const elements = stripe.elements(options);
  // Create and mount the Payment Element
  const payment_element = elements.create('payment');
  payment_element.on('change', function (event) {
    //billingDataChange();
    if (event.error) {
      handle_error(event.error.message);
      return;
    } else {
      jQuery('#chama-payment-errors').removeClass('show');
    }
    if (event.complete) {
      // enable payment button
      payment_form.querySelector('.chama-pay-button').disabled = false;
      $('.chama-pay-button').removeClass('chama-disabled-button');
    }
  });
  if ($('#chama_commission_id').val() && $('#chama_commission_allowed_countries').val()) {
    allowed_countries = $('#chama_commission_allowed_countries').val();
    const allowed_countries_array = allowed_countries.split(',');
    const shipping_options = { mode: 'shipping', allowedCountries: allowed_countries_array };
    const address_element = elements.create('address', shipping_options);
    address_element.mount('#chama-shipping-element');
  }
  payment_element.mount('#chama-payment-element');

  const payment_form = document.querySelector('.chama-payment-form');

  payment_form.addEventListener('submit', async (e) => {
    //display loader
    $('.chama-loader-wrapper').css('display', 'flex');
    // Avoid a full page POST request.
    e.preventDefault();
    var base_rest_url = $('#chama_base_rest_url').val();
    var confirmation_url = $('#chama_confirmation_url').val();
    var email = $('#chama_email').val();
    var nonce = $('#_wpnonce').val();
    var description = $('#chama_description').val();
    var type = $('#chama_type').val();
    var full_name = null;
    var billing_details = null;
    var campaign_id = null;
    var commission_id = null;
    var captcha_response = null;
    var input_amount = $('#chama_payment_amount').val();

    const form_data = {
      '_wpnonce': nonce,
      'amount': input_amount,
      'type': type,
    };
    if ($('#chama_campaign_id').val()) {
      campaign_id = $('#chama_campaign_id').val();
      form_data.campaign_id = campaign_id;

    }
    if ($('#chama_commission_id').val()) {
      commission_id = $('#chama_commission_id').val();
      form_data.commission_id = commission_id;
    }
    // Disable the form from submitting twice.
    payment_form.querySelector('.chama-pay-button').disabled = true;
    $('.chama-pay-button').addClass('chama-disabled-button');

    // Trigger form validation and wallet collection
    const { error: submitError } = await elements.submit();
    if (submitError) {
      handle_error(submitError.message);
      $('.chama-loader-wrapper').css('display', 'none');
      return;
    }
    // server validation
    const { status, message } = await $.ajax({
      url: base_rest_url + "v1/stripe/validate",
      type: "POST",
      data: form_data,
      error: function (data) {
        var response = JSON.parse(data.responseText);

        $('#chama-payment-errors').html(response.message);
        $('#chama-payment-errors').addClass('show');
        // Re-enable the form so the customer can resubmit.
        payment_form.querySelector('.chama-pay-button').disabled = false;
        $('.chama-pay-button').removeClass('chama-disabled-button');
        $('.chama-loader-wrapper').css('display', 'none');
        return;
      }
    });

    if (status == 'passed') {
      //create payment intent

      if ($('#chama_first_name').val() && $('#chama_last_name').val()) {
        full_name = $('#chama_first_name').val() + ' ' + $('#chama_last_name').val();
        billing_details = {
          email: email,
          name: full_name,
        };
      }
      else {
        billing_details = {
          email: email
        }
      }
      var values = {
        '_wpnonce': nonce,
        'amount': amount_cents,
        'description': description,
        'email': email,
        'type': type,
        'name': full_name,
      };
      if ($('#chama-captcha-response').val()) {
        captcha_response = $('#chama-captcha-response').val();
        values.captcha_response = captcha_response;
      }
      if ($('#chama_campaign_id').val()) {
        campaign_id = $('#chama_campaign_id').val();
        values.campaign_id = campaign_id;

      }
      if ($('#chama_commission_id').val()) {
        commission_id = $('#chama_commission_id').val();
        values.commission_id = commission_id;
      }
      if ($('#chama_commission_request').val()) {
        commission_request = $('#chama_commission_request').val();
        values.commission_request = commission_request;
      }
      if ($('#chama_commission_price').val()) {
        commission_price = $('#chama_commission_price').val();
        values.commission_price = commission_price;
      }
      if ($('#chama_commission_shipping').val()) {
        commission_shipping = $('#chama_commission_shipping').val();
        values.commission_shipping = commission_shipping;
      }
      if ($('#chama_commission_addons').val()) {
        commission_addons = $('#chama_commission_addons').val();
        values.commission_addons = commission_addons;
      }
      const { clientSecret, receiptId } = await $.ajax({
        url: base_rest_url + "v1/stripe/payment",
        type: "POST",
        data: values,
        error: function (data) {
          $('#chama-payment-errors').html(data.responseText);
          $('#chama-payment-errors').addClass('show');
          $('.chama-loader-wrapper').css('display', 'none');
          return;
        }
      });
      if (receiptId) {
        confirmation_url = confirmation_url + '&receipt_id=' + receiptId;
      }
      if (clientSecret) {
        const { error } = await stripe.confirmPayment({
          elements,
          clientSecret,
          confirmParams: {
            return_url: confirmation_url,
            payment_method_data: {
              billing_details: billing_details
            }
          },
        });
        //error happened
        if (error) {
          handle_error(error.message);

          // Re-enable the form so the customer can resubmit.
          payment_form.querySelector('.chama-pay-button').disabled = false;
          $('.chama-pay-button').removeClass('chama-disabled-button');
          $('.chama-loader-wrapper').css('display', 'none');
          return;
        }
      }
    }






  });

});

function handle_error(message) {
  jQuery('#chama-payment-errors').html(message);
  jQuery('#chama-payment-errors').addClass('show');
  jQuery('.chama-loader-wrapper').css('display', 'none');
}