{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="site__banner site__banner--site">
    <h1>Subscriptions</h1>
    <h2>Subscribe and save 10%</h2>
</div>
<article>
    <h1>Review your subscription</h1>

    Shipping address

    <dl>
        <dt>Items:</dt>
            <dd>{{ subscription.items }}</dd>
        <dt>Metadata:</dt>
            <dd>{{ subscription.metadata }}</dd>
        <dt>Address:</dt>
            <dd>{{ subscription.shipping_address }}</dd>
        <dt>Weight:</dt>
            <dd>{{ subscription.total_weight }}</dd>
        <dt>Created At:</dt>
            <dd>{{ subscription.created_at }}</dd>
    </dl>
    <form action="{% url 'storefront:subscription-confirmation' subscription.pk %}" class="subscription-confirmation-form" method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Continue to payment">
    </form>
</article>
<script>
    import { getCookie } from "./cookie.js"

    class Form {
        form

        constructor(form) {
            this.form = document.querySelector(form)
            this.connect()
        }

        connect() {
            this.form.addEventListener('submit', this.submit.bind(this))
        }

        fetch() {
            const formData = new FormData(form)

            // get the csrftoken
            const csrftoken = getCookie("csrftoken")

            const options = {
                method: "POST",
                body: JSON.stringify(Object.fromEntries(formData)),
                mode: "same-origin",
            };

            // construct a new Request passing in the csrftoken
            const request = new Request(this.form.action, {
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken
                },
            })

            return fetch(request, options)
                .then((response) => response.json())
                .then((subscription) => subscription.id)
        }

        submit(event) {
            event.preventDefault()
            response = this.fetch.bind(this)
            console.log(response)
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        new Form('.subscription-confirmation-form')
    })
</script>
{% endblock %}
