<?php
/**
 * Analytics tiles for ACR admin.
 *
 * @package EDD\Pro\CartRecovery\Admin\Screens
 * @copyright Copyright (c) 2026, Sandhills Development, LLC
 * @license https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since 3.6.5
 */

namespace EDD\Pro\CartRecovery\Admin\Screens;

use EDD\Pro\CartRecovery\Emails\Repository as Emails;
use EDD\Pro\CartRecovery\Carts\Repository;
use EDD\Admin\Utils\NoItems;

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

/**
 * Renders summary metrics tiles above the emails list.
 */
final class Analytics {

	/**
	 * Email repository.
	 *
	 * @var Emails|null
	 */
	private $email_repo;

	/**
	 * Cart repository.
	 *
	 * @var Repository|null
	 */
	private $cart_repo;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->email_repo = new Emails();
		$this->cart_repo  = new Repository();

		// Ensure Reports API is initialized.
		if ( ! did_action( 'edd_reports_init' ) ) {
			new \EDD\Reports\Init();
		}
	}

	/**
	 * Renders the analytics tiles with the EDD reports date filter.
	 *
	 * @since 3.6.5
	 * @throws \Exception If report registration or rendering fails.
	 */
	public function render(): void {

		// Render the date filter UI.
		$this->render_filters();

		?>
		<div id="edd-item-wrapper" class="edd-acr__analytics full-width edd-sections-wrap">
			<div class="section-wrap">
				<div id="edd-reports-tiles-wrap" class="edd-report-wrap section-content">
					<?php
					try {
						// Get the registered ACR report.
						$report = \EDD\Reports\get_report( 'cart_recovery_analytics' );

						if ( is_wp_error( $report ) ) {
							throw new \Exception( 'Cart Recovery report not registered: ' . $report->get_error_message() );
						}

						// Get all registered tile endpoints from the report.
						$tiles = $report->get_endpoints( 'tiles' );

						if ( empty( $tiles ) ) {
							echo '</div></div>';
							$this->render_empty_state();
							return;
						}

						// Check if there's any data to display before rendering tiles.
						$first_tile = reset( $tiles );
						$has_data   = $first_tile && ! empty( $first_tile->get_data() );

						if ( ! $has_data ) {
							echo '</div></div>';
							$this->render_empty_state();
							return;
						}

						// Display each tile using the standard Reports display method.
						foreach ( $tiles as $tile ) {
							$tile->display();
						}
					} catch ( \Exception $e ) {
						edd_debug_log( 'EDD ACR Analytics: Failed to render tiles - ' . $e->getMessage() );
						echo '<div class="notice notice-error"><p>' . esc_html__( 'Unable to load analytics tiles.', 'easy-digital-downloads' ) . '</p></div>';
					}
					?>
				</div>

				<!-- Charts Section -->
				<div id="edd-reports-charts-wrap" class="edd-report-wrap section-content">
					<?php
					try {
						// Get the registered ACR report.
						$report = \EDD\Reports\get_report( 'cart_recovery_analytics' );

						if ( is_wp_error( $report ) ) {
							throw new \Exception( 'Cart Recovery report not registered: ' . $report->get_error_message() );
						}

						// Get all registered chart endpoints from the report.
						$charts = $report->get_endpoints( 'charts' );

						if ( ! empty( $charts ) ) {
							// Display each chart except the conversion funnel (which is on the Journey tab).
							foreach ( $charts as $chart_id => $chart ) {
								// Skip the conversion funnel chart - it belongs on the Journey tab.
								if ( 'acr_conversion_funnel_chart' === $chart_id ) {
									continue;
								}
								$chart->display();
							}
						}
					} catch ( \Exception $e ) {
						edd_debug_log( 'EDD ACR Analytics: Failed to render charts - ' . $e->getMessage() );
					}
					?>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Renders the date filter UI using the main EDD reports filter.
	 *
	 * @since 3.6.5
	 */
	private function render_filters(): void {
		?>
		<form method="get" id="edd-acr-analytics-filter">
			<input type="hidden" name="post_type" value="download"/>
			<input type="hidden" name="page" value="edd-cart-recovery"/>
			<input type="hidden" name="tab" value="analytics"/>
			<div id="edd-filters" class="wp-filter">
				<div class="filter-items">
					<?php \EDD\Reports\display_dates_filter(); ?>
					<input type="submit" class="button button-primary" value="<?php esc_attr_e( 'Apply', 'easy-digital-downloads' ); ?>"/>
				</div>
			</div>
		</form>
		<?php
	}

	/**
	 * Renders an empty state when no data is available.
	 *
	 * @since 3.6.5
	 */
	private function render_empty_state(): void {
		$no_items = new NoItems(
			__( 'No email activity yet', 'easy-digital-downloads' ),
			__( 'Email analytics will appear here once recovery emails are sent to customers with abandoned carts.', 'easy-digital-downloads' ),
			array(
				array(
					'type'  => 'secondary',
					'label' => __( 'Configure Email Settings', 'easy-digital-downloads' ),
					'url'   => edd_get_admin_url(
						array(
							'page' => 'edd-cart-recovery',
							'tab'  => 'settings',
						)
					),
				),
			)
		);
		$no_items->render();
	}
}
