<?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 Slider extends Control {

	/**
	 * Render slider field.
	 *
	 * @param $value - Current value. Required.
	 * @param $value_min - The min value the slider can have. Optional.
	 * @param $value_max - The max value the slider can have. Optional.
	 * @param $step - The step value of the slider. Optional.
	 * @param string $label - Label for slider. Optional.
	 * @param string $helper_text - Text after slider. Optional.
	 * @param array $attributes - Additional attributes for select: id, name, class. Optional.
	 * @param bool $discrete - Continuous or Discrete Slider. Optional.
	 * @param int $default
	 *
	 * @return void
	 * @noinspection PhpMissingParamTypeInspection
	 */
	public static function render( $value, $value_min = 0, $value_max = 10, $step = 1, string $label = '', $helper_text = '', $attributes = [], bool $discrete = true, int $default = 0 ) {

		$props = [
			'value'       => $value,
			'value_min'   => $value_min,
			'value_max'   => $value_max,
			'step'        => $step,
			'label'       => $label,
			'helper_text' => $helper_text,
			'attributes'  => $attributes,
			'discrete'    => $discrete,
			'default'     => $default,
		];

		/** @noinspection HtmlUnknownAttribute */
		echo wp_sprintf(
			'<div %s>
                <input %s>
                <div class="mdc-slider__track-container"><div class="mdc-slider__track"></div></div>
                <div class="mdc-slider__thumb-container">
                    <div class="mdc-slider__pin"><span class="mdc-slider__pin-value-marker"></span></div>
                    <svg class="mdc-slider__thumb"><circle></circle></svg>
                    <div class="mdc-slider__focus-ring"></div>
                </div>
            </div>
            %s',
			self::attributes( [
				'id'            => $attributes['id'] ?? '',
				'class'         => self::cssClass( $props ),
				'data-step'     => $step >= 0 ? $step : 1,
				'role'          => 'slider',
				'aria-valuemin' => $value_min,
				'aria-valuemax' => $value_max,
				'aria-valuenow' => $value,
				'aria-label'    => $label,
			] ),
			self::attributes( [
				'id'    => ( $attributes['id'] ?? '' ) . '-input',
				'name'  => $attributes['name'] ?? '',
				'type'  => $attributes['type'] ?? 'hidden',
				'value' => $value,
			] ),
			self::helper_text( $props )
		);
	}

	/**
	 * Build CSS class string for the slider.
	 *
	 * @param $props
	 *
	 * @return string
	 */
	private static function cssClass( $props ): string {

		$class = 'mdc-slider mdc-slider-width ';
		if ( $props['discrete'] ) {
			$class .= ' mdc-slider--discrete ';
		}
		if ( isset( $props['attributes']['class'] ) ) {
			$class .= ' ' . $props['attributes']['class'];
		}

		return trim( $class );

	}


}
