<?php
/**
 * Trait for campaign tracking on orders.
 *
 * @package     EDD\Pro\CampaignTracker\Campaigns\Traits
 * @copyright   Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.6.3
 */

namespace EDD\Pro\CampaignTracker\Campaigns\Traits;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

trait Order {
	/**
	 * Adds the campaign info to the order meta.
	 *
	 * @since 3.6.3
	 * @param int $order_id The order ID.
	 * @return void
	 */
	protected function add_meta( $order_id, $campaign_info ) {

		// Validate campaign data is a non-empty array before processing.
		if ( empty( $campaign_info ) || ! is_array( $campaign_info ) ) {
			return;
		}

		// Ensure at least one campaign parameter exists.
		// Accept any combination of utm_campaign, utm_source, utm_medium, utm_term, or utm_content.
		if ( empty( $campaign_info['name'] ) &&
			empty( $campaign_info['source'] ) &&
			empty( $campaign_info['medium'] ) &&
			empty( $campaign_info['term'] ) &&
			empty( $campaign_info['content'] ) ) {
			return;
		}

		// Save individual fields for reporting queries.
		if ( ! empty( $campaign_info['name'] ) ) {
			edd_update_order_meta( $order_id, '_eddct_campaign_name', $campaign_info['name'] );
		}
		if ( ! empty( $campaign_info['source'] ) ) {
			edd_update_order_meta( $order_id, '_eddct_campaign_source', $campaign_info['source'] );
		}
		if ( ! empty( $campaign_info['medium'] ) ) {
			edd_update_order_meta( $order_id, '_eddct_campaign_medium', $campaign_info['medium'] );
		}
		if ( ! empty( $campaign_info['term'] ) ) {
			edd_update_order_meta( $order_id, '_eddct_campaign_term', $campaign_info['term'] );
		}
		if ( ! empty( $campaign_info['content'] ) ) {
			edd_update_order_meta( $order_id, '_eddct_campaign_content', $campaign_info['content'] );
		}
	}
}
