<?php
/**
 * Top Campaign by Average Order Value Tile.
 *
 * @package     EDD\Pro\CampaignTracker\Admin\Reports\Endpoints\Tiles
 * @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\Reports\Endpoints\Tiles;

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

use EDD\Reports\Endpoints\Tiles\Tile;

/**
 * Top Campaign by AOV Tile.
 *
 * @since 3.6.3
 */
class TopCampaignAOV extends Tile {

	/**
	 * Gets the tile endpoint ID.
	 *
	 * @since 3.6.3
	 * @return string
	 */
	protected function get_id(): string {
		return 'top_campaign_aov';
	}

	/**
	 * Gets the tile label for display.
	 *
	 * @since 3.6.3
	 * @return string
	 */
	protected function get_label(): string {
		return __( 'Top Campaign by AOV', 'easy-digital-downloads' );
	}

	/**
	 * Gets the data for the endpoint.
	 *
	 * @since 3.6.3
	 * @return string
	 */
	protected function get_data() {
		global $wpdb;

		$column = $this->exclude_taxes ? 'o.total - o.tax' : 'o.total';

		$result = $wpdb->get_row(
			"SELECT
				campaign.meta_value as campaign_name,
				AVG({$column}) as aov
			FROM {$wpdb->edd_orders} o
			INNER JOIN {$wpdb->edd_ordermeta} campaign ON (o.id = campaign.edd_order_id AND campaign.meta_key = '_eddct_campaign_name')
			WHERE o.type = 'sale'
			AND o.status IN('complete', 'revoked', 'partially_refunded')
			AND {$this->get_date_sql()}
			AND campaign.meta_value IS NOT NULL
			AND campaign.meta_value > ''
			GROUP BY campaign.meta_value
			ORDER BY aov DESC
			LIMIT 1"
		);

		if ( ! $result || ! $result->campaign_name ) {
			return __( 'No data', 'easy-digital-downloads' );
		}

		return sprintf(
			'%s<br><small>%s %s</small>',
			esc_html( $result->campaign_name ),
			edd_currency_filter( edd_format_amount( $result->aov ) ),
			__( 'avg', 'easy-digital-downloads' )
		);
	}
}
