<?php
/**
 * Cart Recovery Site Health integration.
 *
 * @package EDD\Pro\CartRecovery\Admin
 * @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;

use EDD\EventManagement\SubscriberInterface;
use EDD\Cron\Events\SingleEvent;

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

/**
 * Adds Cart Recovery information to WordPress Site Health.
 *
 * @since 3.6.5
 */
final class SiteHealth implements SubscriberInterface {

	/**
	 * Returns the subscribed events.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	public static function get_subscribed_events(): array {
		return array(
			'edd_debug_information' => 'add_cart_recovery_info',
		);
	}

	/**
	 * Adds Cart Recovery information to the EDD debug information.
	 *
	 * @since 3.6.5
	 * @param array $information The debug information array.
	 * @return array Modified debug information array.
	 */
	public function add_cart_recovery_info( $information ) {
		if ( ! edd_get_option( 'acr_enabled', false ) ) {
			return $information;
		}

		$information['edd_cart_recovery'] = array(
			'label'  => __( 'Easy Digital Downloads &mdash; Cart Recovery', 'easy-digital-downloads' ),
			'fields' => $this->get_fields(),
		);

		return $information;
	}

	/**
	 * Gets the Cart Recovery fields for Site Health.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	private function get_fields() {
		return array_merge(
			$this->get_status_fields(),
			$this->get_statistics_fields(),
			$this->get_cron_fields()
		);
	}

	/**
	 * Gets status fields.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	private function get_status_fields() {
		return array(
			'acr_enabled'       => array(
				'label' => __( 'Cart Recovery Enabled', 'easy-digital-downloads' ),
				'value' => edd_get_option( 'acr_enabled', false ) ? __( 'Yes', 'easy-digital-downloads' ) : __( 'No', 'easy-digital-downloads' ),
			),
		);
	}

	/**
	 * Gets statistics fields.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	private function get_statistics_fields() {
		global $wpdb;

		$table = $wpdb->prefix . 'edd_acr_carts';
		$stats = array();

		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table ) {
			// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$total      = $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE status != 'expired'" );
			$with_email = $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE email IS NOT NULL AND status != 'expired'" );
			$oldest     = $wpdb->get_var( "SELECT MIN(date_created) FROM {$table}" );
			// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

			$stats['total_active_carts']  = array(
				'label' => __( 'Total Active Carts', 'easy-digital-downloads' ),
				'value' => (int) $total,
			);
			$stats['carts_with_email']    = array(
				'label' => __( 'Carts With Email', 'easy-digital-downloads' ),
				'value' => (int) $with_email,
			);
			$stats['carts_without_email'] = array(
				'label' => __( 'Carts Without Email', 'easy-digital-downloads' ),
				'value' => (int) ( $total - $with_email ),
			);

			if ( $oldest ) {
				$stats['oldest_cart_age'] = array(
					'label' => __( 'Oldest Active Cart', 'easy-digital-downloads' ),
					'value' => sprintf(
						/* translators: %s: human time difference */
						__( '%s ago', 'easy-digital-downloads' ),
						human_time_diff( strtotime( $oldest ), time() )
					),
				);
			}
		}

		return $stats;
	}

	/**
	 * Gets cron fields.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	private function get_cron_fields() {
		$cron_events = array(
			'edd_acr_cleanup_transients' => __( 'Transient Cleanup', 'easy-digital-downloads' ),
		);

		$fields = array();
		foreach ( $cron_events as $event => $label ) {
			$timestamp = SingleEvent::next_scheduled( $event );
			$value     = __( 'Not Scheduled', 'easy-digital-downloads' );

			if ( $timestamp ) {
				// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
				if ( defined( 'WP_DISABLE_CRON' ) && constant( 'WP_DISABLE_CRON' ) ) {
					$value = __( 'Cron Disabled', 'easy-digital-downloads' );
				} else {
					$value = sprintf(
						'%s (%s)',
						edd_date_i18n( $timestamp, 'Y-m-d H:i:s' ),
						/* translators: %s: human time difference */
						sprintf( __( 'in %s', 'easy-digital-downloads' ), human_time_diff( $timestamp ) )
					);
				}
			}

			$fields[ 'cron_' . sanitize_key( $event ) ] = array(
				'label' => $label,
				'value' => $value,
			);
		}

		return $fields;
	}
}
