<?php
/**
 * Campaign information on order details screen.
 *
 * @package     EDD\Pro\CampaignTracker\Admin\Orders\Details
 * @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\Admin\Orders\Details;

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

use EDD\EventManagement\SubscriberInterface;

/**
 * Campaign Class.
 *
 * @since 3.6.3
 */
class Campaign implements SubscriberInterface {

	/**
	 * 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_get_order_details_sections' => 'add_campaign_section',
		);
	}

	/**
	 * Add campaign section to order details tabs.
	 *
	 * @since 3.6.3
	 * @param array $sections Existing sections.
	 * @return array Modified sections.
	 */
	public function add_campaign_section( $sections ) {
		if ( edd_is_add_order_page() ) {
			return $sections;
		}

		$sections['campaign'] = array(
			'id'       => 'campaign',
			'label'    => __( 'Campaign', 'easy-digital-downloads' ),
			'icon'     => 'megaphone',
			'callback' => array( $this, 'render_section' ),
		);

		return $sections;
	}

	/**
	 * Render campaign section content.
	 *
	 * @since 3.6.3
	 * @param object $order The order object.
	 * @return void
	 */
	public function render_section( $order ) {
		?>
		<div>
			<h3><?php esc_html_e( 'Campaign Information', 'easy-digital-downloads' ); ?></h3>
			<?php echo $this->render_campaign_info( $order->id ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		</div>
		<?php
	}

	/**
	 * Render Campaign Info.
	 *
	 * @since 3.6.3
	 * @param int $payment_id Payment post ID.
	 * @return string Campaign info.
	 */
	public function render_campaign_info( $payment_id ) {
		if ( empty( $payment_id ) ) {
			return '';
		}

		$campaign_info = $this->get_campaign_info( $payment_id );
		if ( ! $campaign_info ) {
			return __( 'No campaign information available.', 'easy-digital-downloads' );
		}

		$labels = array(
			'source'  => __( 'Campaign Source', 'easy-digital-downloads' ),
			'medium'  => __( 'Campaign Medium', 'easy-digital-downloads' ),
			'name'    => __( 'Campaign Name', 'easy-digital-downloads' ),
			'term'    => __( 'Campaign Term', 'easy-digital-downloads' ),
			'content' => __( 'Campaign Content', 'easy-digital-downloads' ),
		);

		ob_start();
		?>
		<table class="wp-list-table widefat striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Parameter', 'easy-digital-downloads' ); ?></th>
					<th><?php esc_html_e( 'Value', 'easy-digital-downloads' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php
				// Loop through labels because they're in the order we want.
				foreach ( $labels as $key => $value ) {
					if ( ! empty( $campaign_info[ $key ] ) ) {
						?>
						<tr>
							<td><strong><?php echo esc_html( $value ); ?></strong></td>
							<td><?php echo esc_html( $campaign_info[ $key ] ); ?></td>
						</tr>
						<?php
					}
				}
				?>
			</tbody>
		</table>
		<?php

		return ob_get_clean();
	}

	/**
	 * Gets the order campaign information.
	 *
	 * Retrieves campaign data from order meta, with fallback to legacy payment meta for
	 * backwards compatibility. If campaign data is found in the legacy payment_meta format,
	 * it will be automatically migrated to the modern order meta structure and the legacy
	 * data will be removed from payment_meta to prevent duplication.
	 *
	 * @since 3.6.3
	 * @param int $payment_id The order/payment ID.
	 * @return array|false The campaign information array containing campaign parameters (name, source, medium, etc.)
	 *                     if it exists; false if no campaign data is found.
	 */
	private function get_campaign_info( $payment_id ) {
		// Build campaign info from individual meta fields.
		$campaign_info = array(
			'name'    => edd_get_order_meta( $payment_id, '_eddct_campaign_name', true ),
			'source'  => edd_get_order_meta( $payment_id, '_eddct_campaign_source', true ),
			'medium'  => edd_get_order_meta( $payment_id, '_eddct_campaign_medium', true ),
			'term'    => edd_get_order_meta( $payment_id, '_eddct_campaign_term', true ),
			'content' => edd_get_order_meta( $payment_id, '_eddct_campaign_content', true ),
		);

		// Filter out empty values.
		$campaign_info = array_filter( $campaign_info );

		// If no individual fields exist, check for legacy serialized data.
		if ( empty( $campaign_info ) ) {
			// Check for legacy eddct_campaign meta.
			$legacy_campaign = edd_get_order_meta( $payment_id, 'eddct_campaign', true );

			if ( ! $legacy_campaign ) {
				// Check for even older payment_meta format.
				$payment_meta = edd_get_payment_meta( $payment_id );
				if ( ! empty( $payment_meta['eddct_campaign'] ) ) {
					$legacy_campaign = $payment_meta['eddct_campaign'];
				}
			}

			// Migrate legacy data to individual fields.
			if ( $legacy_campaign && is_array( $legacy_campaign ) ) {
				if ( ! empty( $legacy_campaign['name'] ) ) {
					edd_update_order_meta( $payment_id, '_eddct_campaign_name', $legacy_campaign['name'] );
				}
				if ( ! empty( $legacy_campaign['source'] ) ) {
					edd_update_order_meta( $payment_id, '_eddct_campaign_source', $legacy_campaign['source'] );
				}
				if ( ! empty( $legacy_campaign['medium'] ) ) {
					edd_update_order_meta( $payment_id, '_eddct_campaign_medium', $legacy_campaign['medium'] );
				}
				if ( ! empty( $legacy_campaign['term'] ) ) {
					edd_update_order_meta( $payment_id, '_eddct_campaign_term', $legacy_campaign['term'] );
				}
				if ( ! empty( $legacy_campaign['content'] ) ) {
					edd_update_order_meta( $payment_id, '_eddct_campaign_content', $legacy_campaign['content'] );
				}

				$campaign_info = $legacy_campaign;
			}
		}

		return ! empty( $campaign_info ) ? $campaign_info : false;
	}
}
