<?php
/**
 * Member Health / At-Risk Users.
 *
 * Scores users on engagement and surfaces those most likely to go inactive —
 * the early-warning complement to Ghost Purge. Generic: works on any site, with
 * MemberPress as an optional booster. Records a last-login timestamp so recency
 * scoring improves from the moment the module is enabled.
 *
 * Default off.
 *
 * @package Platform\Helm\Modules\Member_Health
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Member_Health;

use Platform\Helm\Contracts\ModuleInterface;
use WP_User;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class MemberHealthModule implements ModuleInterface {

	public function id(): string {
		return 'member_health';
	}

	public function name(): string {
		return __( 'At-Risk Users', 'platform-helm' );
	}

	public function description(): string {
		return __( 'Scores users on engagement — login recency, content activity and tenure (plus MemberPress subscription when present) — and flags those most likely to go inactive. The early-warning side of Ghost Purge.', 'platform-helm' );
	}

	public function default_enabled(): bool {
		return false;
	}

	public function boot(): void {
		add_action( 'wp_login', [ $this, 'record_login' ], 10, 2 );
		( new AtRiskUsersPage() )->register_hooks();
	}

	/**
	 * Stamp the user's last-login time so recency scoring is accurate going
	 * forward (historical logins fall back to the registration date).
	 *
	 * @param string $user_login
	 * @param mixed  $user
	 */
	public function record_login( $user_login, $user ): void {
		unset( $user_login );
		if ( $user instanceof WP_User && $user->exists() ) {
			update_user_meta( $user->ID, HealthScorer::LAST_LOGIN_META, time() );
		}
	}
}
