<?php
/**
 * @fs_premium_only
 *
 * Preset registry. Free and Pro builds both call into this through the
 * helper afi_get_preset_registry(); in the free build the registry
 * simply has no presets registered (the /pro/ folder is stripped at
 * build time), so the helper returns a no-op object and the UI shows
 * upsell prompts instead of "Apply preset" buttons.
 *
 * @since 2.5.0
 * @package AutomotiveFeedImport
 */

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

class AFI_Preset_Registry
{
	/**
	 * @var AFI_Preset_Base[] Registered preset instances, keyed by preset id.
	 */
	private $presets = array();

	/**
	 * Register a preset. Called by each preset file at load time.
	 *
	 * @param AFI_Preset_Base $preset
	 */
	public function register(AFI_Preset_Base $preset)
	{
		$this->presets[$preset->get_id()] = $preset;
	}

	/**
	 * Get every registered preset.
	 *
	 * @return AFI_Preset_Base[]
	 */
	public function all()
	{
		return $this->presets;
	}

	/**
	 * Get the preset registered against a specific id, or null if none.
	 *
	 * @param string $id
	 * @return AFI_Preset_Base|null
	 */
	public function get($id)
	{
		return isset($this->presets[$id]) ? $this->presets[$id] : null;
	}

	/**
	 * Get all presets whose target CPT matches the given slug. Multiple
	 * presets can target the same CPT (e.g. different versions of the
	 * same host plugin), so callers should be ready for an array.
	 *
	 * @param string $cpt Post type slug.
	 * @return AFI_Preset_Base[]
	 */
	public function for_cpt($cpt)
	{
		$matches = array();
		foreach ($this->presets as $preset) {
			if ($preset->get_target_cpt() === $cpt) {
				$matches[$preset->get_id()] = $preset;
			}
		}
		return $matches;
	}
}

if (!function_exists('afi_get_preset_registry')) {
	/**
	 * Singleton accessor for the preset registry.
	 *
	 * @return AFI_Preset_Registry
	 */
	function afi_get_preset_registry()
	{
		static $instance = null;
		if (null === $instance) {
			$instance = new AFI_Preset_Registry();
		}
		return $instance;
	}
}
