<?php

namespace CommerceBird;

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

if ( ! class_exists( 'CMBIRD_AI_Product_Blocks_Cron' ) ) {
	/**
	 * Handles weekly generation cron for AI product blocks.
	 */
	class CMBIRD_AI_Product_Blocks_Cron {

		const CRON_HOOK      = 'cmbird_ai_review_summary_weekly_cron';
		const OPTION_ENABLED = 'cmbird_ai_review_summary_enabled';

		/**
		 * Constructor.
		 */
		public function __construct() {
			add_filter( 'cron_schedules', array( $this, 'register_weekly_interval' ) );
			add_action( self::CRON_HOOK, array( $this, 'run' ) );
		}

		/**
		 * Register weekly schedule.
		 *
		 * @param array $schedules Cron schedules.
		 * @return array
		 */
		public function register_weekly_interval( $schedules ) {
			if ( ! isset( $schedules['weekly'] ) ) {
				$schedules['weekly'] = array(
					'interval' => WEEK_IN_SECONDS,
					'display'  => __( 'Once Weekly', 'commercebird' ),
				);
			}

			return $schedules;
		}

		/**
		 * Cron callback.
		 *
		 * @return void
		 */
		public function run(): void {
			if ( ! (bool) get_option( self::OPTION_ENABLED, false ) ) {
				return;
			}

			$product_ids = \wc_get_products(
				array(
					'status' => 'publish',
					'limit'  => -1,
					'return' => 'ids',
				)
			);

			if ( empty( $product_ids ) ) {
				return;
			}

			$generator = new \CommerceBird\CMBIRD_AI_Product_Blocks_Generator();
			foreach ( $product_ids as $product_id ) {
				$generator->generate( (int) $product_id );
				usleep( 200000 );
			}
		}

		/**
		 * Activation hook.
		 *
		 * @return void
		 */
		public static function activate(): void {
			if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
				wp_schedule_event( time(), 'weekly', self::CRON_HOOK );
			}
		}

		/**
		 * Deactivation hook.
		 *
		 * @return void
		 */
		public static function deactivate(): void {
			wp_clear_scheduled_hook( self::CRON_HOOK );
		}
	}
}

if ( ! class_exists( 'CMBIRD_AI_Review_Summary_Cron' ) && class_exists( 'CMBIRD_AI_Product_Blocks_Cron' ) ) {
	class_alias( __NAMESPACE__ . '\\CMBIRD_AI_Product_Blocks_Cron', __NAMESPACE__ . '\\CMBIRD_AI_Review_Summary_Cron' );
}
