<?php
/**
 * Choosing one field on a form.
 *
 * A select when the form's fields could be read, and a plain text box when they
 * could not. Form plugins change their internals between versions, and a
 * mapping control that renders as an empty dropdown is one a merchant cannot
 * work around — where a text box, with the name typed by hand, still works.
 *
 * @package TextTango
 *
 * @var array<string, mixed> $args {
 *     @type string   $id     Element id.
 *     @type string   $name   Field name.
 *     @type string   $value  Currently chosen field.
 *     @type string[] $fields Field names to offer.
 *     @type string   $none   Label for choosing nothing.
 * }
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

$texttango_fields = (array) ( $args['fields'] ?? array() );
$texttango_value  = (string) ( $args['value'] ?? '' );
$texttango_id     = (string) ( $args['id'] ?? '' );
$texttango_name   = (string) ( $args['name'] ?? '' );

/*
 * A value that is no longer among the form's fields is still offered, so
 * rebuilding a form does not silently unconfigure the mapping and leave the
 * screen showing "none" as though the merchant had chosen it.
 */
if ( '' !== $texttango_value && ! in_array( $texttango_value, $texttango_fields, true ) ) {
	$texttango_fields[] = $texttango_value;
}
?>
<?php if ( empty( $texttango_fields ) ) : ?>
	<input
		type="text"
		class="tt-input"
		id="<?php echo esc_attr( $texttango_id ); ?>"
		name="<?php echo esc_attr( $texttango_name ); ?>"
		value="<?php echo esc_attr( $texttango_value ); ?>"
		placeholder="<?php esc_attr_e( 'Field name', 'texttango' ); ?>"
	/>
<?php else : ?>
	<select class="tt-input" id="<?php echo esc_attr( $texttango_id ); ?>" name="<?php echo esc_attr( $texttango_name ); ?>">
		<option value=""><?php echo esc_html( (string) ( $args['none'] ?? '' ) ); ?></option>
		<?php foreach ( $texttango_fields as $texttango_field ) : ?>
			<option value="<?php echo esc_attr( (string) $texttango_field ); ?>" <?php selected( $texttango_value, (string) $texttango_field ); ?>>
				<?php echo esc_html( (string) $texttango_field ); ?>
			</option>
		<?php endforeach; ?>
	</select>
<?php endif; ?>
