{% extends "common/base.html" %}
{% load i18n static crispy_forms_tags purchase django_htmx %}

{% block extrahead %}
    <link rel="stylesheet" href="{% static "purchase/css/basket_form.css" %}">
{% endblock %}
{% block content %}
    {% if basket %}
        <h1>{{ basket }} <span id="basket-price" class="badge bg-secondary">{{ basket.price|currency }}</span></h1>
        <p class="metadata">
            {{ basket.created_at }}
        </p>
        {% if not basket.payment_method %}
            <div class="alert alert-danger" role="alert">{% translate "Missing payment method." %}</div>
        {% endif %}
    {% else %}
        <h1>{% translate "New basket" %} <span id="basket-price" class="badge bg-secondary d-none">{{ basket.price|currency }}</span></h1>
    {% endif %}
    {% crispy form %}
    <div class="row">
        <div class="col">
            <form
                hx-get="{% url "purchase:additional_unpriced_product" %}"
                hx-target="#products"
                hx-swap="beforeend"
            >
                <div class="input-group">
                    <select class="form-select" name="product_to_add" id="product_to_add">
                        {% for product in products %}
                            <option value="{{ product.pk }}">{{ product.name }}</option>
                        {% endfor %}
                    </select>
                    <button
                        class="btn btn-outline-secondary"
                        type="submit"
                        id="add_product"
                    >
                        {% translate "Add product" %}
                    </button>
                </div>
            </form>
        </div>
    </div>
    {% for item in basket.items.all %}
        {% if item.product.unit_price_cents == 0 %}
            <input
                type="hidden"
                hx-get="{% url "purchase:additional_unpriced_product" %}?product_to_add={{ item.product.pk }}&value={{ item.unit_price_cents }}"
                hx-trigger="load"
                hx-target="#products"
                hx-swap="beforeend"
            >
        {% endif %}
    {% endfor %}
    <div class="row mt-4">
        <div class="col">
            {% if basket %}
                <a href="{% url "purchase:new" %}" class="btn btn-secondary">{% translate "New basket" %}</a>
            {% endif %}
        </div>
    </div>
{% endblock %}

{% block extrascript %}
    <script src="{% static 'vendor/htmx-1.8.6/htmx.min.js' %}" defer></script>
    {% django_htmx_script %}
    <script defer type="application/javascript" src="{% static "purchase/js/basket_form.js" %}"></script>
{% endblock %}
