<?php
/**
 * Plugin bootstrap.
 *
 * @package MacaHold
 */

defined( 'ABSPATH' ) || exit;

/**
 * Main plugin class.
 */
class Maca_Hold_Plugin {

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

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

		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		require_once MACA_HOLD_PATH . 'includes/class-plugin-updater.php';

		// Register updater on init so translated strings are not loaded before WP 6.7 allows it.
		add_action( 'init', array( $this, 'register_updater' ), 5 );
		add_action( 'init', array( $this, 'init' ) );

		if ( is_admin() ) {
			require_once MACA_HOLD_PATH . 'admin/class-admin-page.php';
			new Maca_Hold_Admin_Page();
		}
	}

	/**
	 * Register api.maca.se updater after init (translations safe).
	 *
	 * @return void
	 */
	public function register_updater() {
		maca_hold_register_updater();
	}

	/**
	 * Initialize frontend components.
	 *
	 * @return void
	 */
	public function init() {
		require_once MACA_HOLD_PATH . 'includes/hub-api.php';
		require_once MACA_HOLD_PATH . 'includes/hub-rest.php';
		new Maca_Hold_Hub_Rest();

		$extended = new Maca_Hold_Extended_Features();
		$extended->register();

		$page_exceptions = new Maca_Hold_Page_Exceptions();
		$page_exceptions->register();

		$renderer = new Maca_Hold_Template_Renderer();
		$gate     = new Maca_Hold_Maintenance_Gate( $renderer );
		$cache    = new Maca_Hold_Cache_Compat();

		$gate->register();
		$cache->register();
	}

	/**
	 * Activation hook.
	 *
	 * @return void
	 */
	public static function activate() {
		$settings = Maca_Hold_Settings::get();

		if ( empty( $settings['secret_token'] ) ) {
			$settings['secret_token'] = Maca_Hold_Settings::generate_secret_token();
			update_option( MACA_HOLD_OPTION_KEY, wp_parse_args( $settings, Maca_Hold_Settings::get_defaults() ) );
		}

		require_once MACA_HOLD_PATH . 'includes/maca-api.php';
		maca_hold_api_on_activate();
	}

	/**
	 * Deactivation hook.
	 *
	 * @return void
	 */
	public static function deactivate() {
		require_once MACA_HOLD_PATH . 'includes/maca-api.php';
		maca_hold_api_on_deactivate();
	}
}
