<?php

namespace TotalThemeCore\WPBakery\Params;

defined( 'ABSPATH' ) || exit;

/**
 * WPBakery Param => Select Buttons.
 */
final class Select_Buttons {

	/**
	 * Field output.
	 */
	public static function output( $settings, $value ) {
		$default_value = ! empty( $settings['std'] ) ? $settings['std'] : '';
		$choices       = $settings['choices'] ?? $settings['param_name'] ?? false;

		// Get choices
		if ( $choices && class_exists( '\TotalThemeCore\Vcex\Setting_Choices' ) ) {
			$choices = (new \TotalThemeCore\Vcex\Setting_Choices( $choices, $settings ))->get_choices();
		}

		// Choices isn't an array so display a single text input
		if ( ! is_array( $choices ) ) {
			return '<input type="text" class="wpb_vc_param_value '
				. esc_attr( $settings['param_name'] ) . ' '
				. esc_attr( $settings['type'] ) . '" name="' . esc_attr( $settings['param_name'] ) . '" value="' . esc_attr( $value ) . '">';
		}

		// No value set default
		if ( ! $value ) {
			if ( $default_value ) {
				$value = $default_value;
			} else {
				$temp_choices = $choices;
				reset( $temp_choices );
				$value = key( $temp_choices );
			}
		}

		// Output select buttons
		$html = '<div class="vcex-select-buttons-param vcex-custom-select vcex-noselect">';

			// Loop through choices
			foreach ( $choices as $id => $label ) {
				if ( $default_value && '' === $id ) {
					continue; // remove the "Default" empty option when the param has a defined default
				}
				$choice_class = [ 'vcex-opt' ];
				if ( $id == $value ) {
					$choice_class[] = 'vcex-active';
				}
				if ( $id ) {
					$choice_class[] = 'vcex-opt-' . sanitize_html_class( $id );
				}
				if ( ! defined( 'TOTAL_THEME_ACTIVE' ) ) {
					$label = str_replace( 'ticon', 'fa', $label );
				}
				$html .= '<button type="button" class="' . esc_attr( implode( ' ', $choice_class ) ) . '" data-value="' . esc_attr( $id )  . '">' . wp_kses_post( $label ) . '</button>';
			}

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

		$html .= '</div>';

		// Display notice
		if ( ! empty( $settings['notice'] ) ) {
			$html .= '<div class="vcex-vc-notice vc_description vc_clearfix">' . wp_kses_post( $settings['notice'] ) . '</div>';
		}

		// Return param
		return $html;
	}

}
