<?php
/**
 * Accounts Module Helpers
 *
 * Utility functions for account-related operations.
 *
 * @package AmbassadorHub\Accounts
 */

namespace AmbassadorHub\Accounts;

use AmbassadorHub\Accounts\AccountsTransient;

use function get_users;
use function gmdate;
use function time;
use function count;

/**
 * Helper functions for the Accounts module.
 */
final class Helpers {

	/**
	 * Get the total number of verified ambassadors.
	 *
	 * @return int Total ambassador count.
	 */
	public static function get_total_ambassadors(): int {
		$transient_key = 'total_ambassadors_count';
		$cached        = AccountsTransient::get( $transient_key );

		if ( false !== $cached ) {
			return (int) $cached;
		}

		$ambassadors = get_users(
			array(
				'role'       => Roles::ROLE_AMBASSADOR,
				'fields'     => 'ID',
				'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- required to filter verified ambassadors only.
					array(
						'key'     => '_ambh_email_verified',
						'value'   => '1',
						'compare' => '=',
					),
				),
			)
		);

		$count = count( $ambassadors );

		// Cache for 15 minutes.
		AccountsTransient::set( $transient_key, $count, 15 * MINUTE_IN_SECONDS );

		return $count;
	}

	/**
	 * Get the number of ambassadors registered in the past N days.
	 *
	 * @param int $days Number of days to look back.
	 *
	 * @return int Recent ambassador count.
	 */
	public static function get_recent_ambassadors( int $days = 7 ): int {
		$transient_key = 'recent_ambassadors_' . $days . 'd';
		$cached        = AccountsTransient::get( $transient_key );

		if ( false !== $cached ) {
			return (int) $cached;
		}

		// Calculate the date threshold.
		$days_ago = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );

		$ambassadors = get_users(
			array(
				'role'       => Roles::ROLE_AMBASSADOR,
				'fields'     => 'ID',
				'date_query' => array(
					array(
						'after'     => $days_ago,
						'inclusive' => true,
						'column'    => 'user_registered',
					),
				),
				'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- required to filter verified ambassadors only.
					array(
						'key'     => '_ambh_email_verified',
						'value'   => '1',
						'compare' => '=',
					),
				),
			)
		);

		$count = count( $ambassadors );

		// Cache for 15 minutes.
		AccountsTransient::set( $transient_key, $count, 15 * MINUTE_IN_SECONDS );

		return $count;
	}
}
