<?php
/**
 * Variable source registry helpers.
 *
 * @package 100Prints
 */

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

require_once HUNDRED_PRINTS_PATH . 'data-sources/interface-variable-source.php';
require_once HUNDRED_PRINTS_PATH . 'data-sources/class-variable-source-base.php';
require_once HUNDRED_PRINTS_PATH . 'data-sources/class-variable-sources.php';
require_once HUNDRED_PRINTS_PATH . 'data-sources/class-variable-source-registry.php';

/**
 * Get the shared variable source registry.
 *
 * @return Hundred_Prints_Variable_Source_Registry
 */
function hundred_prints_get_variable_source_registry() {
	static $registry = null;

	if ( null === $registry ) {
		$registry = new Hundred_Prints_Variable_Source_Registry();
	}

	return $registry;
}

/**
 * Get the built-in variable source definitions.
 *
 * @return array
 */
function hundred_prints_get_builtin_variable_sources() {
	return hundred_prints_get_variable_source_registry()->get_editor_definitions();
}

/**
 * Get all variable source definitions, including third-party metadata additions.
 *
 * Prefer the `100prints_register_variable_sources` action for new behavior-bearing
 * sources. This filter remains for editor-only metadata and existing integrations.
 *
 * @return array
 */
function hundred_prints_get_variable_mapping_sources() {
	$sources = apply_filters( '100prints_variable_mapping_sources', hundred_prints_get_builtin_variable_sources() );

	return is_array( $sources ) ? array_values( $sources ) : [];
}

/**
 * Get one variable source definition by key.
 *
 * @param string $source_key Source key.
 * @return array|null
 */
function hundred_prints_get_variable_mapping_source( $source_key ) {
	$source_key = sanitize_key( $source_key );

	foreach ( hundred_prints_get_variable_mapping_sources() as $source ) {
		if ( isset( $source['value'] ) && $source['value'] === $source_key ) {
			return $source;
		}
	}

	return null;
}

/**
 * Sanitize a variable mapping field value based on its schema.
 *
 * @param array $field Field schema.
 * @param mixed $value Raw field value.
 * @return mixed
 */
function hundred_prints_sanitize_variable_mapping_field_value( array $field, $value ) {
	return Hundred_Prints_Variable_Source_Registry::sanitize_field_value( $field, $value );
}
