{% extends 'admin/kmuhelper/change_form.html' %}

{% block extrahead %}
    {{ block.super }}

    <script>
        function openURL(url, doPrint) {
            const $ = django.jQuery;

            // Check if the form has been changed
            const formChanged = $('form').serialize() !== window.initialData;
            if (formChanged) {
                if (!confirm('Achtung: Es liegen ungespeicherte Änderungen vor. Die PDF-Datei wird mit den aktuell gespeicherten Daten generiert. Trotzdem fortfahren?')) {
                    return false;
                }
            }

            // Open the URL in a new window
            const win = window.open(url, '_blank');

            // (Try to) automatically print the document
            if (doPrint) {
                setTimeout(function () {
                    win.print();
                }, 1000);
            }

            // Prevent the default action
            return false;
        }
    </script>

{% endblock extrahead %}

{% block object-tools-items %}
    {% if change %}
        <li class="dropdown">
            <a href="#">PDF Generieren</a>
            <div>
                <b>PDF generieren</b>
                <hr>
                <i>Rechnung</i>
                <a href="{% url 'admin:kmuhelper_order_pdf' object_id %}?preset=invoice" target="_blank"
                   onclick="return openURL(this.href, false);" rel="noopener">Digital</a>
                <a href="{% url 'admin:kmuhelper_order_pdf' object_id %}?preset=invoice&print" target="_blank"
                   onclick="return openURL(this.href, true);" rel="noopener">Druck</a>
                <hr>
                <i>Zahlungserinnerung</i>
                <a href="{% url 'admin:kmuhelper_order_pdf' object_id %}?preset=payment-reminder" target="_blank"
                   onclick="return openURL(this.href, false);" rel="noopener">Digital</a>
                <a href="{% url 'admin:kmuhelper_order_pdf' object_id %}?preset=payment-reminder&print" target="_blank"
                   onclick="return openURL(this.href, true);" rel="noopener">Druck</a>
                <hr>
                <i>Mehr</i>
                <a href="{% url 'admin:kmuhelper_order_pdf' object_id %}?preset=delivery-note" target="_blank"
                   rel="noopener">Lieferschein</a>
                <a href="{% url 'admin:kmuhelper_order_pdf_form' object_id %}">Benutzerdefiniert</a>
            </div>
        </li>

        {% if perms.kmuhelper.view_email or perms.kmuhelper.add_email %}
            {% load kmuhelper_tags %}
            {% kmuhelper_email_show_buttons as show_email_buttons %}
            {% if show_email_buttons %}

                <li class="dropdown">
                    <a href="#">E-Mails</a>
                    <div>
                        <b>E-Mails</b>
                        <hr>

                        {% if perms.kmuhelper.view_emailtemplate and perms.kmuhelper.add_email %}
                            <abbr title="Speichere die Daten dieser Bestellung im Zwischenspeicher und gehe zu E-Mail-Vorlagen">
                                <a href="{% url 'admin:kmuhelper_emailtemplate_savevars' %}?{{ original.to_query_string }}">Zu
                                    E-Mail-Vorlage</a>
                            </abbr>
                            <hr>
                        {% endif %}
                        {% if original.addr_billing_email %}
                            {% if original.email_link_invoice and perms.kmuhelper.view_email %}
                                <a href="{% url 'admin:kmuhelper_email_change' original.email_link_invoice.pk %}">Rechnungsemail
                                    ansehen</a>
                            {% endif %}
                            {% if perms.kmuhelper.add_email and perms.kmuhelper.change_order %}
                                <a href="{% url 'admin:kmuhelper_order_email_invoice' object_id %}">Rechnungsemail
                                    generieren</a>
                            {% endif %}
                        {% else %}
                            <a href="#" class="disabled">Rechnungsemail</a>
                        {% endif %}
                        <hr>
                        {% if original.addr_shipping_email and original.is_shipped %}
                            {% if original.email_link_shipped and perms.kmuhelper.view_email %}
                                <a href="{% url 'admin:kmuhelper_email_change' original.email_link_shipped.pk %}">Lieferungsemail
                                    ansehen</a>
                            {% endif %}
                            {% if perms.kmuhelper.add_email and perms.kmuhelper.change_order %}
                                <a href="{% url 'admin:kmuhelper_order_email_shipped' object_id %}">Lieferungsemail
                                    generieren</a>
                            {% endif %}
                        {% else %}
                            <a href="#" class="disabled">Lieferungsemail</a>
                        {% endif %}
                    </div>
                </li>

            {% endif %}
        {% endif %}

        {% if perms.kmuhelper.change_order and original.woocommerceid %}
            <li>
                <abbr title="Achtung: Hier abgeänderte Werte werden überschrieben, sofern diese in WooCommerce gespeichert werden können!">
                    <a href="{% url 'kmuhelper:wc-update-order' object_id %}">Von WooCommerce importieren und
                        ersetzen</a>
                </abbr>
            </li>
        {% endif %}

        {% if perms.kmuhelper.add_supply and original.is_shipped %}
            <li>
                <abbr title="Die Produkte dieser Bestellung zu einer Lieferung kopieren">
                    <a href="{% url 'admin:kmuhelper_order_copy_to_supply' object_id %}" rel="noopener">Rücksendung</a>
                </abbr>
            </li>
        {% endif %}

        {% if original.tracking_number %}
            <li><a target="_blank" href="{{ original.tracking_link }}" rel="noopener">Tracking</a></li>
        {% endif %}
    {% endif %}
    {{ block.super }}
{% endblock %}

