<?php

define( 'KD_SUPPORT_POST_FORMATS_URI', KD_SUPPORT_URI . 'post-formats/' );

if ( ! class_exists( 'Kd_Post_Formats' ) ) {

	class Kd_Post_Formats {

		public $posts_type = array('post');

		/**
		 * @var array
		 */
		public $advance_settings = array(
			'image_size' => array(
				'image'         => 'large',
				'gallery'       => 'large',
				'gallery_popup' => 'large',
				'gallery_slide' => 'large'
			)
		);

		/**
		 * @var
		 */
		public $post_formats;

		public function __construct () {
			$this->advance_settings = apply_filters( 'kd_change_image_size', $this->advance_settings );

			add_action( 'init', array( $this, 'init' ) );
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), 100 );
			add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
			add_action( 'edit_form_after_title', array( $this, 'admin_markup' ) );
			add_action( 'save_post', array( $this, 'save_post' ) );
			add_shortcode( 'kd_formats_ui', array( $this, 'kd_render_formats_ui' ) );
		}

		public function init () {

			$this->posts_type = apply_filters( 'kd_format_ui_posts_type', $this->posts_type );

			if ( ! current_theme_supports( 'post-formats' ) ) {
				add_theme_support( 'post-formats', array(
					'image',
					'gallery',
					'audio',
					'quote',
					'video'
				) );
			}

		}

		public function enqueue_scripts () {

			wp_register_style( 'justifiedGallery', KD_SUPPORT_POST_FORMATS_URI . 'frontend/justified-gallery/justifiedGallery.min.css', KD_SUPPORT_VER, 'all' );
			wp_register_style( 'magnificpopup', KD_SUPPORT_POST_FORMATS_URI . 'frontend/magnific-popup/magnific-popup.css', KD_SUPPORT_VER, 'all' );
			wp_register_style( 'owlcarousel', KD_SUPPORT_POST_FORMATS_URI . 'frontend/owl/owl.carousel.css', KD_SUPPORT_VER, 'all' );
			wp_register_style( 'kd_style', KD_SUPPORT_POST_FORMATS_URI . 'frontend/style.css', array(), KD_SUPPORT_VER, 'all' );

			wp_register_script( 'justifiedGallery', KD_SUPPORT_POST_FORMATS_URI . 'frontend/justified-gallery/jquery.justifiedGallery.min.js', array( 'jquery' ), KD_SUPPORT_VER, true );
			wp_register_script( 'magnificpopup', KD_SUPPORT_POST_FORMATS_URI . 'frontend/magnific-popup/magnific-popup.min.js', array( 'jquery' ), KD_SUPPORT_VER, true );
			wp_register_script( 'owlcarousel', KD_SUPPORT_POST_FORMATS_URI . 'frontend/owl/owl.carousel.min.js', array( 'jquery' ), KD_SUPPORT_VER, true );
			wp_register_script( 'kd_formats_ui_script', KD_SUPPORT_POST_FORMATS_URI . 'frontend/script.js', array( 'jquery' ), KD_SUPPORT_VER, true );

			if ( ! wp_script_is( 'justifiedGallery' ) ) {
				wp_enqueue_style( 'justifiedGallery' );
				wp_enqueue_script( 'justifiedGallery' );
			}

			if ( ! wp_script_is( 'magnificPopup' ) ) {
				wp_enqueue_style( 'magnificpopup' );
				wp_enqueue_script( 'magnificpopup' );
			}

			if ( ! wp_script_is( 'owlcarousel' ) ) {
				wp_enqueue_style( 'owlcarousel' );
				wp_enqueue_script( 'owlcarousel' );
			}

			wp_enqueue_style( 'kd_style' );
			wp_enqueue_script( 'kd_formats_ui_script' );

		}

		public function admin_enqueue_scripts () {

			$screen = get_current_screen();

			if ( isset( $screen ) && isset( $screen->id ) && in_array($screen->id, $this->posts_type) ) {

				wp_register_style( 'kd__formats_ui_style', KD_SUPPORT_POST_FORMATS_URI . 'backend/style.css', array(), KD_SUPPORT_VER, false );
				wp_enqueue_style( 'kd__formats_ui_style' );

				wp_register_script( 'kd__formats_ui_script', KD_SUPPORT_POST_FORMATS_URI . 'backend/script.js', array( 'jquery' ), KD_SUPPORT_VER, true );
				wp_enqueue_script( 'kd__formats_ui_script' );
			}

		}

		public function save_post ( $post_id ) {
			if ( isset( $_POST['post_type'] ) && in_array($_POST['post_type'], $this->posts_type) && isset( $_POST['kd_post_formats'] ) ) {
				update_post_meta( $post_id, "kd_post_formats", $_POST['kd_post_formats'] );
			}
		}

		public function admin_markup () {
			global $post;

			if ( empty( $post->post_type ) ) {
				return false;
			}
			if ( !in_array($post->post_type, $this->posts_type)) {
				return;
			}

			$kd_post_formats = get_theme_support( 'post-formats' );

			if ( empty( $kd_post_formats ) ) {
				return;
			}
			$kd_post_formats = array_merge( array( 'standard' ), $kd_post_formats[0] );
			$kd_post_formats = apply_filters('kd_custom_post_formats', $kd_post_formats, $post->post_type);
			$kd_post_meta    = get_post_meta( $post->ID, 'kd_post_formats', true );
			if ( empty( $kd_post_meta ) ) {
				$kd_post_meta = array();
			}

			$kd_post_meta = array_merge( array(
				'standard' => '',
				'aside'    => '',
				'link'     => '',
				'status'   => '',
				'audio'    => '',
				'chat'     => '',
				'gallery'  => array(
					'images' => '',
					'type'   => ''
				),
				'image'    => '',
				'quote'    => array(
					'content' => '',
					'author'  => '',
					'url'     => ''
				),
				'video'    => ''
			), $kd_post_meta );
			?>
			<div id="kd-handle-post-format">
				<?php $this->control_tabs( $kd_post_formats, get_post_format( $post->ID ) ); ?>

				<div id="kd-handle-post-format">
					<?php
					foreach ( $kd_post_formats as $format ) {
						$function = 'markup_item_' . $format;
						call_user_func( array( $this, $function ), $kd_post_meta[ $format ] );
					}
					?>
				</div>
			</div>
			<?php
		}

		public function control_tabs ( $settings, $post_format ) {
			?>
			<div id="kd-controls-post-format" data-format="<?php echo esc_attr( $post_format ); ?>">
				<ul class="clearfix">
					<?php
					foreach ( $settings as $format ) {
						?>
						<li class="kd-control-item" data-format="<?php echo esc_attr( $format ); ?>">
							<a href="#kd-format-<?php echo esc_attr( $format ); ?>"><?php echo $format; ?></a>
						</li>
						<?php
					}
					?>
				</ul>
			</div>
			<?php
		}

		public function markup_item_standard ( $settings ) {

		}

		public function markup_item_aside ( $settings ) {

		}

		public function markup_item_audio ( $settings ) {
			?>
			<div id="kd-post-format-audio" class="kd-format-block">
				<div class="kd-format-field">
					<label for="kd-audio-field-url"><strong><?php esc_html_e( 'Audio URL (oEmbed) or Embed Code', 'kendytheme' ); ?></strong></label>
					<textarea name="kd_post_formats[audio]" id="kd-audio-field-url" tabindex="1"><?php echo esc_textarea( $settings ); ?></textarea>
				</div>
			</div>
			<?php
		}

		public function markup_item_chat ( $settings ) {

		}

		public function markup_item_gallery ( $settings ) {
			$arr_images = explode( ',', $settings['images'] );
			$type       = $settings['type'];
			?>
			<div id="kd-post-format-gallery" class="kd-format-block">
				<div class="kd-format-field">
					<label><strong><?php esc_html_e( 'Gallery Image', 'kendytheme' ); ?></strong></label>
					<div class="kd-gallery-field-images">
						<div class="gallery clearfix">
							<ul class="list-kd-image-media">
								<?php
								foreach ( $arr_images as $image ) {
									if ( ! empty( $image ) ) {
										$thumbnail = wp_get_attachment_image_src( $image, 'thumbnail' );
										echo sprintf( '<li class="kd-image" data-id="%1s"><img src="%2s"/><div class="kd-control-wrap"><i class="kd-edit dashicons dashicons-edit"></i><i class="kd-close dashicons dashicons-no-alt"></i></div></li>', esc_attr( $image ), esc_url( $thumbnail[0] ) );
									}
								}
								?>
							</ul>
						</div>
						<div class="kd-button-media" data-parent=".kd-gallery-field-images > .gallery">
							<input class="kd-media-value" type="hidden" name="kd_post_formats[gallery][images]" value="<?php echo esc_attr( $settings['images'] ); ?>" />
							<a href="#" class="button kd-button"><?php esc_html_e( 'Select Image', 'kendytheme' ); ?></a>
						</div>
					</div>
				</div>

				<?php
				$options = array(
					'gallery' => __( 'Tiled Gallery', 'kendytheme' ),
					'slideshow' => __( 'SlideShow', 'kendytheme' )
				);
				$options = apply_filters('kd_post_format_gallery_layout', $options);
				if (!empty($options)) {
					if (empty($type)) {
						$arr_key = array_keys($options);
						$type = $arr_key[0];
					}
					?>
					<div class="kd-format-field">
						<label><strong><?php esc_html_e( 'Gallery Layout', 'kendytheme' ) ?></strong></label>
						<div class="kd-gallery-field-type">
							<select>
								<?php
								foreach ($options as $key => $layout) {
									?>
									<option value="<?php echo esc_attr($key); ?>"><?php echo $layout; ?></option>
									<?php
								}
								?>
							</select>
							<input class="kd-type-gallery" name="kd_post_formats[gallery][type]" type="hidden" value="<?php echo esc_attr( $type ); ?>" />
						</div>
					</div>
					<?php
				}
				do_action('kd_post_format_gallery_after', $settings);
				?>
			</div>
			<?php
		}

		public function markup_item_image ( $settings ) {
			?>
			<div id="kd-post-format-image" class="kd-format-block">
				<div class="kd-format-field">
					<label><strong><?php esc_html_e( 'Choose Image', 'kendytheme' ); ?></strong></label>
					<div class="kd-image-field-id">
						<div class="image-show">
							<ul class="list-kd-image-media">
								<?php
								if ( ! empty( $settings ) ) {
									$thumbnail = wp_get_attachment_image_src( $settings, 'thumbnail' );
									echo sprintf( '<li class="kd-image" data-id="%1s"><img src="%2s"/><div class="kd-control-wrap"><i class="kd-edit dashicons dashicons-edit"></i><i class="kd-close dashicons dashicons-no-alt"></i></div></li>', esc_attr( $settings ), esc_url( $thumbnail[0] ) );
								}
								?>
							</ul>
						</div>
						<div class="kd-button-media" data-parent=".kd-image-field-id > .image-show" data-multiple="false">
							<input class="kd-media-value" type="hidden" name="kd_post_formats[image]" value="<?php echo esc_attr( $settings ); ?>" />
							<a href="#" class="button kd-button"><?php esc_html_e( 'Select Image', 'kendytheme' ); ?></a>
						</div>
					</div>
				</div>
			</div>
			<?php
		}

		public function markup_item_quote ( $settings ) {
			?>
			<div id="kd-post-format-quote" class="kd-format-block">
				<div class="kd-format-field">
					<label for="kd-quote-field-content"><strong><?php esc_html_e( 'Quote', 'kendytheme' ); ?></strong></label>
					<textarea id="kd-quote-field-content" name="kd_post_formats[quote][content]" tabindex="1"><?php echo esc_textarea( $settings['content'] ); ?></textarea>
				</div>
				<div class="kd-format-field">
					<label for="kd-quote-field-author"><strong><?php esc_html_e( 'Author', 'kendytheme' ); ?></strong></label>
					<input id="kd-quote-field-author" type="text" name="kd_post_formats[quote][author]" value="<?php echo esc_attr( $settings['author'] ); ?>" tabindex="1" />
				</div>
				<div class="kd-format-field">
					<label for="kd-quote-field-url"><strong><?php esc_html_e( 'Link', 'kendytheme' ); ?></strong></label>
					<input id="kd-quote-field-url" type="text" name="kd_post_formats[quote][url]" value="<?php echo esc_url( $settings['url'] ); ?>" tabindex="1" />
				</div>
			</div>
			<?php
		}

		public function markup_item_status ( $settings ) {

		}

		public function markup_item_video ( $settings ) {
			?>
			<div id="kd-post-format-video" class="kd-format-block">
				<div class="kd-format-field">
					<div class="kd-icon-wrap clearfix">
						<label for="kd-video-field-url"><strong><?php esc_html_e( 'Enter Youtube/Vimeo URL or Embed Code.', 'kendytheme' ); ?></strong></label>
						<textarea id="kd-video-field-url" name="kd_post_formats[video]" tabindex="1"><?php echo esc_textarea( $settings ); ?></textarea>
					</div>
				</div>
			</div>

			<?php
		}

		public function kd_render_formats_ui () {
			$post_id = get_the_ID();

			$kd_formats_ui = get_post_meta( $post_id, 'kd_post_formats', true );
			$post_format   = get_post_format( $post_id );
			if ( empty( $kd_formats_ui ) || empty( $post_format ) || empty( $kd_formats_ui[ $post_format ] ) ) {
				return;
			}

			$function = 'render_item_' . $post_format;
			?>
			<div class="kd-wrap-shortcode">
				<?php
				$is_custom = apply_filters('kd_post_format_' . $post_format, '', $kd_formats_ui[ $post_format ], $this);

				if (!$is_custom) {
					call_user_func( array( $this, $function ), $kd_formats_ui[ $post_format ] );
				}

				?>
			</div>
			<?php
		}

		public function render_item_aside ( $settings ) {

		}

		public function render_item_gallery ( $settings ) {

			if ( empty( $settings['images'] ) ) {
				return;
			}
			$images     = explode( ',', $settings['images'] );
			$image_size = $this->advance_settings['image_size']['gallery'];
			$class      = 'kd-gallery kd-magnific-popup';
			if ( $settings['type'] == 'slideshow' ) {
				$class .= ' kd-images-slider ';
				$image_size = $this->advance_settings['image_size']['gallery_slide'];
			} else {
				$class .= ' kd-tiled';
			}
			?>
			<div class="<?php echo esc_attr( $class ); ?>">
				<?php
				foreach ( $images as $id ) {
					$src       = $this->get_image_src( $id, $image_size );
					$src_popup = $this->get_image_src( $id, $this->advance_settings['image_size']['gallery_popup'] );

					if ( ! empty( $src ) ) {
						?>
						<div class="kd-item-image" style="background-image: url(<?php echo esc_url( $src ); ?>)">
							<a class="item" href="<?php echo esc_url( $src_popup ); ?>" data-caption="<?php echo esc_attr( get_the_title( $id ) ); ?>">
								<img src="<?php echo esc_url( $src ); ?>" alt="<?php echo esc_attr( get_the_title( $id ) ); ?>" title="<?php echo esc_attr( get_the_title( $id ) ); ?>" />
							</a>
						</div>

						<?php
					}
				}
				?>
			</div>
			<?php
		}

		public function render_item_link ( $settings ) {

		}

		public function render_item_image ( $settings ) {
			if ( ! empty( $settings ) ) {
				$image = $this->get_image_src( $settings, $this->advance_settings['image_size']['image'] );
				if ( ! empty( $image ) ) {
					?>
					<div class="image kd-image">
						<img src="<?php echo esc_url( $image ); ?>" alt="<?php echo esc_attr( get_the_title( $settings ) ); ?>" title="<?php echo esc_attr( get_the_title( $settings ) ); ?>" />
					</div>
					<?php
				}
			}
		}

		public function render_item_quote ( $settings ) {

			if ( empty( $settings['content'] ) && empty( $settings['author'] ) ) {
				return;
			}
			?>
			<blockquote class="kd-quote">
				<?php
				if ( ! empty( $settings['content'] ) ) {
					?>
					<p>
						<?php echo wp_kses_post( $settings['content'] ); ?>
					</p>
					<?php
				}
				?>
				<?php
				if ( ! empty( $settings['author'] ) ) {
					if ( ! empty( $settings['url'] ) ) {
						?>
						<cite>
							<a href="<?php echo esc_url( $settings['url'] ); ?>" target="_blank"><?php echo wp_kses_post( $settings['author'] ); ?></a>
						</cite>
						<?php
					} else {
						echo wp_kses_post( $settings['author'] );
					}
					?>
					<?php
				}
				?>
			</blockquote>
			<?php

		}

		public function render_item_status ( $settings ) {

		}

		public function render_item_video ( $settings ) {

			if ( empty( $settings ) ) {
				return;
			}
			$regex_video = $this->parse_video( $settings );

			if ( empty( $regex_video ) ) {
				return;
			}

			$url = '';

			if ( $regex_video['type'] == 'youtube' ) {
				$url = '//www.youtube.com/embed/' . $regex_video['id'];
			} else if ( $regex_video['type'] == 'vimeo' ) {
				$url = '//player.vimeo.com/video/' . $regex_video['id'] . '?title=0&amp;byline=0&amp;portrait=0';
			}

			if ( empty( $url ) ) {
				return;
			}
			?>
			<div class="kd-video video embed-responsive embed-responsive-16by9">
				<iframe class="embed-responsive-item" src="<?php echo esc_url( $url ); ?>"></iframe>
			</div>
			<?php

		}

		public function render_item_audio ( $settings ) {

			if ( empty( $settings ) ) {
				return;
			}
			preg_match( '/src="([^"]+)"/', $settings, $match );
			$url = $match[1];

			if ( empty( $url ) ) {
				return;
			}
			?>
			<div class="kd-audio video embed-responsive embed-responsive-16by9">
				<iframe class="embed-responsive-item" src="<?php echo esc_url( $url ); ?>"></iframe>
			</div>
			<?php


		}

		public function render_item_chat () {

		}

		public function get_image_src ( $attachment_id, $image_size ) {
			$image = wp_get_attachment_image_src( $attachment_id, $image_size );

			if ( $image ) {
				$image = $image[0];
			}

			return $image;
		}

		public function parse_video ( $url ) {

			if ( strpos( $url, 'youtube' ) > 0 ) {

				preg_match( '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $output_array );

				return array(
					'type' => 'youtube',
					'id'   => $output_array[1]
				);
			}

			if ( strpos( $url, 'vimeo' ) > 0 ) {

				preg_match( '/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/', $url, $output_array );

				return array(
					'type' => 'vimeo',
					'id'   => $output_array[5]
				);
			}

			return false;
		}
	}


}

$GLOBALS['Kd_Post_Formats'] = new Kd_Post_Formats();