jQuery(document).ready(function($) {

    const hidePriceEl    = document.getElementById("hidePrice");
    const viewModeEl     = document.getElementById("viewMode");
    const showShippingEl = document.getElementById("showShipping");
    const bgValueEl      = document.getElementById("bgValue");
    const resultEl       = document.getElementById("copyLink");
    const msgEl          = document.getElementById("msg");
    const bgHelpEl       = document.getElementById("bgHelp");

    if (
        hidePriceEl &&
        viewModeEl &&
        showShippingEl &&
        bgValueEl &&
        resultEl &&
        msgEl &&
        bgHelpEl
    ) {

        function isHexColor(v) {
            return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(v.trim());
        }

        function isHttpUrl(v) {
            try {
                const u = new URL(v.trim());

                return u.protocol === "http:" ||
                    u.protocol === "https:";
            } catch {
                return false;
            }
        }

        function buildLink() {
            const base = resultEl.getAttribute("data-base");
            let url;

            try {
                url = new URL(base);
            } catch {
                resultEl.textContent = base;

                return base;
            }

            if (hidePriceEl.checked) {
                url.searchParams.set("price", "hide");
            } else {
                url.searchParams.delete("price");
            }

            if (viewModeEl.value === "full") {
                url.searchParams.set("view", "full");
            } else {
                url.searchParams.delete("view");
            }

            if (showShippingEl.checked) {
                url.searchParams.set("shipping", "show");
            } else {
                url.searchParams.delete("shipping");
            }

            const bg = bgValueEl.value.trim();

            if (!bg) {
                url.searchParams.delete("background");
                bgHelpEl.style.display = "none";
            } else if (isHexColor(bg) || isHttpUrl(bg)) {
                url.searchParams.set("background", bg);
                bgHelpEl.style.display = "none";
            } else {
                url.searchParams.delete("background");
                bgHelpEl.style.display = "block";
            }

            const finalUrl = url.toString();

            resultEl.textContent = finalUrl;

            return finalUrl;
        }

        function copyToClipboard() {
            const text = buildLink();

            navigator.clipboard.writeText(text).then(() => {
                msgEl.style.display = "block";

                setTimeout(() => {
                    msgEl.style.display = "none";
                }, 2000);
            }).catch(err => {
                alert("Kopiëren is niet gelukt: " + err);
            });
        }

        ["input", "change"].forEach(evt => {
            hidePriceEl.addEventListener(evt, buildLink);
            viewModeEl.addEventListener(evt, buildLink);
            showShippingEl.addEventListener(evt, buildLink);
            bgValueEl.addEventListener(evt, buildLink);
        });

        buildLink();
    }

    $("#pickingRoute").sortable({
        items: "tr.main",
        cursor: "pointer",
        axis: "y",
        dropOnEmpty: false,

        start: function(e, ui) {
            ui.item.addClass("selected");
        },

        stop: function(e, ui) {
            ui.item.removeClass("selected");
        }
    });

    $(".app_logo_upload").click(function(e) {
        e.preventDefault();

        var custom_uploader = wp.media({
            title: "Company logo",

            button: {
                text: "Upload Image"
            },

            multiple: false
        })
            .on("select", function() {
                var attachment = custom_uploader
                    .state()
                    .get("selection")
                    .first()
                    .toJSON();

                $(".app_logo").attr("src", attachment.url);
                $(".app_logo").show();
                $(".logoUrl").val(attachment.url);
            })
            .open();
    });

    $(".pickingSubRoute").sortable({
        items: "tr.sub",
        cursor: "pointer",
        axis: "y",
        dropOnEmpty: false,

        start: function(e, ui) {
            ui.item.addClass("selected");
        },

        stop: function(e, ui) {
            ui.item.removeClass("selected");
        }
    });

    $(document).on("click", "#add_app_user", function(e) {
        e.preventDefault();

        var clone = $(".duplicate_row").last();

        $(clone)
            .clone()
            .removeAttr("value")
            .insertAfter(clone);
    });

    $(document).on("click", ".remove_picker", function(e) {
        e.preventDefault();

        $(this)
            .closest(".orderpickingapp-user-card")
            .remove();
    });

    /*
     * AJAX - Create account
     */
    $("#createAccount").click(function(e) {
        e.preventDefault();

        $("#createAccount").addClass("disabled");

        var data = $(this)
            .parent("form")
            .serializeArray();

        $.ajax({
            type: "POST",
            url: ajaxurl,

            data: {
                action: "create_user_account",
                data: data,
                security: appData.nonce
            },

            dataType: "JSON",

            success: function(response) {
                if (response.message !== "") {
                    alert(response.message);
                    $("#createAccount").removeClass("disabled");
                } else {
                    location.reload();
                }
            },

            error: function() {
                $("#createAccount").removeClass("disabled");

                alert(
                    "Unable to create a account. Please try again."
                );
            }
        });
    });

    /*
     * AJAX - Reset API key
     */
    $("#orderpickingapp_reset_api_key").click(function(e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: ajaxurl,

            data: {
                action: "orderpickingapp_reset_api_key",
                security: appData.nonce
            },

            dataType: "JSON",

            success: function() {
                location.reload();
            }
        });
    });

    /*
 * AJAX - Save settings
 */
    $(".submit_options").click(function(e) {
        e.preventDefault();

        $(".submit_options").addClass("disabled");

        var current_form = $(this).closest("form");
        var data = current_form.serializeArray();

        /*
         * Bouw app_users expliciet per gebruikerskaart op.
         *
         * De HTML gebruikt app_users[][veld]. Met serializeArray() blijven
         * de gebruikersrijen daardoor niet betrouwbaar bij elkaar, vooral
         * omdat niet-aangevinkte checkboxes niet worden meegestuurd.
         */
        if (current_form.find(".orderpickingapp-user-card").length) {
            data = data.filter(function(item) {
                return item.name.indexOf("app_users[") !== 0;
            });

            /*
             * Geeft aan dat dit daadwerkelijk het gebruikersformulier is.
             * Hierdoor kan ook een lege gebruikerslijst worden opgeslagen.
             */
            data.push({
                name: "app_users_present",
                value: "1"
            });

            current_form.find(".orderpickingapp-user-card").each(function(index) {
                var card = $(this);

                var fields = [
                    "app_users_name",
                    "app_users_password",
                    "app_users_start_time",
                    "app_users_end_time",
                    "app_users_picking_amount",
                    "app_users_type"
                ];

                fields.forEach(function(field) {
                    var input = card.find(
                        "[name='app_users[][" + field + "]']"
                    ).first();

                    data.push({
                        name: "app_users[" + index + "][" + field + "]",
                        value: input.length ? input.val() : ""
                    });
                });

                data.push({
                    name:
                        "app_users[" +
                        index +
                        "][app_users_force_scan_all]",
                    value: card
                        .find(
                            "[name='app_users[][app_users_force_scan_all]']"
                        )
                        .is(":checked")
                        ? "1"
                        : "0"
                });
            });
        }

        current_form.find("input:checkbox").each(function() {
            var name = $(this).attr("name");

            if (
                !name ||
                name === "delivery_list_method[]" ||
                name === "pickup_list_method[]" ||
                name.indexOf("app_users[") === 0
            ) {
                return;
            }

            data.push({
                name: name,
                value: this.checked ? this.value : "0"
            });
        });

        var pickup_methods = [];

        $("input[name='pickup_list_method[]']:checked").each(function() {
            pickup_methods.push($(this).val());
        });

        data.push({
            name: "pickup_list_method",
            value: pickup_methods
        });

        var delivery_methods = [];

        $("input[name='delivery_list_method[]']:checked").each(function() {
            delivery_methods.push($(this).val());
        });

        data.push({
            name: "delivery_list_method",
            value: delivery_methods
        });

        var pickroute = [];

        $("input[name='pickroute']").each(function() {
            var pickroute_item = $(this).val();

            if (pickroute_item !== "") {
                pickroute.push(pickroute_item);
            }
        });

        data.push({
            name: "pickroute",
            value: pickroute
        });

        $.ajax({
            type: "POST",
            url: ajaxurl,

            data: {
                action: "save_app_settings",
                token: $("#token").val(),
                security: appData.nonce,
                data: data
            },

            dataType: "JSON",

            success: function(response) {
                alert(response.message);
                $(".submit_options").removeClass("disabled");
            },

            error: function() {
                alert("Unable to save this settings");
                $(".submit_options").removeClass("disabled");
            }
        });
    });

    /*
     * Download picklist
     */
    $(document).on(
        "click",
        ".DownloadPicklist",
        function(e) {
            e.preventDefault();

            var button = $(this);
            var buttonText = button.html();

            button.html("In progress...");

            $.ajax({
                type: "POST",
                url: ajaxurl,

                data: {
                    action: "download_picklist",
                    status: button.attr("order_status"),
                    type: button.attr("file_type"),
                    security: appData.nonce
                },

                success: function(response) {
                    button.html(buttonText);

                    if (response && response.link) {
                        window.open(
                            response.link,
                            "_blank"
                        );
                    } else {
                        alert(
                            "The pick list could not be downloaded."
                        );
                    }
                },

                error: function() {
                    button.html(buttonText);

                    alert(
                        "The pick list could not be downloaded."
                    );
                }
            });
        }
    );

    /*
     * Stock mutations laden
     */
    $(document).on(
        "click",
        "#load_stock_mutations",
        function(e) {
            e.preventDefault();

            var productId =
                $(this).attr("data-product_id");

            $("#stock_mutations").html(
                "<p>Loading stock mutations...</p>"
            );

            $.ajax({
                type: "POST",
                url: ajaxurl,

                data: {
                    action: "get_stock_mutations",
                    product_id: productId,
                    security: appData.nonce
                },

                success: function(response) {
                    $("#stock_mutations").html(
                        response.data
                    );
                },

                error: function(xhr, status, error) {
                    $("#stock_mutations").html(
                        '<span style="color:red;">Error: ' +
                        error +
                        "</span>"
                    );
                }
            });
        }
    );

    /*
     * Stock mutations exporteren
     */
    $("#export_stock_mutations").click(function(e) {
        e.preventDefault();

        var productId =
            $(this).attr("data-product_id");

        var url =
            ajaxurl +
            "?action=export_stock_mutations" +
            "&security=" +
            encodeURIComponent(appData.nonce) +
            "&product_id=" +
            encodeURIComponent(productId);

        window.location.href = url;
    });

    /*
     * Analytics laden
     */
    $(document).on(
        "click",
        "#loadAnalytics",
        function(e) {
            e.preventDefault();

            var data = {
                action: "load_analytics_html",
                token: $(this).attr("data-token"),
                security: appData.nonce
            };

            $.post(
                ajaxurl,
                data,
                function(response) {
                    $("#analytics .ajaxContent").html(
                        response
                    );
                }
            );
        }
    );

    /*
     * Analytics CSV downloaden
     */
    $(document).on(
        "click",
        "#downloadCSVExport",
        function(e) {
            e.preventDefault();

            var data = {
                action: "download_csv_export",
                token: $(this).attr("data-token"),
                security: appData.nonce
            };

            $.post(
                ajaxurl,
                data,
                function(response) {
                    var downloadLink =
                        document.createElement("a");

                    var fileData = [response];

                    var blobObject = new Blob(
                        fileData,
                        {
                            type: "text/csv;charset=utf-8;"
                        }
                    );

                    var url =
                        URL.createObjectURL(blobObject);

                    downloadLink.href = url;
                    downloadLink.download =
                        "picking_analytics.csv";

                    document.body.appendChild(
                        downloadLink
                    );

                    downloadLink.click();

                    document.body.removeChild(
                        downloadLink
                    );

                    URL.revokeObjectURL(url);
                }
            );
        }
    );

    const addIPButton = document.getElementById(
        'addCurrentPackingIp'
    );

    const ipField = document.getElementById(
        'packingAllowedIps'
    );

    if (!addIPButton || !ipField) {
        return;
    }

    addIPButton.addEventListener('click', function () {
        const currentIp = String(
            addIPButton.dataset.ip || ''
        ).trim();

        if (!currentIp) {
            return;
        }

        const currentValues = ipField.value
            .split(/\r?\n|,/)
            .map(function (value) {
                return value.trim();
            })
            .filter(Boolean);

        if (!currentValues.includes(currentIp)) {
            currentValues.push(currentIp);
            ipField.value = currentValues.join('\n');

            /*
             * Activeer eventueel de bestaande saveknop,
             * maar sla niet automatisch op.
             */
            ipField.dispatchEvent(
                new Event('change', {
                    bubbles: true
                })
            );
        }

        addIPButton.textContent = 'Current IP added';

        window.setTimeout(function () {
            addIPButton.textContent = 'Add current IP';
        }, 2000);
    });
});