<?php
namespace TotalThemeCore\WPBakery\Params;

defined( 'ABSPATH' ) || exit;

/**
 * WPBakery Param => Color Picker.
 *
 * @package TotalThemeCore
 * @version 1.4.5
 */
final class Colorpicker {

	public static function output( $settings, $value ) {
		$is_custom    = true;
		$custom_color = $value;
		$palette      = array();

		if ( function_exists( 'wpex_get_color_palette' ) ) {
			$palette = wpex_get_color_palette();
		}

		if ( 'term_color' === $value || ( ! empty( $value ) && array_key_exists( $value, $palette ) ) ) {
			$is_custom = false;
			$custom_color = '';
		}

		$class = 'vcex-color-param';

		if ( $is_custom ) {
			$class .= ' vcex-color-param--custom';
		}

		if ( 'term_color' === $value ) {
			$class .= ' vcex-color-param--hide-preview';
		}

		$html = '<div class="' . $class . '">';

			// Select Field.
			$html .= '<select class="vcex-color-param__select" name="vcex-color-param__select">';

			$html .= '<option value="" ' . selected( $is_custom, true, false ) . '>' . esc_html( 'Custom', 'total-theme-core' ) . '</option>';

				if ( is_array( $palette ) ) {
					foreach ( $palette as $p_key => $p_val ) {
							$html .= '<option value="' . esc_attr( $p_key ) . '" ' . selected( $value, $p_key, false ) . ' data-color="' . esc_attr( $p_val['color'] ) . '">' . esc_html( $p_val['name'] ) . '</option>';
					}
				}

				if ( isset( $settings['extra_choices'] ) && is_array( $settings['extra_choices'] ) ) {
					foreach ( $settings['extra_choices'] as $label => $val ) {
						$html .= '<option value="' . esc_attr( $val ) . '" ' . selected( $value, $val, false ) . ' data-color="' . esc_attr( $val ) . '">' . esc_html( $label ) . '</option>';
					}
				}

			$html .= '</select>';

			// Color Picker.
			$html .= '<input class="vcex-color-param__picker vc_color-control" name="vcex-color-param__picker" class="vc_color-control" type="text" value="' . esc_attr( $custom_color ) . '">';

			// Color Preview
			$color_preview = $palette[$value]['color'] ?? '';
			$html .= '<div class="vcex-color-param__preview" style="background-color:' . $color_preview . '"></div>';

			// Hidden field.
			$html .= '<input name="' . esc_attr( $settings['param_name'] ) . '" class="wpb_vc_param_value  ' . esc_attr( $settings['param_name'] ) . ' ' . esc_attr( $settings['type'] ) . '_field" type="hidden" value="' . esc_attr( $value ) . '">';

		$html .= '</div>';

		return $html;
	}
}