// Add the product or variation regular price to the tracked download meta data.
add_action('somdn_count_download_post_success', 'carlo_add_price_to_download_meta', 10, 2);
function carlo_add_price_to_download_meta($post_id, $post_info)
{
    $product_id = ($post_info['meta_input']['somdn_product_id'] ?? 0);
    $variation_id = ($post_info['meta_input']['somdn_variation_id'] ?? 0);

    $product = null;
    $price = '';

    if ($variation_id) {
        $product = wc_get_product($variation_id);
        if ($product) {
            $price = $product->get_regular_price();
        }
    } else {
        $product = wc_get_product($product_id);
        if ($product) {
            $price = $product->get_regular_price();
        }
    }

    $price = sanitize_text_field($price);

    add_post_meta($post_id, 'carlo_download_product_price', $price);
}

// Output the price for the product/variation as it was at the time of download.
add_action('somdn_tracked_download_details_html', 'carlo_tracked_download_details_output_new');
function carlo_tracked_download_details_output_new($post_id)
{
    $price = get_post_meta($post_id, 'carlo_download_product_price', true);
    if (empty($price)) {
        $price = 'N/A';
    }

    ?>

        <div class="somdn-tracked-download-content-wrap">
            <div class="somdn-tracked-download-label">Price</div>
            <div class="somdn-tracked-download-content"><?php echo esc_html($price); ?></div>
        </div>

    <?php
}

// Add a custom column to the stats export with a unique header_id.
add_filter('somdn_stats_get_headers_all', 'carlo_download_stats_new_headers');
function carlo_download_stats_new_headers($headers)
{
    $new_header = array(
        'type' => 'custom',
        'title' => 'Price',
        'content' => 'string'
    );

    // Add the custom column with a unique header ID as the array key.
    // In this example the unique header ID is 'carlo_price'.
    // This is used when outputting the data to the spreadsheet.
    $headers['carlo_price'] = $new_header;

    return $headers;
}

// The filter name format is 'somdn_stats_get_custom_field_{header_id}',
// where header_id is the array key added in the 'somdn_stats_get_headers_all' filter.
// In the above price example we used 'carlo_price' as the header ID.
// Each new column needs its own filter/function.
// $download is the post ID of the download log.
add_filter('somdn_stats_get_custom_field_carlo_price', 'somdn_stats_get_custom_field_carlo_price_content', 10, 2);
function somdn_stats_get_custom_field_carlo_price_content($value, $download)
{
    $price = get_post_meta($download, 'carlo_download_product_price', true);
    if (empty($price)) {
        $price = '';
    }

    return esc_html($price);
}