<?php
namespace TotalTheme\Customizer\Controls;

use WP_Customize_Control;
use TotalTheme\Theme_Icons;

defined( 'ABSPATH' ) || exit;

/**
 * Customizer Sortable Control.
 *
 * @package TotalTheme
 * @subpackage Customizer
 * @version 5.5
 */
class Sortable extends WP_Customize_Control {

	/**
	 * The control type.
	 */
	public $type = 'wpex_sortable';

	/**
	 * Enque scripts.
	 */
	public function enqueue() {
		wp_enqueue_script( 'jquery-ui-core' );
		wp_enqueue_script( 'jquery-ui-sortable' );
	}

	/**
	 * The control template.
	 */
	public function render_content() {
		$input_id = '_customize-input-' . $this->id;
		$choices  = $this->choices;
		$values   = $this->value();

		if ( is_string( $choices ) && is_callable( $choices ) ) {
			$choices = (array) call_user_func( $choices );
		}

		if ( is_string( $values ) ) {
			$values = explode( ',', $values );
		}

		?>

		<label class="customize-control-title"><?php echo esc_html( $this->label ); ?></label>

		<?php if ( ! empty( $this->description ) ) : ?>
			<span id="_customize-description-<?php echo esc_attr( $this->id ); ?>" class="description customize-control-description"><?php echo wp_kses_post( $this->description ); ?></span>
		<?php endif; ?>

		<div class="wpex-customize-sortable">

			<ul class="wpex-customize-sortable__list"><?php

				foreach ( $values as $val ) {
					$label = $choices[$val] ?? '';

					if ( $label && is_string( $label ) ) { ?>
						<li data-wpex-value="<?php echo esc_attr( $val ); ?>" class="wpex-customize-sortable__item">
							<span class="wpex-customize-sortable__item-label"><?php echo esc_html( $label ); ?></span>
							<button type="button" class="wpex-customize-sortable__button">
								<?php Theme_Icons::render_icon( 'toggle-on', 'wpex-customize-sortable__icon' ); ?>
								<?php $this->button_reader_text(); ?>
							</button>
						</li>
					<?php
					}
					unset( $choices[$val] );
				}

				foreach ( $choices as $val => $label ) { ?>

					<li data-wpex-value="<?php echo esc_attr( $val ); ?>" class="wpex-customize-sortable__item wpex-customize-sortable__item--disabled">
						<span class="wpex-customize-sortable__item-label"><?php echo esc_html( $label ); ?></span>
						<button type="button" class="wpex-customize-sortable__button">
							<?php Theme_Icons::render_icon( 'toggle-on', 'ticon-rotate-180' ); ?>
							<?php $this->button_reader_text(); ?>
						</button>
					</li>

				<?php }

			?></ul>

		</div>

		<?php
	}

	/**
	 * Toggle button reader text.
	 */
	protected function button_reader_text() {
		echo '<span class="screen-reader-text">' . esc_html__( 'Toggle section on or off.', 'total' ) . '</span>';
	}

}