(function () {
    function collectFormData(form) {
        var data = new FormData(form);
        var params = new URLSearchParams(window.location.search);

        ["sub1", "sub2", "sub3", "sub4", "sub5", "subid", "clickid"].forEach(function (key) {
            if (params.get(key) && !data.get(key)) {
                data.set(key, params.get(key));
            }
        });

        if (!data.get("subid") && data.get("clickid")) {
            data.set("subid", data.get("clickid"));
        }

        data.set("country", data.get("country") || "ES");
        data.set("country_code", data.get("country_code") || "ES");
        data.set("offer", data.get("offer") || "GlucoZen");
        data.set("source", document.referrer || window.location.href);
        data.set("timestamp", new Date().toISOString());

        return data;
    }

    function bindForms() {
        document.querySelectorAll("form").forEach(function (form) {
            form.setAttribute("action", "order.php");
            form.setAttribute("method", "post");

            if (form.dataset.drcashBound === "1") {
                return;
            }
            form.dataset.drcashBound = "1";

            form.addEventListener("submit", async function (event) {
                event.preventDefault();
                event.stopImmediatePropagation();

                var submitButton = form.querySelector("[type='submit'], button");
                var data = collectFormData(form);

                if (submitButton) {
                    submitButton.disabled = true;
                }

                try {
                    var response = await fetch("order.php", {
                        method: "POST",
                        headers: { "Content-Type": "application/json;charset=utf-8" },
                        body: JSON.stringify(Object.fromEntries(data.entries()))
                    });
                    var result = await response.json();

                    if (!response.ok || result.status !== "ok") {
                        throw new Error(result.message || "order_error");
                    }

                    sessionStorage.setItem("glucozen_order_confirmed", "1");
                    window.location.href = "thanks/?order=" + encodeURIComponent(result.order_reference || "confirmed");
                } catch (error) {
                    if (submitButton) {
                        submitButton.disabled = false;
                    }
                    alert("Por favor, revise sus datos e intentelo de nuevo.");
                }
            }, true);
        });
    }

    bindForms();
    document.addEventListener("DOMContentLoaded", bindForms);
    window.addEventListener("load", bindForms);
})();
