<?php
namespace SabaiApps\Directories\Component\Form\Field;

use SabaiApps\Directories\Component\Form\Form;

/**
 * RangeField provides a slider for selecting a min/max range.
 * Handles initialization, value processing, and validation for range input.
 */
class RangeField extends SliderField {

	/**
	 * Initializes the Range field as a double slider.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		$data['#slider_type'] = 'double';
		parent::formFieldInit( $name, $data, $form );
	}

	/**
	 * Handles value processing and validation for the Range field on submit.
	 *
	 * @param mixed $value
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldSubmit( &$value, array &$data, Form $form ) {
		if ( ! is_string( $value ) ) {
			$value = null;
			return;
		}

		$value = isset( $value ) ? explode( ';', $value ) : array();
		$value = array(
			'min' => isset( $value[0] ) ? (string) $value[0] : '',
			'max' => isset( $value[1] ) ? (string) $value[1] : '',
		);

		if ( ! strlen( $value['min'] ) && ! strlen( $value['max'] ) ) {
			if ( $form->isFieldRequired( $data ) ) {
				$form->setError( isset( $data['#required_error_message'] ) ? $data['#required_error_message'] : __( 'Please fill out this field.', 'directories-pro' ), $data );
			}
			$value = null;
			return;
		}

		if ( strlen( $value['min'] ) ) {
			$min = $value['min'];
		} else {
			$min = $data['#min_value'];
			unset( $value['min'] );
		}
		if ( strlen( $value['max'] ) ) {
			$max = $value['max'];
		} else {
			$max = $data['#max_value'];
			unset( $value['max'] );
		}
		if ( $max < $min
			|| $max > $data['#max_value']
			|| $min < $data['#min_value']
		) {
			$form->setError( sprintf( __( 'The input range must be between %1$s and %2$s.' ), $data['#min_value'], $data['#max_value'] ), $data );
		}
	}
}
