<?php
/**
 * Cron Warmer.
 *
 * Schedules an hourly event that pre-computes the site-wide dashboard data
 * (manager + community widgets) into transients, so /wp-admin/ loads are cache
 * hits. Per-user author data is left to lazy compute.
 *
 * The event is unscheduled cleanly when the module is disabled or the plugin
 * deactivates, so we never leave orphaned cron entries.
 *
 * @package Platform\Helm\Modules\Persona_Dashboards
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Persona_Dashboards;

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

final class CronWarmer {

	public const HOOK     = 'platform_helm_pd_warm';
	private const SCHEDULE = 'hourly';

	private DataCache $cache;
	private DataProviders $data;

	public function __construct() {
		$this->cache = new DataCache();
		$this->data  = new DataProviders();
	}

	public function register_hooks(): void {
		add_action( self::HOOK, [ $this, 'warm' ] );
		add_action( 'admin_init', [ $this, 'maybe_schedule' ] );
	}

	public function maybe_schedule(): void {
		if ( ! wp_next_scheduled( self::HOOK ) ) {
			wp_schedule_event( time() + 60, self::SCHEDULE, self::HOOK );
		}
	}

	public static function unschedule(): void {
		$ts = wp_next_scheduled( self::HOOK );
		if ( false !== $ts ) {
			wp_unschedule_event( $ts, self::HOOK );
		}
		wp_clear_scheduled_hook( self::HOOK );
	}

	/**
	 * Pre-compute site-wide values used by manager + community widgets.
	 */
	public function warm(): void {
		$this->cache->put( 'mgr_content_counts', $this->data->content_counts(), DataCache::TTL_NORMAL );
		$this->cache->put( 'mgr_daily_publishing', $this->data->daily_publishing( 30 ), DataCache::TTL_RELAXED );
		$this->cache->put( 'mgr_recent_posts', $this->data->recent_posts( 8 ), DataCache::TTL_LIVE );
		$this->cache->put( 'editor_top_comments', $this->data->top_posts_by_comments( 5 ), DataCache::TTL_RELAXED );
		$this->cache->put( 'comm_recent_comments', $this->data->recent_comments( 8 ), DataCache::TTL_LIVE );

		do_action( 'platform_helm_pd_warm_completed' );
	}
}
