<?php
/**
 * Container: wires components, owns settings.
 *
 * @package Form_Flight_Recorder
 */

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

/**
 * Plugin container.
 */
class Ffrd_Plugin {

	/**
	 * Singleton.
	 *
	 * @var Ffrd_Plugin|null
	 */
	private static $instance = null;

	/**
	 * Components.
	 *
	 * @var array
	 */
	private $components = array();

	/**
	 * Accessor.
	 *
	 * @return Ffrd_Plugin
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Wire everything.
	 */
	private function __construct() {
		$this->components['events']     = new Ffrd_Events();
		$this->components['registry']   = new Ffrd_Registry();
		$this->components['collector']  = new Ffrd_Collector( $this );
		$this->components['adapters']   = new Ffrd_Adapters( $this );
		$this->components['reconciler'] = new Ffrd_Reconciler( $this );
		$this->components['alerts']     = new Ffrd_Alerts( $this );

		if ( is_admin() ) {
			$this->components['admin'] = new Ffrd_Admin( $this );
		}

		$this->components['site_health'] = new Ffrd_Site_Health( $this );

		if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( 'WP_CLI' ) ) {
			Ffrd_Cli::register( $this );
		}

		add_action( 'ffrd_tick_hourly', array( $this, 'tick_hourly' ) );
		add_action( 'ffrd_tick_daily', array( $this, 'tick_daily' ) );

		/**
		 * Fires when Form Flight Recorder finished wiring (Pro hooks this).
		 *
		 * @param Ffrd_Plugin $this Container.
		 */
		do_action( 'ffrd_loaded', $this );
	}

	/**
	 * Component accessor.
	 *
	 * @param string $key Component key.
	 * @return object|null
	 */
	public function get( $key ) {
		return isset( $this->components[ $key ] ) ? $this->components[ $key ] : null;
	}

	/**
	 * Settings with defaults.
	 *
	 * @return array
	 */
	public function settings() {
		$defaults = array(
			'digest'         => 'weekly',
			'digest_email'   => get_option( 'admin_email' ),
			'instant_alerts' => 1,
			'silence_hours'  => 48,
		);
		$saved    = get_option( 'ffrd_settings', array() );
		return wp_parse_args( is_array( $saved ) ? $saved : array(), $defaults );
	}

	/**
	 * Hourly: reconciliation sweep + heartbeat + prune.
	 */
	public function tick_hourly() {
		$this->get( 'reconciler' )->sweep();
		$this->get( 'events' )->prune();

		/**
		 * Fires on the hourly tick after the sweeps.
		 *
		 * @param Ffrd_Plugin $this Container.
		 */
		do_action( 'ffrd_hourly', $this );
	}

	/**
	 * Daily: form discovery + digest cadence + (Pro presence check).
	 */
	public function tick_daily() {
		$this->get( 'adapters' )->discover();
		$this->get( 'alerts' )->maybe_send_digest();

		/**
		 * Fires on the daily tick after discovery + digest (Pro presence hook).
		 *
		 * @param Ffrd_Plugin $this Container.
		 */
		do_action( 'ffrd_daily', $this );
	}
}
