<?php
/**
 * Галерея
 *
 *
 * 1. Правка разметки галереи под bootstrap
 * 2. Добавление class="thumbnail img-thumbnail" к медиафайлам
 * 3. Правка номеров стобцов (+12 -5 -7 -8 -9) для шорткода галереи
 *
 *
 * @author veselka.ua
 * @version 0.3
 *
 * @package veselka_ua/themes
 */

class ImgGalleryOwl {

	/**
	 * Объект обработки библиотек.
	 * @type object
	 */
	private $lib_kit;


	public function __construct() {


		if( !is_admin() ) {
			/**
			 * Хук для получение объекта с общими методами.
			 */
			add_action( 'wp_lib_construct_exchange', [$this, 'get_wp_lib_construct'], 29, 1 );

			// Библиотека owl.
			add_action( 'after_setup_theme', [$this, 'add_owl_gallery'] );
		}


		/**
		 * Правка разметки галереи
		 */
		remove_shortcode('gallery');
		add_shortcode('gallery', [$this, 'wp_owl_gallery']);
		/**
		 * Не использовать стиль для галереи по умолчанию
		 */
		add_filter('use_default_gallery_style', '__return_null');
		/**
		 * Галерея
		 */
		add_theme_support('owl-gallery');
		/**
		 * Колонки нативной галереи
		 */
		add_action( 'wp_enqueue_media', [$this, 'media_gallery_additional_columns'] );

		/**
		 * Хук для показа нативной галереи
		 */
		add_action( 'gallery_shortcode', [$this, 'get_gallery_shortcode'], 10, 0 );

		/**
		 * Хук для показа нативной галереи
		 */
		add_action( 'ordered_gallery_shortcode', [$this, 'get_ordered_gallery_shortcode'], 10, 1 );
	}


//////////////////// Публичные методы ////////////////////


	/**
	 * функция хука для получения общего объекта по ссылке.
	 *
	 * Сортировка.
	 *
	 * @param object $lib_construct
	 * @return void
	 */
	final public function get_wp_lib_construct( $lib_construct ){
		// Объект с общими методами в локальное свойство
		$this->lib_kit = $lib_construct;
	}


