<?php

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

namespace AmbassadorHub\Fields\Fields;

use function esc_attr;
use function esc_html;
use function sanitize_key;

/**
 * Class representing a radio buttons custom field.
 */
final class RadioField extends AbstractField {

	use OptionsFieldTrait;

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

		parent::__construct();
	}

	/**
	 * Render the group label without a `for` attribute — radio groups have multiple inputs.
	 */
	public function render_field_label( array $field, $id, $label ): void {
		if ( empty( $field['label'] ) ) {
			return;
		}
		$required = ! empty( $field['required'] );
		echo '<label>'
			. esc_html( $label )
			. ( $required ? ' <span aria-hidden="true">*</span>' : '' )
			. '</label>';
	}

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

	/**
	 * Render frontend input for radio 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();
		foreach ( $options as $option_value => $option_label ) {
			$checked  = (string) $option_value === (string) $value ? ' checked="checked"' : '';
			$radio_id = $id . '_' . sanitize_key( $option_value );
			echo '<label style="display: block; margin: 8px 0;">';
			echo '<input type="radio"'
				. ' id="' . esc_attr( $radio_id ) . '"'
				. ' name="' . esc_attr( $name ) . '"'
				. ' value="' . esc_attr( $option_value ) . '"'
				. $checked // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static safe string.
				. ' />';
			echo ' ' . esc_html( $option_label );
			echo '</label>';
		}
	}
}
