<?php
/**
 * SVG Icon registry.
 *
 * @package Kutby
 * @since   2.5.0
 */

declare(strict_types=1);

namespace Kutby\Icons;

use Kutby\Helpers\Utils;

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

/**
 * Class Registry
 */
final class Registry {

	/**
	 * Registered icon name => relative path under assets/icons/.
	 *
	 * @var array<string, string>
	 */
	private static array $map = array();

	/**
	 * Whether defaults were registered.
	 *
	 * @var bool
	 */
	private static bool $booted = false;

	/**
	 * Register default admin/nav icons.
	 *
	 * @return void
	 */
	public static function boot(): void {
		if ( self::$booted ) {
			return;
		}
		self::$booted = true;

		$defaults = array(
			'dashboard',
			'settings',
			'appearance',
			'colors',
			'typography',
			'header',
			'footer',
			'home',
			'button',
			'cards',
			'sidebar',
			'breadcrumb',
			'search',
			'social',
			'seo',
			'performance',
			'import',
			'info',
			'check',
			'close',
			'warning',
			'menu',
		);

		foreach ( $defaults as $name ) {
			self::add( $name, $name . '.svg' );
		}

		/**
		 * Allow registering extra icons.
		 *
		 * @since 2.5.0
		 *
		 * @param self $class Registry class string for static calls.
		 */
		do_action( 'kutby_icons_register' );
	}

	/**
	 * Register an icon.
	 *
	 * @param string $name Name.
	 * @param string $file Filename without .svg or relative path.
	 * @return void
	 */
	public static function add( string $name, string $file ): void {
		self::$map[ $name ] = $file;
	}

	/**
	 * @return array<string, string>
	 */
	public static function all(): array {
		self::boot();
		return self::$map;
	}

	/**
	 * Resolve path for an icon name.
	 *
	 * @param string $name Name.
	 * @return string
	 */
	public static function path( string $name ): string {
		self::boot();

		if ( isset( self::$map[ $name ] ) ) {
			$file = self::$map[ $name ];
			if ( str_ends_with( $file, '.svg' ) ) {
				return KUTBY_ASSETS . '/icons/' . ltrim( $file, '/' );
			}
			return KUTBY_ASSETS . '/icons/' . sanitize_file_name( $name ) . '.svg';
		}

		return Utils::icon_path( $name );
	}
}