	/**
	 * Добавить owl.
	 *
	 * @param void
	 * @return void
	 */
	final public function add_owl_gallery() {

		$this->lib_kit->set_lib_list('owl.carousel','css');
		$this->lib_kit->set_lib_list(['owl.carousel' => 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js'],'js');
		$this->lib_kit->set_new_lib('owl.gallery', ['page-template-contact.php']);

	}


	/**
	 * Обертка для получения разметки галереи.
	 * 
	 * @param void
	 * @return string $result_set
	 */
	final public function get_gallery_shortcode() {

		$result_set = "\t\t\t\t\t\t" . '<div class="owl-gallery-wrapper">';
		$result_set .= do_shortcode('[gallery]');
		$result_set .= "\t\t\t\t\t\t" . '</div>';

		echo $result_set;
	}


	/**
	 * Обертка для получения разметки галереи.
	 * 
	 * @param $ids
	 * @return string $result_set
	 */
	final public function get_ordered_gallery_shortcode($ids) {

		$result_set = "\t\t\t\t\t\t" . '<div class="owl-gallery-wrapper">';
		$result_set .= do_shortcode('[gallery ids="'.$ids.'"]');
		$result_set .= "\t\t\t\t\t\t" . '</div>';

		echo $result_set;
	}

	/**
	 * Правка разметки галереи для owl carousel.
	 *
	 * @param array $attr
	 * @return string $output
	 */
	final public function wp_owl_gallery($attr) {
		$post = get_post();

		static $instance = 0;
		$instance++;

		$ids = get_post_meta( $post->ID, 'gallery', true );
		//var_dump($post->ID);
		if( (bool)$ids && empty($attr['ids']) ) {
			$attr['ids'] = $ids;
		}

		if( !empty($attr['ids']) ) {
			if (empty($attr['orderby'])) {
				$attr['orderby'] = 'post__in';
			}
			$attr['include'] = $attr['ids'];
		}

		$output = apply_filters('post_gallery', '', $attr);

		if( $output != '' ) {
			return $output;
		}

		if( isset($attr['orderby']) ) {
			$attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
			if( !$attr['orderby'] ) {
				unset($attr['orderby']);
			}
		}

		extract(shortcode_atts(
			[
				'orderby'		=> 'post__in',
				'order'			=> 'menu_order ID',
				'id'			=> $post->ID,
				'itemtag'		=> '',
				'icontag'		=> '',
				'captiontag'	=> '',
				'columns'		=> 1,
				'size'			=> 'medium',
				'include'		=> '',
				'exclude'		=> '',
				'link'			=> 'none'
			],
			$attr
		));

		$id = intval($id);
		/*$columns = (12 % $columns == 0) ? $columns: 3;
		$grid = sprintf('col-sm-%1$s col-lg-%1$s', 12/$columns);*/

		if( $order === 'RAND' ) {
			$orderby = 'none';
		}

		if( !empty($include) ) {
			$_attachments = get_posts([
				'include'			=>	$include,
				'post_status'		=>	'inherit',
				'post_type'			=>	'attachment',
				'post_mime_type'	=> 'image',
				'order'				=>	$order,
				'orderby'			=>	$orderby,
			]);

			$attachments = [];
			foreach( $_attachments as $key => $val ) {
				$attachments[$val->ID] = $_attachments[$key];
			}
		} elseif( !empty($exclude) ) {
			$attachments = get_children([
				'post_parent'		=>	$id,
				'exclude'			=>	$exclude,
				'post_status'		=>	'inherit',
				'post_type'			=>	'attachment',
				'post_mime_type'	=>	'image',
				'order'				=>	$order,
				'orderby'			=>	$orderby,
			]);
		} else {
			$attachments = get_children([
				'post_parent'		=>	$id,
				'post_status'		=>	'inherit',
				'post_type'			=>	'attachment',
				'post_mime_type'	=>	'image',
				'order'				=>	$order,
				'orderby'			=>	$orderby,
			]);
		}

		if( empty($attachments) ) {
			return '';
		}

		if( is_feed() ) {
			$output = PHP_EOL;
			foreach( $attachments as $att_id => $attachment ) {
				$output .= wp_get_attachment_link($att_id, $size, true) . PHP_EOL;
			}
			return $output;
		}

		// Full width gallery
		if( is_page_template('page-template-full-gallery.php') ) {
			$columns = 1;
			$size = 'hd';
		}


		$unique = (get_query_var('page')) ? $instance . '-p' . get_query_var('page'): $instance;
		$output = '<div id="gallery-' . $id . '-' . $unique . '" data-row="'.$columns.'" class="gallery responsive-carousel">';
		$output .= PHP_EOL . "\t\t\t\t\t\t" . '<div class="owl-carousel owl-gallery">';

		$i = 0;
		foreach ($attachments as $id => $attachment) {
			switch($link) {
				case 'file':
					//$image = wp_get_attachment_link($id, $size, false, false);
					$image_attributes_ico = wp_get_attachment_image_src( $id, $size );
					$image_attributes_full = wp_get_attachment_image_src( $id, 'full' );
					$alt = get_post_meta($id, '_wp_attachment_image_alt', true);
					$image = PHP_EOL . "\t\t\t\t\t\t\t" . '<a href="' . $image_attributes_full[0] . '" title="' . $alt . '">';
					$image .= PHP_EOL . "\t\t\t\t\t\t\t\t" . '<img class="img-responsive" src="' . $image_attributes_ico[0] .'" alt="' . $alt . '">';
					$image .= PHP_EOL . "\t\t\t\t\t\t\t" . '</a>'; 
					break;
				case 'none':
					$image_attributes = wp_get_attachment_image_src( $id, $size );
					$alt = get_post_meta($id, '_wp_attachment_image_alt', true);
					$image = PHP_EOL . "\t\t\t\t\t\t\t\t" . '<img class="img-responsive" src="' . $image_attributes[0] .'" alt="' . $alt . '">';
					//wp_get_attachment_image($id, $size, false, array('class' => 'thumbnail img-thumbnail'));
					break;
				default:
					$image_attributes = wp_get_attachment_image_src( $id, $size );
					$alt = get_post_meta($id, '_wp_attachment_image_alt', true);
					$image = PHP_EOL . "\t\t\t\t\t\t\t\t" . '<img class="img-responsive" src="' . $image_attributes[0] .'" alt="' . $alt . '">';
					break;
			}
			/*$output .= ($i % $columns == 0) ? '<div class="row gallery-row">': '';*/
			$output .= PHP_EOL . "\t\t\t\t\t\t\t" . '<div class="clearfix">' . $image;

			/*if (trim($attachment->post_excerpt)) {
				$output .= '<div class="highslide-caption">' . wptexturize($attachment->post_excerpt) . '</div>';
			}*/

			$output .= PHP_EOL . "\t\t\t\t\t\t\t" . '</div><!-- /.clearfix -->';
			$i++;
			/*$output .= ($i % $columns == 0) ? '</div>' : '';*/
		}

		/*$output .= ($i % $columns != 0 ) ? '</div>' : '';*/
		$output .= PHP_EOL . "\t\t\t\t\t\t" . '</div><!-- /.owl-carousel -->';
		$output .= PHP_EOL . "\t\t\t\t\t" . '</div><!-- /.responsive-carousel -->';

		return $output;
	}


	/**
	 * Колонки нативной галереи.
	 *
	 * @param void
	 * @return void
	 */
	final public function media_gallery_additional_columns(){
		add_action( 'admin_print_footer_scripts', array($this, 'media_gallery_additional_columns_script'), 999);
	}


	/**
	 * JS.
	 *
	 * @param void
	 * @return string
	 */
	final public function media_gallery_additional_columns_script(){
	?>
	<script type="text/javascript">
	jQuery(function(){
		if(wp.media.view.Settings.Gallery){
			wp.media.view.Settings.Gallery = wp.media.view.Settings.extend({
				className: "collection-settings gallery-settings",
				template: wp.media.template("gallery-settings"),
				render:	function() {
					wp.media.View.prototype.render.apply( this, arguments );
					// Append an option for 12 columns if not already present...
					var $s = this.$('select.columns');
					$s.find('option[value="2"]').remove();
					$s.find('option[value="3"]').remove();
					$s.find('option[value="4"]').remove();
					$s.find('option[value="5"]').remove();
					$s.find('option[value="6"]').remove();
					$s.find('option[value="7"]').remove();
					$s.find('option[value="8"]').remove();
					$s.find('option[value="9"]').remove();
					// Select the correct values.
					_( this.model.attributes ).chain().keys().each( this.update, this );
					return this;
				}
			});
		}
	});
	</script>
	<?php
	}




} // end ImgGalleryOwl
?>