<?php
/**
 * Migration functions for EDD 3.0 compatibility.
 *
 * @package     EDD\Pro\CampaignTracker\Upgrades
 * @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\Upgrades;

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

use EDD\EventManagement\SubscriberInterface;

/**
 * Migration Class
 *
 * @since 3.6.3
 */
class Migration implements SubscriberInterface {
	use \EDD\Pro\CampaignTracker\Campaigns\Traits\Order;

	/**
	 * Returns an array of events that this subscriber wants to listen to.
	 *
	 * @since 3.6.3
	 * @return array
	 */
	public static function get_subscribed_events() {
		return array(
			'edd_30_migrate_order' => array( 'migrate_campaign_data', 10, 3 ),
		);
	}

	/**
	 * During the EDD 3.0 migration, copies the campaign data from the old post metadata
	 * to the new order meta table.
	 *
	 * If the campaign data is the only thing in the `payment_meta`, delete that metadata.
	 * If anything else is left in the metadata, remove just the campaign data and update the order meta.
	 *
	 * @since 3.6.3
	 * @param int   $order_id     The new order ID.
	 * @param array $payment_meta The original payment meta.
	 * @param array $meta         The original post meta.
	 * @return void
	 */
	public function migrate_campaign_data( $order_id, $payment_meta, $meta ) {
		$campaign_info = ! empty( $payment_meta['eddct_campaign'] ) ? $payment_meta['eddct_campaign'] : false;
		if ( ! $campaign_info ) {
			return;
		}

		edd_update_order_meta( $order_id, 'eddct_campaign', $campaign_info );

		$this->add_meta( $order_id, $campaign_info );

		$migrated_meta = edd_get_order_meta( $order_id, 'payment_meta', true );
		if ( is_array( $migrated_meta ) && ! empty( $migrated_meta ) ) {
			unset( $migrated_meta['eddct_campaign'] );
		}
		if ( empty( $migrated_meta ) ) {
			edd_delete_order_meta( $order_id, 'payment_meta' );
		} else {
			edd_update_order_meta( $order_id, 'payment_meta', $migrated_meta );
		}
	}
}
