<?php
declare( strict_types=1 );

namespace FiboFilters\Filters\Types;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Color
 */
class Color extends Filter {

	/**
	 * This is the name of this filter type.
	 *
	 * @var string
	 */
	protected $filter_type = 'color';

	protected function after_set_values(): void {
		$this->add_colors_data();
	}

	private function add_colors_data() {
		$color_overrides = $this->get_prop( 'color_overrides' );
		$color_values    = wp_list_pluck( $color_overrides, 'value' );

		foreach ( $this->get_values() as $value ) {
			// If using custom source, we could pass value in hex format, and label as a name of color.
			// For custom fields, value will be same as label.
			// For attributes, value will be term_id, and we don't want to use it as a color.
			$color = strpos( $this->get_source(), 'tax_pa_' ) === false && ! is_numeric( $value['value'] ) && $value['label'] !== $value['value'] ? $value['value'] : $value['label'];

			$this->update_value( $value['value_id'], 'color', $color, true );
			$this->update_value( $value['value_id'], 'img_url', '', true );

			if ( in_array( $value['label_url'], $color_values, true ) !== false ) {
				$color_override = $color_overrides[ array_search( $value['label_url'], $color_values, true ) ];
				if ( ! empty( $color_override['color'] ) ) {
					$this->update_value( $value['value_id'], 'color', $color_override['color'], true );
				}
				if ( ! empty( $color_override['img_url'] ) ) {
					$this->update_value( $value['value_id'], 'img_url', $color_override['img_url'], true );
				}
				if ( ! empty( $color_override['label'] ) ) {
					$this->update_value( $value['value_id'], 'label', $color_override['label'] );
				}
			}
		}
	}
}
