<?php
/**
 * 5-minute cron that promotes scheduled coupons to active and expires past-end ones.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Modules\Coupons;

defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

final class Coupon_Scheduler {

	public static function register(): void {
		add_action( 'suitemkt3k_cron_5min', array( __CLASS__, 'tick' ) );
	}

	public static function tick(): void {
		global $wpdb;
		$now = current_time( 'mysql' );

		$wpdb->query(
			$wpdb->prepare(
				'UPDATE %i SET status = %s WHERE status = %s AND (starts_at IS NULL OR starts_at <= %s) AND (ends_at IS NULL OR ends_at > %s)',
				Coupon_Manager::table(),
				Coupon_Manager::STATUS_ACTIVE,
				Coupon_Manager::STATUS_SCHEDULED,
				$now,
				$now
			)
		);

		$wpdb->query(
			$wpdb->prepare(
				'UPDATE %i SET status = %s WHERE ends_at IS NOT NULL AND ends_at <= %s AND status <> %s',
				Coupon_Manager::table(),
				Coupon_Manager::STATUS_EXPIRED,
				$now,
				Coupon_Manager::STATUS_EXPIRED
			)
		);

		$ids = $wpdb->get_col(
			$wpdb->prepare(
				'SELECT id FROM %i WHERE updated_at >= %s',
				Coupon_Manager::table(),
				gmdate( 'Y-m-d H:i:s', time() - 600 )
			)
		);
		foreach ( (array) $ids as $cid ) {
			Coupon_Manager::sync_wc_coupon( (int) $cid );
		}
	}
}
