<?php

/**
 * Options Field Trait
 *
 * Shared functionality for fields that have options (radio, dropdown).
 *
 * @package AmbassadorHub\CustomFields
 */

namespace AmbassadorHub\Fields\Fields;

use InvalidArgumentException;
use function sanitize_text_field;
use function sprintf;

/**
 * Trait providing options parsing for fields with radio/dropdown options.
 */
trait OptionsFieldTrait {

	/**
	 * Get the settings fields for options-based fields (radio, dropdown).
	 *
	 * @return array
	 */
	public function get_settings_fields(): array {
		return array(
			array(
				'type'        => 'textarea',
				'id'          => 'options_' . $this->id,
				'label'       => __( 'Options', 'ambassadorhub' ),
				'rows'        => 5,
				'placeholder' => "value1|Label 1\nvalue2|Label 2",
				'description' => __( 'One per line. Format: value|Label', 'ambassadorhub' ),
			),
		);
	}

	/**
	 * Validate and process options-based 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']['options'] = self::parse_options( $data['settings']['options'] ?? '' );
		if ( empty( $field['settings']['options'] ) ) {
			throw new InvalidArgumentException( sprintf( 'At least one option is required for %s fields.', esc_html( $this->id ) ) );
		}
	}

	/**
	 * Parse option string into key-value pairs.
	 *
	 * Format: "value1|Label 1\nvalue2|Label 2"
	 *
	 * @param string $options_string Option string.
	 *
	 * @return array<string,string> Parsed options.
	 */
	protected static function parse_options( string $options_string ): array {
		$options = array();
		$lines   = explode( "\n", $options_string );

		foreach ( $lines as $line ) {
			$line = trim( $line );
			if ( ! $line ) {
				continue;
			}

			if ( strpos( $line, '|' ) !== false ) {
				[ $value, $label ] = explode( '|', $line, 2 );
				$value             = sanitize_text_field( trim( $value ) );
				$label             = sanitize_text_field( trim( $label ) );
			} else {
				$value = sanitize_text_field( $line );
				$label = $value;
			}

			if ( $value ) {
				$options[ $value ] = $label;
			}
		}

		return $options;
	}
}
