jQuery(document).ready(function ($) {
    $('.bwd-download-text').on('click', function (e) {

        var $button = $(this);
        var order_id = $button.data('order-id') || 0;
        var cv_download = $button.data('cv-download') || 0;
        var subscription_billing_period = $button.data('subscription-billing-period') || '';
        var template_style = $button.data('template-style') || '';

        var cv_download_cell = $button.closest('tr').find('.cv-download-cell');
        var total_download_cell = $button.closest('tr').find('.total-download-cell');

        $.ajax({
            url: bwd_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'bwd_handle_pdf_download',
                order_id: order_id,
                cv_download: cv_download,
                subscription_billing_period: subscription_billing_period,
                template_style: template_style,
                security: bwd_ajax_object.security,
            },
            success: function (response) {
                if (response.success) {

                    // Update remaining downloads counter (subscription only)
                    if (cv_download_cell.length && response.data.remaining_downloads !== undefined) {
                        cv_download_cell.text(response.data.remaining_downloads);
                    }

                    // Update total downloads counter (subscription only)
                    if (total_download_cell.length && response.data.total_downloads !== undefined) {
                        total_download_cell.text(response.data.total_downloads);
                    }

                } else {
                    e.stopImmediatePropagation();
                    alert(response.data.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX Error: ' + error);
                alert('An error occurred while downloading the file.');
            }
        });
    });
});