<?php
/**
 * Registry of widget JSON import/export handlers.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Content_Widgets_Widget_Json_Registry
 */
class Rsmspark_Content_Widgets_Widget_Json_Registry {

	const EXPORT_PLUGIN = 'rsmspark-content-widgets';

	/**
	 * Widget ids with dedicated SiteOrigin admin scripts (skip generic enqueue).
	 *
	 * @return string[]
	 */
	public static function dedicated_admin_widget_ids() {
		return array( 'hero', 'footer', 'features' );
	}

	/**
	 * Widget ids that already define their own import_export form section.
	 *
	 * @return string[]
	 */
	public static function widgets_with_import_export_form() {
		return array( 'hero', 'footer', 'features' );
	}

	/**
	 * @param string $registry_id Widget registry id.
	 * @return string|null Dedicated config class or null for generic handler.
	 */
	public static function dedicated_handler_class( $registry_id ) {
		$map = array(
			'hero'     => 'Rsmspark_Content_Widgets_Hero_Presets',
			'footer'   => 'Rsmspark_Content_Widgets_Footer_Config',
			'features' => 'Rsmspark_Content_Widgets_Features_Config',
		);

		$id = sanitize_key( (string) $registry_id );

		return $map[ $id ] ?? null;
	}

	/**
	 * @param string $registry_id Widget registry id.
	 * @return string|null Render-layer widget class.
	 */
	public static function render_class_for( $registry_id ) {
		$id = sanitize_key( (string) $registry_id );
		if ( '' === $id ) {
			return null;
		}

		if ( class_exists( 'Rsmspark_Content_Widgets_Bootstrap', false ) ) {
			Rsmspark_Content_Widgets_Bootstrap::load_classes();
		}

		$parts = explode( '_', $id );
		$class = 'Rsmspark_Content_Widgets_Widget_' . implode( '_', array_map( 'ucfirst', $parts ) );

		return class_exists( $class, false ) ? $class : null;
	}

	/**
	 * @param string $registry_id Widget registry id.
	 * @return bool
	 */
	public static function supports_widget_json( $registry_id ) {
		$id = sanitize_key( (string) $registry_id );
		if ( '' === $id ) {
			return false;
		}

		if ( ! Rsmspark_Content_Widgets_Settings::is_widget_enabled( $id ) ) {
			return false;
		}

		if ( self::dedicated_handler_class( $id ) ) {
			return true;
		}

		return null !== self::render_class_for( $id );
	}

	/**
	 * @param string $block_slug Block slug (hyphenated).
	 * @return string
	 */
	public static function registry_id_from_block_slug( $block_slug ) {
		return Rsmspark_Content_Widgets_Registry::registry_id_from_block_slug( $block_slug );
	}

	/**
	 * @param string $registry_id Widget registry id.
	 * @return string
	 */
	public static function block_slug_for_registry_id( $registry_id ) {
		return Rsmspark_Content_Widgets_Registry::siteorigin_folder_id( $registry_id );
	}
}
