<?php
/**
 * Header layout registry.
 *
 * @package Kutby
 * @since   2.6.0
 */

declare(strict_types=1);

namespace Kutby\Header\Services;

use Kutby\Header\Contracts\HeaderLayoutInterface;

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

/**
 * Class HeaderRegistry
 */
final class HeaderRegistry {

	/**
	 * @var array<string, class-string<HeaderLayoutInterface>>
	 */
	private array $layouts = array();

	/**
	 * Shared instance for Manager / Module.
	 *
	 * @var self|null
	 */
	private static ?self $instance = null;

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

	/**
	 * @param string                              $id    Layout id.
	 * @param class-string<HeaderLayoutInterface> $class Class.
	 * @return void
	 */
	public function add( string $id, string $class ): void {
		$this->layouts[ sanitize_key( $id ) ] = $class;
	}

	/**
	 * @param string $id Id.
	 * @return bool
	 */
	public function has( string $id ): bool {
		return isset( $this->layouts[ sanitize_key( $id ) ] );
	}

	/**
	 * @param string $id Id.
	 * @return class-string<HeaderLayoutInterface>|null
	 */
	public function get_class( string $id ): ?string {
		$id = sanitize_key( $id );
		return $this->layouts[ $id ] ?? null;
	}

	/**
	 * @return array<string, class-string<HeaderLayoutInterface>>
	 */
	public function all(): array {
		return $this->layouts;
	}

	/**
	 * Id => Arabic label for Admin select.
	 *
	 * @return array<string, string>
	 */
	public function labels(): array {
		$out = array();
		foreach ( $this->layouts as $id => $class ) {
			if ( ! is_subclass_of( $class, HeaderLayoutInterface::class ) ) {
				continue;
			}
			/** @var HeaderLayoutInterface $instance */
			$instance   = new $class();
			$out[ $id ] = $instance->label();
		}
		return $out;
	}

	/**
	 * Instantiate a layout.
	 *
	 * @param string $id Id.
	 * @return HeaderLayoutInterface|null
	 */
	public function make( string $id ): ?HeaderLayoutInterface {
		$class = $this->get_class( $id );
		if ( null === $class || ! is_subclass_of( $class, HeaderLayoutInterface::class ) ) {
			return null;
		}
		return new $class();
	}
}
