<?php
/**
 * The radio image customize control allows developers to create a list of image radio inputs.
 *
 * Note, the `$choices` array is slightly different than normal and should be in the form of
 * `array(
 *    $value => array( 'url' => $image_url, 'label' => $text_label ),
 *    $value => array( 'url' => $image_url, 'label' => $text_label ),
 * )`
 *
 * This class is modified from Hybrid Core's radio image control.
 *
 * @author     Justin Tadlock <justin@justintadlock.com>
 * @copyright  Copyright (c) 2008 - 2015, Justin Tadlock
 * @link       http://themehybrid.com/hybrid-core
 * @license    http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 */

/**
 * Radio image customize control.
 */
class Penci_Customize_Control_Radio_Image extends WP_Customize_Control
{
	/**
	 * The type of customize control being rendered.
	 * @var string
	 */
	public $type = 'radio-image';

	/**
	 * Loads the scripts/styles.
	 */
	public function enqueue()
	{


	}

	/**
	 * Add custom parameters to pass to the JS via JSON.
	 */
	public function to_json()
	{
		parent::to_json();

		// We need to make sure we have the correct image URL.
		foreach ( $this->choices as $value => $args )
		{
			$this->choices[$value]['url'] = esc_url( sprintf( $args['url'], get_template_directory_uri(), get_stylesheet_directory_uri() ) );
		}

		$this->json['settings'] = array();
		foreach ( $this->settings as $key => $setting ) {
			$this->json['settings'][ $key ] = $setting->id;
		}



		$this->json['choices'] = $this->choices;
		$this->json['link']    = $this->get_link();
		$this->json['value']   = $this->value();
		$this->json['id']      = $this->id;
	}

	/**
	 * Underscore JS template to handle the control's output.
	 */
	public function content_template()
	{
		?>
		<# if ( ! data.choices ) {
			return;
		} #>

		<# if ( data.label ) { #>
			<span class="customize-control-title">{{ data.label }}</span>
		<# } #>

		<# if ( data.description ) { #>
			<span class="description customize-control-description">{{{ data.description }}}</span>
		<# } #>

		<# _.each( data.choices, function( args, choice ) { #>
			<label>
				<input type="radio" value="{{ choice }}" name="_customize-{{ data.type }}-{{ data.id }}" {{{ data.link }}} <# if ( choice === data.value ) { #> checked="checked"<# } #> />
				<span class="screen-reader-text">{{ args.label }}</span>
				<img class="penci-radio-image {{ data.id }}" src="{{ args.url }}" data-image-preview="{{ args.preview }}" alt="{{ args.label }}" title="{{ args.label }}">
			</label>
		<# } ) #>
		<?php
	}
}
