<?php

namespace Merkulove\Readabler\Unity\Controls;

/** Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

class Control {

	/**
	 * Build HTML attributes string from associative array.
	 *
	 * @param array $atts
	 *
	 * @return string
	 */
	protected static function attributes( array $atts ): string {

		// Return early if no attributes are provided
		if ( empty( $atts ) ) {
			return '';
		}

		// Build attributes string
		$attributes = '';
		foreach ( $atts as $key => $value ) {
			$attributes .= esc_attr( $key ) . '="' . esc_attr( $value ) . '" ';
		}

		return trim( $attributes );

	}

	/**
	 * Render helper text.
	 *
	 * @param array $props
	 *
	 * @return void
	 */
	protected static function helper_text( array $props = [] ): string {

		// Return early if no helper text is provided
		if ( ! isset( $props['helper_text'] ) ) {
			return '';
		}

		// Old-fashioned way
		if ( is_string( $props['helper_text'] ) && trim( $props['helper_text'] ) !== '' ) {
			return wp_sprintf(
				'<div class="mdc-text-field-helper-line">
					<div class="mdc-text-field-helper-text mdc-text-field-helper-text--persistent">%s</div>
				  </div>',
				wp_kses_post( $props['helper_text'] )
			);
		}

		// New-fashioned way for display saved values
		if ( is_array( $props['helper_text'] ) ) {

			// Prefix and Suffix
			$prefix = $props['helper_text']['prefix'] ?? '';
			$suffix = $props['helper_text']['suffix'] ?? '';

			// Unit
			$unit = '';
			if ( ! empty( $props['helper_text']['unit'] ) ) {
				$unit = ' ' . esc_html( $props['helper_text']['unit'] );
			}

			// Determine value to display. If value equals default and default_fallback is set, use default_fallback.
			$value = $props['value'] ?? '';
			if ( $value === $props['default'] && isset($props['helper_text']['default_fallback']) ) {
				$value = $props['helper_text']['default_fallback'];
				$unit = '';
			}

			return wp_sprintf(
				'<div class="mdc-text-field-helper-line">
					<div class="mdc-text-field-helper-text mdc-text-field-helper-text--persistent">
						%1$s <strong>%2$s</strong><strong>%3$s</strong> %4$s
					</div>
				  </div>',
				esc_html( $prefix ),
				esc_attr( $value ),
				esc_html( $unit ),
				esc_html( $suffix )
			);
		}

		return '';

	}

}
