<?php
/**
 * PlayHealth — compute the health-pill state for an automation row.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class PlayHealth {

	public const STATE_GREEN  = 'green';
	public const STATE_YELLOW = 'yellow';
	public const STATE_RED    = 'red';
	public const STATE_PAUSED = 'paused';

	/**
	 * Compute the pill for a single play row.
	 *
	 * @param array<string,mixed>      $play     Workflow row (from wp_cartcue_workflows).
	 * @param array<string,mixed>|null $activity Last-run row from ReportsRepository::fetch_play_last_activity().
	 * @param Plugin                   $plugin   Plugin instance for cap/limit checks.
	 *
	 * @return array{state:string,label:string,tooltip:string,dot:string}
	 */
	public static function compute( array $play, $activity, Plugin $plugin ): array {
		$status  = (string) ( $play['status'] ?? 'paused' );
		$play_id = (int) ( $play['id'] ?? 0 );
		$last_at = is_array( $activity ) ? (string) ( $activity['last_run_at'] ?? '' ) : '';
		$run_cnt = (int) ( $play['run_count'] ?? 0 );

		if ( 'active' !== $status ) {
			return [
				'state'   => self::STATE_PAUSED,
				'label'   => __( 'Paused', 'cartcue-sales-automation' ),
				'tooltip' => __( 'This automation is paused. Toggle it on to start sending.', 'cartcue-sales-automation' ),
				'dot'     => '⚫',
			];
		}

		$mail = MarketingConsent::get_settings();
		if ( '' === trim( (string) ( $mail['from_email'] ?? '' ) ) ) {
			return [
				'state'   => self::STATE_RED,
				'label'   => __( 'Email config missing', 'cartcue-sales-automation' ),
				'tooltip' => __( 'No "From" address is set, so emails will fail. Open Settings → Sender.', 'cartcue-sales-automation' ),
				'dot'     => '🔴',
			];
		}

		$max_active = $plugin->max_active_plays();
		if ( $max_active > 0 && ! $plugin->is_play_allowed_to_run( $play_id ) ) {
			return [
				'state'   => self::STATE_RED,
				'label'   => __( 'Blocked by plan cap', 'cartcue-sales-automation' ),
				'tooltip' => __( 'Active but not running — the free plan cap is reached. Pause another play or upgrade.', 'cartcue-sales-automation' ),
				'dot'     => '🔴',
			];
		}

		if ( '' === $last_at && 0 === $run_cnt ) {
			return [
				'state'   => self::STATE_YELLOW,
				'label'   => __( 'Waiting for first trigger', 'cartcue-sales-automation' ),
				'tooltip' => __( "It's live, but no one has matched the trigger yet. Check that customers are actually doing this thing.", 'cartcue-sales-automation' ),
				'dot'     => '🟡',
			];
		}

		if ( '' !== $last_at ) {
			$age_sec = max( 0, time() - strtotime( $last_at ) );
			if ( $age_sec > 7 * DAY_IN_SECONDS ) {
				return [
					'state'   => self::STATE_YELLOW,
					'label'   => __( 'Sent 0× in 7 days', 'cartcue-sales-automation' ),
					'tooltip' => sprintf(
						/* translators: %s: human time diff e.g. "12 days" */
						__( 'Last sent %s ago. Check that customers still match the trigger.', 'cartcue-sales-automation' ),
						human_time_diff( strtotime( $last_at ), time() )
					),
					'dot'     => '🟡',
				];
			}
		}

		return [
			'state'   => self::STATE_GREEN,
			'label'   => __( 'Sending fine', 'cartcue-sales-automation' ),
			'tooltip' => $last_at
				? sprintf(
					/* translators: %s: human time diff e.g. "3 hours" */
					__( 'Last sent %s ago. All systems go.', 'cartcue-sales-automation' ),
					human_time_diff( strtotime( $last_at ), time() )
				)
				: __( 'Active and ready. The next match will send.', 'cartcue-sales-automation' ),
			'dot'     => '🟢',
		];
	}

	/**
	 * Render the pill HTML for a play.
	 */
	public static function render( array $play, $activity, Plugin $plugin ): string {
		$h = self::compute( $play, $activity, $plugin );
		return sprintf(
			'<span class="ap-health-pill ap-health-pill--%1$s" title="%2$s" data-state="%1$s"><span class="ap-health-pill__dot" aria-hidden="true">%3$s</span><span class="ap-health-pill__label">%4$s</span></span>',
			esc_attr( $h['state'] ),
			esc_attr( $h['tooltip'] ),
			esc_html( $h['dot'] ),
			esc_html( $h['label'] )
		);
	}
}
