// Create a Stripe client.
(function ($) {

	var stripe = Stripe( mcs_stripe.publishable_key );
	var elements = stripe.elements();
	var submitButton = document.getElementById( 'mcs-stripe-submit' );
	var cardExists = document.getElementById( 'mcs-card-element' );

	if ( cardExists !== null ) {

		var style = {
			base: {
				// Add your base input styles here. For example:
				fontSize: '18px',
				color: "#32325d",
			},
			complete: {
				color: '#1b2798',
			},
			invalid: {
				iconColor: '#9f373e',
				color: '#9f373e',
			}
		};

		// Create an instance of the card Element.
		var card = elements.create('card', {style: style});

		// Add an instance of the card Element into the `card-element` <div>.
		card.mount('#mcs-card-element');
		
		card.addEventListener('change', function(event) {
			var displayError = document.getElementById('mcs-card-errors');
			if (event.error) {
				displayError.textContent = event.error.message;
			} else {
				displayError.textContent = '';
			}
		});
		
		// Create a token or display an error when the form is submitted.
		var form = document.getElementById('mcs-payment-form');

		form.addEventListener('submit', function(event) {
			event.preventDefault();

			var ownerInfo = {
				payment_method_data: {
					billing_details: {
						name: document.getElementById( 'mcs_name' ).value,
						email: document.getElementById( 'mcs_email' ).value
					},
				},
			};
			submitButton.disabled = true;
			submitButton.value = mcs_stripe.processing;
			submitButton.classList.add( 'processing' );
			var clientSecret = document.getElementById( 'mcs_client_secret' ).value;
			var errorElement = document.getElementById( 'mcs-card-errors' );

			stripe.handleCardPayment( clientSecret, card, ownerInfo ).then(function(result) {
				if (result.error) {
					// Inform the customer that there was an error.
					errorElement.textContent = result.error.message;
					errorElement.classList.add('visible');
					submitButton.disabled = false;
					submitButton.value = mcs_stripe.pay;
				} else {
					errorElement.textContent = mcs_stripe.success;
					errorElement.classList.add('visible');

					// Save the name/email of the purchaser.
					var payment_id = document.getElementById( 'mcs-payment-id' ).value;
					// get price via AJAX.
					var data = {
						'action' : mcssubmit.action,
						'security' : mcssubmit.security,
						'payer_name' : document.getElementById( 'mcs_name' ).value,
						'payer_email' : document.getElementById( 'mcs_email' ).value,
						'payment_id' : payment_id,
					};
					console.log( data );
					$.post( mcssubmit.ajaxurl, data, function (response) {}, "json" );

					// Delay 3 seconds to allow time for Stripe to communicate back to the server.
					setTimeout( function() {
						window.location = mcs_stripe.return_url.replace( '%d', payment_id );
					}, 3000 );
				}
			})
		});
	}

}(jQuery));