<?php
/**
 * Subscription expiration job handler class.
 *
 * @since 2.6.10
 */

namespace Masteriyo\Pro\Jobs;

use Masteriyo\Pro\Enums\SubscriptionStatus;
use Masteriyo\Query\SubscriptionQuery;
use Masteriyo\DateTime;

defined( 'ABSPATH' ) || exit;

/**
 * Subscription expiration job handler class.
 *
 * @since 2.6.10
 */
class CheckSubscriptionExpirationJob {

	/**
	 * Hook to run the job.
	 *
	 * @since 2.6.10
	 */
	const HOOK = 'masteriyo/job/subscription-expiration';

	/**
	 * Initialize.
	 *
	 * @since 2.6.10
	 */
	public function init() {
		$this->init_hooks();
	}

	/**
	 * Initialize hooks.
	 *
	 * @since 2.6.10
	 */
	protected function init_hooks() {
		add_action( self::HOOK, array( $this, 'update_expired_subscription_status' ) );
	}

	/**
	 * Update expired subscription status.
	 *
	 * @since 2.6.10
	 */
	public function update_expired_subscription_status() {
		$query         = new SubscriptionQuery(
			array(
				'status'         => SubscriptionStatus::ACTIVE,
				'posts_per_page' => -1,
			)
		);
		$subscriptions = $query->get_subscriptions();

		foreach ( $subscriptions as $subscription ) {
			$billing_expire_after = $subscription->get_billing_expire_after();
			if ( ! $billing_expire_after ) {
				continue;
			}
			$current_date = new DateTime();
			$expiry_date  = $subscription->get_date_created()
							->modify( "+{$billing_expire_after} months" );
			if ( $current_date > $expiry_date ) {
				$subscription->set_status( SubscriptionStatus::EXPIRED );
				$subscription->save();
			}
		}
	}
}
