{% extends 'base.html' %}

{% block content %}
<div class="container py-5">
    <h1>Stripe Payments</h1>
    {% if not stripe_publishable_key %}
    <div class="alert alert-warning" role="alert">
        Stripe is not configured. Please add your Stripe publishable key to your .env file.
    </div>
    {% else %}
    <p>You are about to purchase the {{ product }} package.</p>
    <button id="checkout-button" class="btn btn-primary">Checkout</button>
    {% endif %}
</div>

<script src="https://js.stripe.com/v3/"></script>
<script>
    {% if stripe_publishable_key %}
    var stripe = Stripe('{{ stripe_publishable_key }}');
    var checkoutButton = document.getElementById('checkout-button');

    checkoutButton.addEventListener('click', function() {
        // Create a Checkout Session to begin payment collection
        fetch('/create-checkout-session?product={{ product }}', {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}'
            }
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(session) {
            return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function(result) {
            // If `redirectToCheckout` fails due to a browser popup blocker, display the localized error message to your customer
            if (result.error) {
                alert(result.error.message);
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
        });
    });
    {% endif %}
</script>
{% endblock %}
