<?php
/**
 * Design System theme pack registry.
 *
 * @package Polanger_Dashboard_Tools
 */

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

/**
 * Loads optional preset theme packs from isolated theme folders.
 */
class PDT_Design_Themes {

	/**
	 * Theme directory map.
	 *
	 * @return array<string,string>
	 */
	public static function get_theme_dirs() {
		return array(
			'pg_aurora' => dirname( __DIR__ ) . '/themes/pg-aurora',
		);
	}

	/**
	 * Get preset token definitions provided by theme packs.
	 *
	 * @param array $defaults Base design defaults.
	 * @return array<string,array>
	 */
	public static function get_presets( $defaults ) {
		$presets = array();

		foreach ( self::get_theme_dirs() as $slug => $dir ) {
			$preset_file = trailingslashit( $dir ) . 'preset.php';
			if ( ! file_exists( $preset_file ) ) {
				continue;
			}

			$preset = include $preset_file;
			if ( is_array( $preset ) ) {
				$presets[ $slug ] = array_merge( $defaults, $preset );
			}
		}

		return $presets;
	}

	/**
	 * Get labels provided by theme packs.
	 *
	 * @return array<string,string>
	 */
	public static function get_labels() {
		return array(
			'pg_aurora' => __( 'PG Aurora', 'polanger-admin-menu-manager' ),
		);
	}

	/**
	 * Resolve a theme asset path and URL.
	 *
	 * @param string $preset Preset slug.
	 * @param string $file   Asset filename.
	 * @return array|null
	 */
	public static function get_asset( $preset, $file ) {
		$preset = sanitize_key( $preset );
		$file   = ltrim( (string) $file, '/\\' );
		$dirs   = self::get_theme_dirs();

		if ( empty( $dirs[ $preset ] ) ) {
			return null;
		}

		$path = trailingslashit( $dirs[ $preset ] ) . $file;
		if ( ! file_exists( $path ) ) {
			return null;
		}

		$relative_dir = 'themes/' . basename( $dirs[ $preset ] );

		return array(
			'path'    => $path,
			'url'     => plugin_dir_url( dirname( __FILE__ ) ) . $relative_dir . '/' . $file,
			'version' => (string) filemtime( $path ),
		);
	}

	/**
	 * Resolve all available theme assets for a filename.
	 *
	 * @param string $file Asset filename.
	 * @return array<string,array>
	 */
	public static function get_assets( $file ) {
		$assets = array();

		foreach ( array_keys( self::get_theme_dirs() ) as $preset ) {
			$asset = self::get_asset( $preset, $file );
			if ( $asset ) {
				$assets[ $preset ] = $asset;
			}
		}

		return $assets;
	}
}
