/* ScanVault Label Designer — Metabox JS */
(function ($) {
    'use strict';

    var params = svld_metabox_params;

    // Single product print
    $(document).on('click', '.svld-print-single', function () {
        var $btn    = $(this);
        var id      = $btn.data('id');
        var $status = $btn.closest('.svld-product-metabox').find('.svld-print-status');
        var qty     = $btn.closest('.svld-product-metabox').find('.svld-qty-input').val() || 1;

        $btn.prop('disabled', true);
        $status.text(params.generating);

        $.post(params.ajax_url, {
            action:     params.print_action,
            nonce:      $btn.data('nonce') || params.nonce,
            product_id: id,
            quantity:   qty,
        }, function (res) {
            $btn.prop('disabled', false);
            if (res.success && res.data.pdf_url) {
                $status.html('<a href="' + res.data.pdf_url + '" target="_blank">' + params.open_pdf + '</a>');
                window.open(res.data.pdf_url, '_blank');
            } else {
                var msg = res.data && res.data.message ? res.data.message : params.error;
                $status.css('color', '#dc3232').text(msg);
            }
        }).fail(function () {
            $btn.prop('disabled', false);
            $status.css('color', '#dc3232').text(params.error);
        });
    });

    // Order print
    $(document).on('click', '.svld-print-order', function () {
        var $btn     = $(this);
        var orderId  = $btn.data('order-id');
        var $status  = $btn.closest('.svld-order-metabox').find('.svld-print-status');

        $btn.prop('disabled', true);
        $status.text(params.generating);

        $.post(params.ajax_url, {
            action:   params.order_print_action,
            nonce:    $btn.data('nonce') || params.nonce,
            order_id: orderId,
        }, function (res) {
            $btn.prop('disabled', false);
            if (res.success && res.data.pdf_url) {
                $status.html('<a href="' + res.data.pdf_url + '" target="_blank">' + params.open_pdf + '</a>');
                window.open(res.data.pdf_url, '_blank');
            } else {
                var msg = res.data && res.data.message ? res.data.message : params.error;
                $status.css('color', '#dc3232').text(msg);
            }
        }).fail(function () {
            $btn.prop('disabled', false);
            $status.css('color', '#dc3232').text(params.error);
        });
    });

}(jQuery));
