<?php

/**
 * Dropdown Field
 *
 * @package AmbassadorHub\CustomFields
 */

namespace AmbassadorHub\Fields\Fields;

use function esc_attr;
use function esc_html;

/**
 * Class representing a dropdown custom field.
 */
final class DropdownField extends AbstractField {

	use OptionsFieldTrait;

	/**
	 * Constructor.
	 *
	 * Initializes the dropdown field with ID and label.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$this->id    = 'dropdown';
		$this->label = __( 'Dropdown', 'ambassadorhub' );

		parent::__construct();
	}

	/**
	 * Sanitize a dropdown value.
	 *
	 * @param mixed $value The raw value to sanitize.
	 *
	 * @return string The sanitized dropdown value.
	 */
	public function sanitize_value( $value ) {
		return sanitize_text_field( $value );
	}

	/**
	 * Render frontend input for dropdown fields.
	 *
	 * @param array  $field         Field definition.
	 * @param string $id            HTML id attribute.
	 * @param string $name          HTML name attribute.
	 * @param string $value         Current value.
	 * @param string $placeholder   Placeholder text.
	 * @param string $required_attr Required attribute string.
	 * @param string $class_attr    CSS class attribute string.
	 *
	 * @return void
	 */
	public function render_field_input(
		array $field,
		string $id,
		string $name,
		string $value,
		string $placeholder,
		bool $required,
		string $class_attr
	): void {
		$options         = $field['options'] ?? array();
		$class_attribute = '';
		if ( '' !== trim( $class_attr ) ) {
			$class_attribute = ' class="' . esc_attr( $class_attr ) . '"';
		}
		echo '<select'
			. ' id="' . esc_attr( $id ) . '"'
			. ' name="' . esc_attr( $name ) . '"'
			. $class_attribute // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- pre-escaped with esc_attr().
			. ( $required ? ' required' : '' )
			. '>';
		foreach ( $options as $option_value => $option_label ) {
			$selected = (string) $option_value === (string) $value ? ' selected="selected"' : '';
			echo '<option value="' . esc_attr( $option_value ) . '"' . $selected . '>' . esc_html( $option_label ) . '</option>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $selected is a static safe string.
		}
		echo '</select>';
	}
}
