<?php
/**
 * Journey screen for cart recovery.
 *
 * @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;

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

/**
 * Journey screen for cart recovery showing customer funnel analytics.
 */
class Journey {

	/**
	 * Renders the journey/funnel screen.
	 *
	 * @since 3.6.5
	 * @throws \Exception If the report is not registered.
	 * @throws \Exception If the report is not initialized.
	 * @throws \Exception If the report is not initialized.
	 */
	public static function render() {
		// Ensure Reports API is initialized.
		if ( ! did_action( 'edd_reports_init' ) ) {
			new \EDD\Reports\Init();
		}

		// Render the date filter UI.
		self::render_filters();

		?>
		<div id="edd-item-wrapper" class="edd-acr__journey full-width edd-sections-wrap">
			<div class="section-wrap">
				<div class="section-content">
					<h2 class="edd-reports__heading"><?php esc_html_e( 'Funnel Performance', 'easy-digital-downloads' ); ?></h2>
					<!-- Funnel Tiles Section -->
					<div id="edd-reports-tiles-wrap" class="edd-report-wrap">
						<?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() );
							}

							// Display funnel-specific tiles.
							$funnel_tiles = array( 'acr_funnel_conversion', 'acr_dropoff_stage' );
							$all_tiles    = $report->get_endpoints( 'tiles' );

							foreach ( $funnel_tiles as $tile_id ) {
								if ( isset( $all_tiles[ $tile_id ] ) ) {
									$all_tiles[ $tile_id ]->display();
								}
							}
						} catch ( \Exception $e ) {
							edd_debug_log( 'EDD ACR Journey: Failed to render funnel tiles - ' . $e->getMessage() );
							echo '<div class="notice notice-error"><p>' . esc_html__( 'Unable to load funnel metrics.', 'easy-digital-downloads' ) . '</p></div>';
						}
						?>
					</div>

					<!-- Funnel Chart Section -->
					<div id="edd-reports-charts-wrap" class="edd-report-wrap">

						<?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 funnel chart endpoint.
							$charts = $report->get_endpoints( 'charts' );

							if ( isset( $charts['acr_conversion_funnel_chart'] ) ) {
								?>
								<div class="edd-reports-chart edd-reports-chart-<?php echo esc_attr( $charts['acr_conversion_funnel_chart']->get_type() ); ?>" id="edd-reports-table-<?php echo esc_attr( $charts['acr_conversion_funnel_chart']->get_id() ); ?>">
									<h3><?php echo esc_html( $charts['acr_conversion_funnel_chart']->get_label() ); ?></h3>
									<p class="description">
										<?php esc_html_e( 'Track how customers progress through the recovery funnel from cart abandonment to purchase completion.', 'easy-digital-downloads' ); ?>
									</p>
									<?php $charts['acr_conversion_funnel_chart']->display(); ?>
								</div>
								<?php
							}
						} catch ( \Exception $e ) {
							edd_debug_log( 'EDD ACR Journey: Failed to render funnel chart - ' . $e->getMessage() );
							echo '<div class="notice notice-error"><p>' . esc_html__( 'Unable to load funnel visualization.', 'easy-digital-downloads' ) . '</p></div>';
						}
						?>
					</div>

					<!-- Stage Metrics Table -->
					<div class="edd-report-wrap">
						<h3><?php esc_html_e( 'Funnel Stage Metrics', 'easy-digital-downloads' ); ?></h3>
						<?php self::render_stage_metrics(); ?>
					</div>

				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Renders the date filter UI using the main EDD reports filter.
	 *
	 * @since 3.6.5
	 */
	private static function render_filters() {
		?>
		<form method="get" id="edd-acr-journey-filter">
			<input type="hidden" name="post_type" value="download"/>
			<input type="hidden" name="page" value="edd-cart-recovery"/>
			<input type="hidden" name="tab" value="journey"/>
			<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 a table of funnel stage metrics.
	 *
	 * @since 3.6.5
	 */
	private static function render_stage_metrics() {
		$repository = new \EDD\Pro\CartRecovery\Journey\Repository();

		// Get date range from filters.
		$dates      = \EDD\Reports\parse_dates_for_range();
		$start_date = $dates['start']->copy()->format( 'Y-m-d' );
		$end_date   = $dates['end']->copy()->format( 'Y-m-d' );

		// Get funnel metrics.
		$metrics = $repository->get_funnel_metrics( $start_date, $end_date );
		$stages  = $metrics['stages'];
		$rates   = $metrics['conversion_rates'];

		?>
		<table class="wp-list-table widefat fixed striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Stage', 'easy-digital-downloads' ); ?></th>
					<th><?php esc_html_e( 'Unique Carts', 'easy-digital-downloads' ); ?></th>
					<th><?php esc_html_e( 'Conversion Rate', 'easy-digital-downloads' ); ?></th>
					<th><?php esc_html_e( 'Drop-Off', 'easy-digital-downloads' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php self::render_stage_row( __( 'Carts Created', 'easy-digital-downloads' ), $stages['created'], empty( $stages['created'] ) ? 0 : 100.0, 0 ); ?>
				<?php self::render_stage_row( __( 'Abandoned', 'easy-digital-downloads' ), $stages['abandoned'], $rates['created_to_abandoned'], $stages['created'] - $stages['abandoned'] ); ?>
				<?php self::render_stage_row( __( 'Email Sent', 'easy-digital-downloads' ), $stages['sent'], $rates['abandoned_to_sent'], $stages['abandoned'] - $stages['sent'] ); ?>
				<?php self::render_stage_row( __( 'Email Opened', 'easy-digital-downloads' ), $stages['opened'], $rates['sent_to_opened'], $stages['sent'] - $stages['opened'] ); ?>
				<?php self::render_stage_row( __( 'Email Clicked', 'easy-digital-downloads' ), $stages['clicked'], $rates['opened_to_clicked'], $stages['opened'] - $stages['clicked'] ); ?>
				<?php self::render_stage_row( __( 'Cart Restored', 'easy-digital-downloads' ), $stages['restored'], $rates['clicked_to_restored'], $stages['clicked'] - $stages['restored'] ); ?>
				<?php self::render_stage_row( __( 'Converted', 'easy-digital-downloads' ), $stages['converted'], $rates['abandoned_to_converted'], $stages['restored'] - $stages['converted'] ); ?>
			</tbody>
		</table>
		<?php
	}

	/**
	 * Renders a single row in the stage metrics table.
	 *
	 * @since 3.6.5
	 * @param string $stage_name    Stage name.
	 * @param int    $count         Number of carts at this stage.
	 * @param float  $conversion    Conversion rate.
	 * @param int    $dropoff       Number of drop-offs.
	 */
	private static function render_stage_row( $stage_name, $count, $conversion, $dropoff ) {
		?>
		<tr>
			<td><strong><?php echo esc_html( $stage_name ); ?></strong></td>
			<td><?php echo esc_html( number_format_i18n( $count ) ); ?></td>
			<td><?php echo esc_html( number_format_i18n( $conversion, 2 ) ); ?>%</td>
			<td>
				<?php if ( $dropoff > 0 ) : ?>
					<span class="edd-acr-dropoff"><?php echo esc_html( number_format_i18n( $dropoff ) ); ?></span>
				<?php else : ?>
					<span class="dashicons dashicons-minus"></span>
				<?php endif; ?>
			</td>
		</tr>
		<?php
	}
}
