<?php

namespace TotalThemeCore\WPBakery\Params;

defined( 'ABSPATH' ) || exit;

/**
 * WPBakery Param => Text.
 */
final class Text {

	/**
	 * Param Output.
	 */
	public static function output( $settings, $value ) {
		$param_name        = $settings['param_name'];
		$responsive        = isset( $settings['responsive'] ) && true === $settings['responsive'];
		$is_val_responsive = $responsive && $value && str_contains( $value, ':' );
		$input_type        = $is_val_responsive ? 'hidden' : ( $settings['input_type'] ?? 'text' );
		$datalist_id       = '';

		if ( ! empty( $settings['datalist'] ) && is_array( $settings['datalist'] ) ) {
			$datalist_id = 'datalist-' . esc_attr( $param_name );
		}

		$html = '';

		if ( $responsive ) {
			$html .= '<div class="vcex-param-responsive-field';
				if ( ! $is_val_responsive ) {
					$html .= ' vcex-param-responsive-field--single';
				}
			$html .= '">';
				$responsive_toggle_pressed = $is_val_responsive ? 'true' : 'false';
				$html .= self::render_responsive_form( $value, $settings, $datalist_id );
				$html .= '<button type="button" class="vcex-param-responsive-field__toggle" aria-pressed="' . $responsive_toggle_pressed . '" aria-label="' . esc_attr__( 'Set Responsive Values', 'total-theme-core' ) . '" title="' . esc_attr__( 'Set Responsive Values', 'total-theme-core' ) . '"><svg class="vcex-param-toggle-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" height="20" width="20"><rect x="0" fill="none" width="20" height="20"/><g><path d="M6 2h8c.55 0 1 .45 1 1v14c0 .55-.45 1-1 1H6c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1zm7 12V4H7v10h6zM8 5h4l-4 5V5z"/></g></svg><svg class="vcex-param-toggle-icon-active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" height="20" width="20"><rect x="0" fill="none" width="20" height="20"/><g><path d="M12 5H7V2L1 6l6 4V7h5c2.2 0 4 1.8 4 4s-1.8 4-4 4H7v2h5c3.3 0 6-2.7 6-6s-2.7-6-6-6z"/></g></svg></button>';
				$html .= '<input name="' . esc_attr( $settings['param_name'] ) . '" class="wpb_vc_param_value ' . esc_attr( "{$settings['param_name']} {$settings['type']}_field" ) . '" type="hidden" value="' . esc_attr( $value ) . '">';
			$html .= '</div>';
		} else {
			$html  = '<input';
				$html .= ' name="' . esc_attr( $param_name ) . '"';
				$html .= ' class="wpb_vc_param_value wpb-textinput ' . esc_attr( $param_name ) . ' ' . esc_attr( $settings['type'] ) . '"';
				$html .= ' type="' . esc_attr( $input_type ) . '"';
				$html .= ' value="' . esc_attr( $value ) . '"';
				if ( $datalist_id ) {
					$html .= ' list="' . esc_attr( $datalist_id ) . '"';
				}
				if ( ! empty( $settings['placeholder'] ) ) {
					$html .= ' placeholder="' . esc_attr( $settings['placeholder'] ) . '"';
				}
				// @todo - Add this functionality so we can swap placeholders based on other field values.
				if ( ! empty( $settings['placeholder_rules'] ) ) {
					$html .= ' data-placeholder-rules="' . esc_attr( wp_json_encode( $settings['placeholder_rules'] ) ) . '"';
				}
			$html .= '>';
		}

		if ( $datalist_id ) {
			$html .= '<datalist id="' . esc_attr( $datalist_id ) . '">';
			foreach ( $settings['datalist'] as $option ) {
				$html .= '<option value="' . esc_attr( $option['value'] ) . '"';
				if ( ! empty( $option['label'] ) ) {
					$html .= ' label="' . esc_attr( $option['label'] ) . '"';
				}
				$html .= '></option>';
			}
			$html .= '</datalist>';
		}

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

		if ( ! empty( $settings['choices'] ) ) {
			$html .= self::render_choices( $settings['choices'] );
		}

		return $html;
	}

