<?php
/**
 * BW Dev core singleton. Constructs the settings layer, builds the module
 * registry, conditionally registers enabled modules, and (in admin) sets up
 * the Settings → BW Dev page.
 *
 * @package BW_Dev
 */

defined( 'ABSPATH' ) || exit;

class BW_Dev_Plugin {

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

	/**
	 * @var BW_Dev_Settings
	 */
	private $settings;

	/**
	 * @var BW_Dev_Brand|null
	 */
	private $brand = null;

	/**
	 * @var BW_Dev_Module_Interface[]
	 */
	private $modules = array();

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

	private function __construct() {}

	public function boot(): void {
		$this->settings = new BW_Dev_Settings();
		$this->settings->register();

		$this->brand = new BW_Dev_Brand( $this->settings );
		$this->brand->register();

		$this->modules = $this->build_modules();
		/**
		 * Filter the module registry. Sibling plugins can add a module here
		 * by appending an object that implements BW_Dev_Module_Interface.
		 */
		$this->modules = apply_filters( 'bw_dev_modules', $this->modules );
		$this->settings->set_modules( $this->modules );

		foreach ( $this->modules as $module ) {
			if ( $this->settings->is_module_enabled( $module->slug() ) ) {
				$module->register();
				do_action( 'bw_dev_module_registered', $module );
			}
		}

		if ( is_admin() ) {
			$admin_page = new BW_Dev_Admin_Page( $this->settings, $this->modules, $this->brand );
			$admin_page->register();
		}

		do_action( 'bw_dev_loaded', $this );
	}

	/**
	 * Built-in modules. New modules land here as the roadmap progresses.
	 */
	private function build_modules(): array {
		return array(
			new BW_Dev_Module_Favicon(),
			new BW_Dev_Module_Sticky(),
			new BW_Dev_Module_Youtube(),
			new BW_Dev_Module_Post_Link(),
			new BW_Dev_Module_Admin_Columns(),
			new BW_Dev_Module_SVG_Upload(),
			new BW_Dev_Module_Admin_Note(),
			new BW_Dev_Module_Flywheel_Auto_Updates(),
			new BW_Dev_Module_Menu_Visibility(),
			new BW_Dev_Module_Hide_Login(),
			new BW_Dev_Module_Security_Hardening(),
			new BW_Dev_Module_Login_Log(),
			new BW_Dev_Module_Subtitle(),
			new BW_Dev_Module_Separator(),
			new BW_Dev_Module_Robots_Txt(),
			new BW_Dev_Module_Llms_Txt(),
			new BW_Dev_Module_Title_Override(),
			new BW_Dev_Module_Established_Year(),
			new BW_Dev_Module_Vendors(),
			new BW_Dev_Module_Theme(),
		);
	}

	public function settings(): BW_Dev_Settings {
		return $this->settings;
	}

	public function brand(): ?BW_Dev_Brand {
		return $this->brand;
	}

	public function modules(): array {
		return $this->modules;
	}
}

/**
 * Global accessor for templates and other plugins.
 */
function bw_dev(): BW_Dev_Plugin {
	return BW_Dev_Plugin::instance();
}
