<?php

namespace SugarCalendarBookings\Locations;

/**
 * Online location provider factory.
 *
 * Registry-based factory for creating online location provider instances.
 * Providers self-register during boot via the register() method.
 * Custom link is always available as the default provider.
 *
 * @since 1.0.0
 */
class OnlineLocationProviderFactory {

	/**
	 * Registered provider classes keyed by slug.
	 *
	 * @since 1.4.0
	 *
	 * @var array<string, class-string<AbstractOnlineLocationProvider>>
	 */
	private static array $providers = [
		'custom_link' => CustomLinkProvider::class,
	];

	/**
	 * Register an online location provider.
	 *
	 * Called by integrations during init() to add themselves as available
	 * location providers in the service form.
	 *
	 * @since 1.4.0
	 *
	 * @param string $slug  Provider slug identifier.
	 * @param string $class Provider class name extending AbstractOnlineLocationProvider.
	 */
	public static function register( string $slug, string $class ): void {

		self::$providers[ $slug ] = $class;
	}

	/**
	 * Create an online location provider from an array.
	 *
	 * @since 1.0.0
	 *
	 * @param array $data The location data.
	 *
	 * @return AbstractOnlineLocationProvider|null
	 */
	public static function from_array( $data ) {

		if ( ! isset( $data['provider'] ) ) {
			return null;
		}

		$slug = $data['provider'];

		if ( ! isset( self::$providers[ $slug ] ) ) {
			return null;
		}

		return self::$providers[ $slug ]::from_array( $data );
	}

	/**
	 * Get all registered provider slugs.
	 *
	 * Used by ServiceFormService to build dynamic validation rules.
	 *
	 * @since 1.4.0
	 *
	 * @return string[]
	 */
	public static function get_registered_slugs(): array {

		return array_keys( self::$providers );
	}
}