{% block after_field_sets %}

    {# Order item inline column collapser #}
    <span id="orderitem-column-collapser">
        (<a onclick="toggleProductInlineExtend()">Mehr/weniger Spalten anzeigen</a>)
    </span>
    <style>
        #orderitem_set-group:not(.showmore) {
            .column-article_number,
            .column-quantity_description,
            .field-article_number,
            .field-quantity_description {
                display: none;
            }
        }

        #orderitem-column-collapser a {
            text-decoration: none;
            cursor: pointer;
        }

        #orderitem-column-collapser a:hover {
            text-decoration: underline;
            color: var(--header-link-color);
        }

        #orderitem_set-group, #orderfee_set-group {
            .field-vat_rate select {
                max-width: 6em;
            }

            .field-discount input {
                max-width: 6em;
            }

            .field-article_number input {
                max-width: 6rem;
            }
        }

    </style>
    <script>
        function toggleProductInlineExtend() {
            document.getElementById("orderitem_set-group").classList.toggle("showmore");
        }

        document.addEventListener("DOMContentLoaded", () => {
            document.querySelector("#orderitem_set-group h2").append(
                document.getElementById("orderitem-column-collapser")
            )

            {% if errors %}
                toggleProductInlineExtend();
            {% endif %}
        })
    </script>

    {# Address copy helper #}
    {% if change and has_change_permission and not original.is_shipped %}
        <div id="auto-copy-form-row" class="form-row">
            <div>
                <div class="flex-container checkbox-row">
                    <input type="checkbox" id="auto-copy"
                           {% if original.addresses_are_equal %}checked="checked"{% endif %}>
                    <label class="vCheckboxLabel" for="auto-copy">Von Rechnungsadresse übernehmen?</label>
                </div>
            </div>
        </div>
        <script>
            ADDR_FIELDS = ['first_name', 'last_name', 'company', 'address_1', 'address_2', 'postcode', 'city', 'state', 'email', 'phone'];
            COUNTRY_MAP = {"Schweiz": "CH", "Liechtenstein": "LI"}
            
            $ = django.jQuery;

            function copyFormIfCheck() {
                if ($("#auto-copy").prop("checked")) {
                    for (let field of ADDR_FIELDS) {
                        $(`#id_addr_shipping_${field}`).val(
                            $(`#id_addr_billing_${field}`).val() || $(`.field-addr_billing_${field} .readonly`).text()
                        )
                    }
                    {# Country is a special case because it's a select (val doesn't match what's displayed in readonly#}
                    $(`#id_addr_shipping_country`).val(
                        $(`#id_addr_billing_country`).val() || (
                            COUNTRY_MAP[$(`.field-addr_billing_country .readonly`).text()]
                        )
                    )
                }
            }

            function updateShippingFormVisibility() {
                if ($("#auto-copy").prop("checked")) {
                    $(".addr-shipping-fieldset .form-row:not(#auto-copy-form-row)").hide();
                    copyFormIfCheck();
                } else {
                    $(".addr-shipping-fieldset .form-row:not(#auto-copy-form-row)").show();
                }
            }

            document.addEventListener("DOMContentLoaded", () => {
                updateShippingFormVisibility();
                $(".addr-shipping-fieldset .form-row.field-addr_shipping_first_name").before(
                    document.getElementById("auto-copy-form-row")
                )

                $(".addr-billing-fieldset").on("input", copyFormIfCheck);
                $("#auto-copy").on("input", updateShippingFormVisibility);
            });
        </script>
    {% endif %}
{% endblock %}

{% block submit_buttons_bottom %}
    {{ block.super }}

    {% if not "unlock" in request.GET %}
        <a href="?unlock" title="Gesperrte Felder freischalten"><i class="fa-solid fa-lock-open"></i></a>
    {% endif %}
{% endblock %}