<?php
/**
 * Campaigns Domain Helpers
 *
 * Pure, stateless utility functions for the Campaigns domain.
 *
 * @package AmbassadorHub\Campaigns
 */

namespace AmbassadorHub\Campaigns;

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

/**
 * Stateless domain helpers for the Campaigns module.
 *
 * All methods are static; this class is never instantiated.
 */
final class CampaignsHelpers {

	/**
	 * Returns true when a post is an active (published) campaign.
	 *
	 * Only published campaigns are open for new fundraisers. Draft, future,
	 * and ended campaigns are excluded.
	 *
	 * @param int|\WP_Post|null $post Post ID or WP_Post object.
	 *
	 * @return bool
	 */
	public static function campaign_is_active( int|\WP_Post|null $post ): bool {
		$post = get_post( $post );

		if ( ! $post ) {
			return false;
		}

		if ( CampaignsModule::POST_TYPE !== $post->post_type || 'publish' !== $post->post_status ) {
			return false;
		}

		$end_date = get_post_meta( $post->ID, '_ambh_end_date', true );
		if ( $end_date && strtotime( $end_date ) <= time() ) {
			// Status was never updated (e.g. demo data with a past end date). Schedule an
			// immediate async action to end it, guarded against duplicate scheduling.
			if ( ! as_has_scheduled_action( 'ambh_end_campaign', array( $post->ID ), 'AmbassadorHub\Campaigns\CampaignsModule' ) ) {
				as_enqueue_async_action( 'ambh_end_campaign', array( $post->ID ), 'AmbassadorHub\Campaigns\CampaignsModule' );
			}
			return false;
		}

		return true;
	}
}
