<?php
/**
 * Main orchestrator (singleton).
 *
 * @package Defog
 */

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

class Defog {

	/** @var Defog|null */
	private static $instance = null;

	/** @var Defog_Tracker */
	public $tracker;
	/** @var Defog_Aggregator */
	public $aggregator;
	/** @var Defog_Rest */
	public $rest;
	/** @var Defog_WooCommerce */
	public $woocommerce;
	/** @var Defog_Admin */
	public $admin;

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

	private function __construct() {
		// Translations load automatically for wp.org-hosted plugins (WP 4.6+).
		$this->tracker    = new Defog_Tracker();
		$this->aggregator = new Defog_Aggregator();
		$this->rest       = new Defog_Rest();

		// E-commerce hooks are harmless when WooCommerce is absent (they never fire).
		$this->woocommerce = new Defog_WooCommerce();

		if ( is_admin() ) {
			$this->admin = new Defog_Admin();
		}

		// Safety net: ensure tables exist if the plugin was updated without re-activation.
		add_action( 'admin_init', array( $this, 'maybe_upgrade' ) );
	}

	/**
	 * Re-create tables / reschedule cron after a version bump.
	 */
	public function maybe_upgrade() {
		if ( get_option( 'defog_db_version' ) !== DEFOG_VERSION ) {
			Defog_Install::create_tables();
			update_option( 'defog_db_version', DEFOG_VERSION );
			if ( ! wp_next_scheduled( 'defog_rollup_event' ) ) {
				wp_schedule_event( time() + 300, 'hourly', 'defog_rollup_event' );
			}
		}
	}
}
