/*
    Copyright AneonTech
    aneontech.help@gmail.com
*/

"use strict";

// Stripe init
function stripeInit(key, placeholders) {
    var stripe_key = Stripe(key);
    var stripe_elements = stripe_key.elements();
    var card_number = stripe_elements.create('cardNumber', {
        placeholder: placeholders[0],
        classes: {
            base: 'form-control stripe-input',
        },
    });
    card_number.mount('#card-number');
    var expiry_month = stripe_elements.create(
        'cardExpiry', {
            placeholder: placeholders[1],
            classes: {
                base: 'form-control stripe-input',
            },
        });
    expiry_month.mount('#card-expiry');
    var card_cvc = stripe_elements.create('cardCvc', {
        placeholder: placeholders[2],
        classes: {
            base: 'form-control stripe-input',
        },
    });
    card_cvc.mount('#card-cvc');

    function setOutcome(result) {
        var errorElement = document.querySelector(
            '.stripe-error');
        errorElement.classList.add('d-none');
        if (result.token) {
            var form = document.querySelector(
                'form[name=card-payment]');
            form
                .querySelector('input[name="token"]')
                .setAttribute('value', result.token.id);
            form.submit();
        } else if (result.error) {
            errorElement.querySelector('p').textContent 
                = result.error.message;
            errorElement.classList.remove('d-none');
        }
        document.querySelector('form[name=card-payment]')
            .querySelector('button[type=submit]').classList.remove('disabled');
    }
    stripe_elements.on('change', function(event) {
        setOutcome(event);
    });
    document
        .querySelector('form[name=card-payment]')
        .addEventListener('submit', function(e) {
            e.preventDefault();
            document.querySelector('form[name=card-payment]')
                .querySelector('button[type=submit]').classList.add('disabled');
            stripe_key.createToken(card_number).then(
                setOutcome);
        });
}