<?php
/**
 * Main plugin bootstrap.
 *
 * @package JOCBM
 */

namespace JOCBM;

use JOCBM\Admin\Admin;
use JOCBM\Blocks\BlockRegistry;
use JOCBM\Database\Schema;
use JOCBM\Rest\RestApi;
use JOCBM\Theme\ThemeConfig;

defined( 'ABSPATH' ) || exit;

/**
 * Class Plugin
 */
final class Plugin {

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

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

		return self::$instance;
	}

	/**
	 * Boot services.
	 */
	public function boot(): void {
		// DB migrations only — template fingerprint sync waits until `init`
		// so Pro/add-ons can register `jocbm_template_dirs` first.
		Schema::maybe_upgrade();
		add_action( 'init', array( Schema::class, 'maybe_sync_templates' ), 5 );

		$this->maybe_migrate_welcome_state();

		( new Admin() )->register();
		( new RestApi() )->register();
		( new BlockRegistry() )->register();
		( new ThemeConfig() )->register();

		/**
		 * Fires after JOC Blockora Morph core services are registered.
		 *
		 * Pro should hook here (or earlier on `plugins_loaded`) to:
		 * - `add_filter( 'jocbm_is_pro', '__return_true' )`
		 * - `add_filter( 'jocbm_template_dirs', … )`
		 * - `add_filter( 'jocbm_seed_categories', … )`
		 * - register REST routes / admin assets
		 *
		 * Register template-dir filters on `plugins_loaded` (priority ≤ 10)
		 * so free boot / seed see them. Fingerprint sync also runs on `init`.
		 * Call `jocbm_resync_library()` from Pro activation.
		 *
		 * @param Plugin $plugin Plugin instance.
		 */
		do_action( 'jocbm_init', $this );
	}

	/**
	 * Existing installs (pre–welcome-gate): skip Welcome on next load.
	 */
	private function maybe_migrate_welcome_state(): void {
		if ( get_option( 'jocbm_installed', false ) ) {
			return;
		}

		// Already had DB / version from an earlier release → treat as installed.
		if ( get_option( 'jocbm_db_version', '' ) || get_option( 'jocbm_version', '' ) ) {
			update_option( 'jocbm_installed', 1 );
			update_option( 'jocbm_welcome_seen', true );
		}
	}
}
