(function($){
    $(document).ready(function() {
        $('#razer-history').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: ajaxurl,
                data: {
                    action: "razer_gold_pin_store_generate_history"
                }
            },
            columns : [
                null,
                null,
                {
                    render : function(id) {
                        return '<button data-id="'+id+'" class="button button-secondary export">Exportar</button>'
                    }
                }
            ],
            info: false
        });
    });

    $('#razer-history').on("click", "button.export", function(e){
        const id = $(this).data('id');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'razer_gold_pin_store_generate_history_export',
                id: id
            },
            beforeSend : () => {
                Swal.fire({
                    title: 'Exportando',
                    onOpen: () => {
                        Swal.showLoading()
                    },
                    allowOutsideClick: false
                });
            },
            success: (r) => {
                if (r.url){
                    Swal.fire({
                        icon: 'success',
                        html: `<a target="_blank" href="${r.url}">Ver pins</a>`,
                        allowOutsideClick: false,
                        showCloseButton: true,
                        showConfirmButton: false
                    })
                }else{
                    Swal.fire(
                        'Error',
                        r.message,
                        'error'
                    );
                }
            }
        });
    });

})(jQuery);