<?php

namespace EasyCriticalCSS;

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

class Plugin {
	private static $instance = null;

	private static $plugin_version = '1.4.6';

	private static $db_version = '3';

	private static $plugin_file;

	public static function get_instance( $plugin_file = '' ) {
		if ( self::$instance === null ) {
			self::$instance    = new self();
			self::$plugin_file = $plugin_file;
		}

		return self::$instance;
	}

	public static function get_plugin_file() {
		return self::$plugin_file;
	}

	public static function get_plugin_version() {
		return self::$plugin_version;
	}

	public static function get_db_version() {
		return self::$db_version;
	}

	private function define_hooks() {
		add_action( 'plugins_loaded', [ $this, 'init' ] );
	}

	private function __construct() {
		$this->define_hooks();
	}

	/**
	 * Ensures stored plugin and database versions are up to date.
	 */
	public function ensure_version_consistency() {
		$stored_plugin_version = get_option( 'easy_cc_version' );
		$stored_db_version     = get_option( 'easy_cc_db_version' );

		if ( $stored_plugin_version !== self::$plugin_version ) {
			flush_rewrite_rules();
			update_option( 'easy_cc_version', self::$plugin_version );

			// Add handshake recycle if it doesn't exist.
			if ( ! wp_next_scheduled( 'easy_cc_cleanup_old_handshakes' ) ) {
				wp_schedule_event( time(), 'twicedaily', 'easy_cc_cleanup_old_handshakes' );
			}

			// Add timeout detection if it doesn't exist.
			if ( ! wp_next_scheduled( 'easy_cc_detect_timeouts' ) ) {
				wp_schedule_event( time(), 'hourly', 'easy_cc_detect_timeouts' );
			}
		}

		if ( $stored_db_version !== self::$db_version ) {
			update_option( 'easy_cc_db_version', self::$db_version );
		}
	}

	public function init() {
		// Don't load plugin on heartbeats
		if ( Helpers::is_heartbeat_request() ) {
			return;
		}

		Admin_Settings::init();
		Critical_CSS_Regenerate::init();
		Compatibility_Cache::init();
		Compatibility_Cloudflare::init();
		Compatibility_EWWW::init();
		Compatibility_Perfmatters::init();
		Compatibility_Trellis::init();
		Compatibility_WooCommerce::init();
		Compatibility_WP_Rocket::init();
		Critical_CSS::init();
		Database::init();
		Failure_Patterns::init();
		Gutenberg::init();
		Delete_Handler::init();
		Notification::init();
		Reset_Handler::init();
		REST_API::init();
		Uninstall_Handler::init();

		$this->ensure_version_consistency();
	}
}