	/**
	 * Returns responsive field.
	 */
	private static function render_responsive_form( $value, $settings ) {
		$medias = [
			'd'  => [
				'label' => esc_html__( 'Desktop', 'total-theme-core' ),
				'icon'  => 'dashicons dashicons-desktop',
			],
			'tl' => [
				'label' => esc_html__( 'Tablet Landscape', 'total-theme-core' ),
				'icon'  => 'dashicons dashicons-tablet',
			],
			'tp' => [
				'label' => esc_html__( 'Tablet Portrait', 'total-theme-core' ),
				'icon'  => 'dashicons dashicons-tablet',
			],
			'pl' => [
				'label' => esc_html__( 'Phone Landscape', 'total-theme-core' ),
				'icon'  => 'dashicons dashicons-smartphone',
			],
			'pp' => [
				'label' => esc_html__( 'Phone Portrait', 'total-theme-core' ),
				'icon'  => 'dashicons dashicons-smartphone',
			],
		];

		$defaults = array_fill_keys( array_keys( $medias ), '' );

		$field_values = $defaults;
		if ( $value && is_string( $value ) ) {
			if ( str_contains( $value, ':' ) ) {
				// Responsive values
				foreach ( explode( '|', $value ) as $pair ) {
					[ $key, $val ] = array_pad( explode( ':', $pair, 2 ), 2, null );
					if ( '' !== $key && null !== $val && array_key_exists( $key, $field_values ) ) {
						$field_values[ trim( $key ) ] = trim( $val );
					}
				}
			} else {
				// Single value: assign to first media (desktop)
				$first_key = array_key_first( $field_values );
				$field_values[ $first_key ] = $value;
			}
		}

		$html = '<div class="vcex-param-responsive-field__list">';
			$first = true;
			$input_type = $settings['input_type'] ?? 'text';
			$vcex_bks = function_exists( 'vcex_get_css_breakpoints' ) ? vcex_get_css_breakpoints() : [];
			foreach ( $medias as $key => $val ) {
				$field_name = $settings['param_name'] . '[' . $key . ']';
				$icon_class = $val['icon'];
				$html .= '<div class="vcex-param-responsive-field__item">';
					if ( 'pl' === $key || 'tl' === $key ) {
						$icon_class .= ' dashicons--flip';
					}
					$html .= '<div class="vcex-param-responsive-field__icon"><span class="' . esc_attr( $icon_class ) . '"></span></div>';
					$html .= '<label for="' . esc_attr( $field_name ) .'" class="screen-reader-text">' . $medias[ $key ]['label'] . '</label>';
					$html .= '<input id="' . esc_attr( $field_name ) .'" data-vcex-device="' . esc_attr( $key ) . '" value="' . esc_attr( $field_values[ $key ] ) . '" type="' . esc_attr( $input_type ) . '"';
						if ( $first ) {
							if ( ! empty( $settings['placeholder'] ) ) {
								$html .= ' placeholder="' . esc_attr( $settings['placeholder'] ) . '"';
							}
							if ( $vcex_bks ) {
								$html .= 'title="(' . esc_attr__( 'Applies to all screen sizes.', 'total-theme-core' ) . ')"';
							}
							$first = false;
						} else {
							if ( ! empty( $vcex_bks[ $key ] ) ) {
								$html .= 'title="(max-width: ' . esc_attr( $vcex_bks[ $key ] ) . ')"';
							}
						}
					$html .= '>';
				$html .= '</div>';
			}
		$html .= '</div>';

		return $html;
	}

	/**
	 * Render allowed vars.
	 */
	private static function render_choices( $choices ): string {
		switch ( $choices ) {
			case 'font_size':
				if ( function_exists( 'wpex_utl_font_sizes' ) ) {
					$font_sizes = array_keys( wpex_utl_font_sizes() );
					$choices = array_combine( $font_sizes, $font_sizes );
				}
				break;
			case 'flex_basis':
				$choices = [ '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12' ];
				$label = esc_html__( 'Preset Columns: %s', 'total-theme-core' );
				break;
		}
		if ( ! is_array( $choices ) ) {
			return '';
		}
		$links = [];
		foreach ( $choices as $var_key => $var_val ) {
			if ( '' !== $var_key && $var_val ) {
				if ( ! is_scalar( $var_key ) ) {
					$var_key = $var_val;
				}
				$aria_label = sprintf(
					esc_attr__( 'Insert %s preset value into the previous field', 'total-theme-core' ),
					$var_val
				);
				$links[] = '<a class="vc-field-preset-insert-link" href="#" role="button" aria-label="' . esc_attr( $aria_label ) . '" data-value="' . esc_attr( $var_key ) . '">' . esc_html( $var_val ) . '</a>';
			}
		}
		if ( empty( $links ) ) {
			return '';
		}
		$label = $label ?? esc_html__( 'Presets: %s', 'total-theme-core' );
		$groups_output[] = sprintf( $label, implode( ', ', $links ) );
		return '<div class="vc_description vc_clearfix">' . implode( '<br>', $groups_output ) . '</div>';
	}

}
