<?php

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

namespace AmbassadorHub\Fields\Fields;

use AmbassadorHub\Fields\FieldFactory;

use InvalidArgumentException;
use function sanitize_text_field;
use function esc_attr;

/**
 * Class representing a checkbox custom field.
 */
final class CheckboxField extends AbstractField {

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

		parent::__construct();
	}

	/**
	 * Get the settings fields for this checkbox field.
	 *
	 * @return array
	 */
	public function get_settings_fields(): array {
		return array(
			array(
				'type'        => 'text',
				'id'          => 'checkbox_value',
				'label'       => __( 'Checkbox Value', 'ambassadorhub' ),
				'value'       => '1',
				'description' => __( 'Value to send in payload when checked.', 'ambassadorhub' ),
			),
		);
	}

	/**
	 * Sanitize a checkbox value (boolean).
	 *
	 * @param mixed $value The raw value to sanitize.
	 *
	 * @return bool The sanitized boolean value.
	 */
	public function sanitize_value( $value ) {
		return ! empty( $value );
	}

	/**
	 * Render a single field row (label + input + description).
	 *
	 * @param array $field Field configuration.
	 *
	 * @return void
	 */
	protected function render_field_settings_row( array $field ): void {
		?>
		<label for="<?php echo esc_attr( $field['id'] ); ?>" style="display: block; margin-bottom: 4px; font-weight: 600;">
			<?php echo esc_html( $field['label'] ); ?>
		</label>
		<?php FieldFactory::create( $field['type'] ?? 'text' )->render_field_input( $field, $field['id'], $field['id'], $field['value'] ?? '', $field['placeholder'] ?? '', $field['required'] ?? '', $field['class'] ?? '' ); ?>
		<?php if ( ! empty( $field['description'] ) ) : ?>
			<p class="description"><?php echo esc_html( $field['description'] ); ?></p>
		<?php endif; ?>
		<?php
	}

	/**
	 * Render nothing — checkbox label is rendered inside render_field_input.
	 */
	public function render_field_label( array $field, $id, $label ): void {}

	/**
	 * Validate and process checkbox field configuration.
	 *
	 * @param array $field Field configuration.
	 * @param array $data Raw input data.
	 *
	 * @return void Modifies $field array in-place.
	 *
	 * @throws InvalidArgumentException If validation fails.
	 */
	public function validate_and_process( array &$field, array $data ): void {
		$field['settings']['checkbox_value'] = sanitize_text_field( $data['settings']['checkbox_value'] ?? '1' );
	}

	/**
	 * Render frontend input for checkbox 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 {
		$class_attribute = '';
		if ( '' !== trim( $class_attr ) ) {
			$class_attribute = ' class="' . esc_attr( $class_attr ) . '"';
		}

		$checkbox_value = $field['checkbox_value'] ?? '1';
		$checked        = (string) $value === (string) $checkbox_value ? ' checked="checked"' : '';
		echo '<label>';
		echo '<input type="checkbox"'
			. ' id="' . esc_attr( $id ) . '"'
			. ' name="' . esc_attr( $name ) . '"'
			. ' value="' . esc_attr( $checkbox_value ) . '"'
			. $class_attribute // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- pre-escaped with esc_attr().
			. $checked // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static safe string.
			. ' />';

		echo esc_html( $field['label'] );
		echo '</label>';
	}

	/**
	 * Render a complete checkbox field row for frontend forms.
	 *
	 * Overrides the base implementation because CheckboxField::render_field_input()
	 * already wraps the <input> inside a <label> — adding a separate label element
	 * before it would create a duplicate and break the click-target association.
	 *
	 * @param array  $field Field definition array.
	 * @param string $id    HTML id attribute for the input.
	 * @param string $name  HTML name attribute for the input.
	 * @param mixed  $value Current field value.
	 *
	 * @return void
	 */
	public function render_form_field(
		array $field,
		string $id,
		string $name,
		$value = ''
	): void {
		$placeholder = $field['placeholder'] ?? '';
		$required    = ! empty( $field['required'] );
		$description = $field['description'] ?? '';
		?>
		<div class="ambh-form-field ambh-form-field--checkbox">
			<?php $this->render_field_input( $field, $id, $name, (string) $value, $placeholder, $required, 'ambh-form-field__input' ); ?>
			<?php if ( $description ) : ?>
				<p class="ambh-form-field__description"><?php echo esc_html( $description ); ?></p>
			<?php endif; ?>
			<span class="ambh-form-field__error" aria-live="polite"></span>
		</div>
		<?php
	}
}

