<?php
/**
 * Top Medium by Revenue 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 Medium by Revenue Tile.
 *
 * @since 3.6.3
 */
class TopMediumRevenue extends Tile {

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

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

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

		// Check if campaign filter is explicitly set in URL.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$has_campaign_filter = isset( $_GET['campaign_tracker'] );
		$campaign            = \EDD\Reports\get_filter_value( 'campaign_tracker' );
		$column              = $this->exclude_taxes ? 'o.total - o.tax' : 'o.total';

		// Build campaign filter SQL.
		$campaign_sql = '';
		if ( $has_campaign_filter && 'all' !== $campaign ) {
			if ( '' === $campaign ) {
				// Filter for empty/unknown campaigns.
				$campaign_sql = 'AND (campaign.meta_value IS NULL OR campaign.meta_value = \'\')';
			} else {
				$campaign_sql = $wpdb->prepare(
					'AND campaign.meta_value = %s',
					$campaign
				);
			}
		}

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

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

		return sprintf(
			'%s<br><small>%s</small>',
			esc_html( $result->medium_name ),
			edd_currency_filter( edd_format_amount( $result->revenue ) )
		);
	}
}
