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

use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Component\Field\IField;

class RangeListRenderer extends AbstractRenderer {

	protected function _fieldRendererInfo() {
		return array(
			'label'            => __( 'Range list', 'directories-pro' ),
			'field_types'      => array( 'number', 'price', 'range' ),
			'default_settings' => array(
				'ranges' => null,
			),
		);
	}

	protected function _fieldRendererSettingsForm( IField $field, array $settings, array $parents = array() ) {
		$field_settings = $field->getFieldSettings();
		return array(
			'ranges' => array(
				'#type'          => 'rangelist',
				'#title'         => __( 'Ranges', 'directories-pro' ),
				'#default_value' => $settings['ranges'],
				'#min_value'     => isset( $field_settings['min'] ) ? $field_settings['min'] : null,
				'#max_value'     => isset( $field_settings['max'] ) ? $field_settings['max'] : null,
				'#weight'        => 1,
			),
		);
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, Entity\Type\IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		$ret = array();
		foreach ( $values as $value ) {
			switch ( $field->getFieldType() ) {
				case 'price':
					$value = $value['value'];
					break;
				case 'range':
					$value = $value['average'] ?? ( $value['min'] + ( $value['max'] - $value['min'] ) / 2 );
					break;
			}
			foreach ( $settings['ranges'] as $range ) {
				if ( $value >= $range['min']
					&& $value <= $range['max']
				) {
					$ret[] = $range['label'];
				}
			}
		}
		return implode( $settings['_separator'], $ret );
	}
}
