<?php
/**
 * Settings Tab Registry
 *
 * @package AmbassadorHub\Admin\Settings
 */

namespace AmbassadorHub\Admin\Settings;

/**
 * Manages registration and retrieval of settings tabs.
 *
 * Modules and feature plugins can register custom tabs and extend existing ones.
 */
final class Registry {
	/**
	 * Registered tabs.
	 *
	 * @var array<string,Tab>
	 */
	private static array $tabs = array();

	/**
	 * Get all registered tabs.
	 *
	 * @return array<string,Tab> Tabs keyed by tab ID.
	 */
	public static function get_tabs(): array {
		if ( empty( self::$tabs ) ) {
			self::load_tabs();
		}

		return self::$tabs;
	}

	/**
	 * Get a specific tab by ID.
	 *
	 * @param string $tab_id Tab identifier.
	 *
	 * @return Tab|null Tab instance or null if not found.
	 */
	public static function get_tab( string $tab_id ): ?Tab {
		$tabs = self::get_tabs();
		return $tabs[ $tab_id ] ?? null;
	}

	/**
	 * Load tabs from filters.
	 *
	 * @return void
	 */
	private static function load_tabs(): void {
		// Core tabs.
		$tabs = array(
			'general'  => new Tabs\GeneralTab(),
			'payments' => new Tabs\PaymentsTab(),
			'spam'     => new Tabs\SpamProtectionTab(),
			'tools'    => new Tabs\ToolsTab(),
			'advanced' => new Tabs\AdvancedTab(),
		);

		/**
		 * Filter to register or modify settings tabs.
		 *
		 * Modules and feature plugins can register new tabs or modify existing
		 * ones. The Custom Fields tab, for example, is added here by the
		 * AmbassadorHub Premium add-on when it's active.
		 *
		 * @since 0.1.0
		 *
		 * @param array<string,Tab> $tabs {
		 *     Tabs keyed by tab ID.
		 *
		 *     @type Tab Tab instance.
		 * }
		 */
		$tabs = apply_filters( 'ambh_settings_tabs', $tabs );

		self::$tabs = is_array( $tabs ) ? $tabs : array();
	}

	/**
	 * Register a settings tab.
	 *
	 * Can be called before Registry::get_tabs() to add custom tabs.
	 *
	 * @param string $tab_id Tab identifier.
	 * @param Tab    $tab    Tab instance.
	 *
	 * @return void
	 */
	public static function register_tab( string $tab_id, Tab $tab ): void {
		self::$tabs[ $tab_id ] = $tab;
	}
}
