<?php

declare(strict_types=1);

namespace SiteFort\Core;

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

use SiteFort\Core\Database\MigrationManager;
use SiteFort\Includes\Module_Loader;

/**
 * Coordinates runtime bootstrap, schema readiness, admin hooks, and modules.
 */
class Core {

	/**
	 * Maintains and registers plugin hooks.
	 */
	protected Module_Loader $loader;

	/**
	 * Plugin slug used for handles and page IDs.
	 */
	protected string $plugin_name;

	/**
	 * Current plugin version.
	 */
	protected string $version;

	/**
	 * Prepare core services before hooks are registered with WordPress.
	 */
	public function __construct() {
		$this->plugin_name = defined( 'SITEFORT_PLUGIN_SLUG' ) ? SITEFORT_PLUGIN_SLUG : 'sitefort';
		$this->version     = defined( 'SITEFORT_VERSION' ) ? SITEFORT_VERSION : '';

		$this->load_dependencies();

		\SiteFort\Core\Installer::ensure_runtime_directories();
		MigrationManager::bootstrap();
		\SiteFort\Includes\SettingsStore::maybe_migrate();
		\SiteFort\Includes\SettingsStore::ensure_boot_flags_autoloaded();

		$this->define_admin_hooks();
		$this->load_modules();
	}

	/**
	 * Load runtime services needed before module initialization.
	 */
	private function load_dependencies(): void {
		$this->loader = new Module_Loader();
	}

	/**
	 * Register hooks for the admin shell and React app host.
	 */
	private function define_admin_hooks(): void {
		$plugin_admin = new \SiteFort\Admin\Admin( $this->get_plugin_name(), $this->get_version() );

		$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_global_admin_assets', 10, 1 );
		$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles', 10, 1 );
		$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts', 10, 1 );
		$this->loader->add_filter( 'admin_body_class', $plugin_admin, 'add_admin_body_class', 10, 1 );
		$this->loader->add_filter( 'script_loader_tag', $plugin_admin, 'add_type_attribute', 10, 3 );
		$this->loader->add_action( 'admin_menu', $plugin_admin, 'add_admin_menu', 10, 0 );
		$this->loader->add_action( 'admin_notices', $plugin_admin, 'render_setup_notice', 10, 0 );
		$this->loader->add_action( 'wp_ajax_sitefort_dismiss_setup_notice', $plugin_admin, 'dismiss_setup_notice_ajax', 10, 0 );
	}

	/**
	 * Load and initialize feature modules.
	 */
	private function load_modules(): void {
		$this->loader->load_modules( $this->get_plugin_name(), $this->get_version() );
	}

	/**
	 * Register queued hooks with WordPress.
	 */
	public function run(): void {
		$this->loader->run();
	}

	/**
	 * Get the plugin slug.
	 */
	public function get_plugin_name(): string {
		return $this->plugin_name;
	}

	/**
	 * Get the hook loader.
	 */
	public function get_loader(): Module_Loader {
		return $this->loader;
	}

	/**
	 * Get the plugin version.
	 */
	public function get_version(): string {
		return $this->version;
	}

}
