<?php
/**
 * SocialPromoter Platform Registry
 *
 * Static registry where platform connectors register themselves.
 * The Poster, Accounts page, and any other component that needs to
 * interact with platforms queries this registry rather than having
 * hardcoded knowledge of specific connectors.
 *
 * Registration happens in PKITS_SP_Core on plugins_loaded. To add
 * a new platform, create a connector class implementing
 * PKITS_SP_Connector_Interface and call register() from Core.
 *
 * @package PublisherKits_SocialPromoter
 */

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

/**
 * Class PKITS_SP_Platform_Registry
 */
class PKITS_SP_Platform_Registry {

	/**
	 * Registered connector instances, keyed by slug.
	 *
	 * @var array<string, PKITS_SP_Connector_Interface>
	 */
	private static $connectors = array();

	/**
	 * Register a platform connector.
	 *
	 * Silently replaces any existing connector with the same slug,
	 * allowing connector upgrades without errors.
	 *
	 * @param PKITS_SP_Connector_Interface $connector Connector instance.
	 * @return void
	 */
	public static function register( PKITS_SP_Connector_Interface $connector ) {
		self::$connectors[ $connector->get_slug() ] = $connector;
	}

	/**
	 * Get a single connector by platform slug.
	 *
	 * @param string $slug Platform slug (e.g. 'x', 'facebook', 'linkedin').
	 * @return PKITS_SP_Connector_Interface|null Connector instance or null if not found.
	 */
	public static function get( $slug ) {
		return isset( self::$connectors[ $slug ] ) ? self::$connectors[ $slug ] : null;
	}

	/**
	 * Get all registered connectors.
	 *
	 * @return array<string, PKITS_SP_Connector_Interface>
	 */
	public static function get_all() {
		return self::$connectors;
	}

	/**
	 * Get all connectors available for a given tier.
	 *
	 * Returns connectors whose tier matches the given value or is 'free'
	 * when 'free' is requested.
	 *
	 * @param string $tier 'free' or 'pro'.
	 * @return array<string, PKITS_SP_Connector_Interface>
	 */
	public static function get_for_tier( $tier ) {
		if ( 'pro' === $tier ) {
			return self::$connectors;
		}
		return array_filter(
			self::$connectors,
			function ( $connector ) {
				return 'free' === $connector->get_tier();
			}
		);
	}

	/**
	 * Check whether a connector is registered for a given slug.
	 *
	 * @param string $slug Platform slug.
	 * @return bool
	 */
	public static function has( $slug ) {
		return isset( self::$connectors[ $slug ] );
	}

	/**
	 * Get all registered platform slugs.
	 *
	 * @return string[]
	 */
	public static function get_slugs() {
		return array_keys( self::$connectors );
	}
}
