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

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

	/**
	 * Gets the tile label for display.
	 *
	 * @since 3.6.3
	 * @return string
	 */
	protected function get_label(): string {
		return __( 'Top Source 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
				source.meta_value as source_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} source ON (o.id = source.edd_order_id AND source.meta_key = '_eddct_campaign_source')
			WHERE o.type = 'sale'
			AND o.status IN('complete', 'revoked', 'partially_refunded')
			AND {$this->get_date_sql()}
			{$campaign_sql}
			AND source.meta_value IS NOT NULL
			AND source.meta_value > ''
			GROUP BY source.meta_value
			ORDER BY revenue DESC
			LIMIT 1"
		);

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

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