<?php
/**
 * Top Campaign by Orders 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 Orders Tile.
 *
 * @since 3.6.3
 */
class TopCampaignOrders extends Tile {

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

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

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

		$result = $wpdb->get_row(
			"SELECT
				campaign.meta_value as campaign_name,
				COUNT(DISTINCT o.id) as order_count
			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 order_count 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 ),
			number_format_i18n( $result->order_count ),
			_n( 'order', 'orders', $result->order_count, 'easy-digital-downloads' )
		);
	}
}
