<?php

/**
 * Class Nevo_Related_Posts
 *
 * @since 0.2.4
 */
class Nevo_Related_Posts {
	static private $_instance = null;

	/**
	 * Get instance
	 *
	 * @return Nevo_Related_Posts
	 */
	static function get_instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	/**
	 * Get related posts
	 *
	 * @param WP_Post|null|int $post
	 * @param string           $by
	 * @param int              $number
	 * @param string           $orderby
	 * @param string           $order
	 *
	 * @return WP_Query|bool
	 */
	function get_related_post( $post = null, $by = 'cat', $number = 3, $orderby = 'date', $order = 'desc' ) {

		$post = get_post( $post );
		if ( ! $post ) {
			return false;
		}

		$current_post_type = get_post_type( $post );
		$query_args          = array(
			'post_type'      => $current_post_type,
			'post__not_in'   => array( $post->ID ),
			'posts_per_page' => $number,
			'orderby'        => $orderby,
			'order'          => $order,
			'no_found_rows'  => true,
			'suppress_filters' => true,
		);

		if ( 'tag' == $by ) {
			$terms    = get_the_tags( $post->ID );
			$term_ids = array();

			if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
				$term_ids = wp_list_pluck( $terms, 'term_id' );
			}
			$query_args['tag__in'] = $term_ids;

		} else {
			$terms    = get_the_category( $post->ID );
			$term_ids = array();

			if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
				$term_ids = wp_list_pluck( $terms, 'term_id' );
			}

			$query_args['category__in'] = $term_ids;
		}

		// Try get related by hand pick.
		$post__in = get_post_meta( $post->ID, '_nevo_related_posts' );
		if ( ! empty( $post__in ) && is_array( $post__in ) ) {
			unset( $query_args['category__in'] );
			unset( $query_args['tag__in'] );

			$query_args['post__in'] = $post__in;
		}

		$query_args = apply_filters( 'nevo/single_post/related_args', $query_args );

		$related_posts = new WP_Query( $query_args );

		return $related_posts;
	}

	/**
	 * Display related post
	 *
	 * @return bool
	 */
	function display() {
		if ( ! is_single() ) {
			return false;
		}

		$number = Nevo()->get_setting( 'post_related_number' );
		$number = absint( $number );
		if ( $number <= 0 ) {
			return false;
		}

		$title   = Nevo()->get_setting( 'post_related_title' );
		$by      = Nevo()->get_setting( 'post_related_by' );
		$orderby = Nevo()->get_setting( 'post_related_orderby' );
		$order   = Nevo()->get_setting( 'post_related_order' );

		// Get related posts.
		$query_posts = $this->get_related_post( null, $by, $number, $orderby, $order );

		if ( $query_posts ) {
			$image_position = Nevo()->get_setting( 'post_related_img_pos' );
			$thumbnail_size = Nevo()->get_setting( 'post_related_thumbnail_size' );
			$excerpt_length = Nevo()->get_setting( 'post_related_excerpt_length' );
			$avatar = Nevo()->get_setting( 'post_related_display_post_avatar' );
			$author = Nevo()->get_setting( 'post_related_display_post_author' );
			$date = Nevo()->get_setting( 'post_related_display_post_date' );
			$comment = Nevo()->get_setting( 'post_related_display_post_comment' );
			$items = apply_filters( 'nevo_related_entry_meta_items', array( 'avatar', 'author', 'date', 'comment' ) );
			$column = intval( Nevo()->get_setting( 'post_related_col' ) );
			
			$wrapper_classes = array(
				'related-posts',
			);

			$per_row_class[] = 'cv-row';
			
			if ( intval( Nevo()->get_setting( 'post_related_col', 'mobile' ) ) ) {
				$per_row_class[] = 'row-cols-'. intval( Nevo()->get_setting( 'post_related_col', 'mobile' ) );
			}
			if ( intval( Nevo()->get_setting( 'post_related_col', 'tablet' ) ) ) {
				$per_row_class[] = 'row-cols-sm-'. intval( Nevo()->get_setting( 'post_related_col', 'tablet' ) );
			}
			if ( intval( Nevo()->get_setting( 'post_related_col', 'desktop' ) ) ) {
				$per_row_class[] = 'row-cols-lg-'. intval( Nevo()->get_setting( 'post_related_col', 'desktop' ) );
			}
			$per_row_class = join( ' ', $per_row_class );
			
			if ($image_position === 'alignleft') {
				$image_position = 'alignleft cv-col-5 cv-mb-0 cv-col-sm-4 cv-me-3';
			}
			elseif ($image_position === 'alignright') {
				$image_position = 'alignright cv-col-5 cv-col-sm-4 cv-ms-3 cv-mb-0';
			}
			else {
				$image_position = 'aligncenter cv-mb-3';
			}
			if ( ! $query_posts->have_posts() ) {
				return '';
			}
			$itemprop = '';

			if ( 'microdata' === nevo_get_schema_type() ) {
				$itemprop = ' itemprop="text"';
			}
			$attrs = array(
				'alt' => the_title_attribute( 'echo=0' ),
				'itemprop' => 'image',
				'class' => 'size-full cv-col-12'
			);
			global $post;

			echo '<div class="' . esc_attr( join( ' ', $wrapper_classes ) ) . ' ">';
			if ($title) {
				echo '<div class="heading-title"><h3 class="related-post-title general-title">' . wp_kses_post( $title ) . '</h3></div>';
			}
			echo '<div class="' . esc_attr( $per_row_class ) . '">';
			while ( $query_posts->have_posts() ) {
				$query_posts->the_post( 'related-post' );
				$link = '<a href="' . esc_url( get_permalink( $post ) ) . '" title="' . the_title_attribute( array( 'echo' => false ) ) . '" rel="bookmark">';
				?>
				<article id="post-<?php the_ID(); ?>" <?php post_class(); ?> <?php nevo_do_microdata( 'article' ); ?>>
					<div class="article-inner h-100">
						<?php
						if ( has_post_thumbnail() && 'disable' !== Nevo()->get_setting( 'post_related_thumbnail_size' ) ) {
							?>
							<div class="post-image position-relative <?php echo esc_attr( $image_position ) ; ?>">
								<?php
								if ( Nevo()->get_setting( 'post_related_display_post_categories' ) ) {
									nevo_do_post_meta_item( 'categories' );
								}
								?>
								<?php echo $link; ?>
								<?php the_post_thumbnail( $thumbnail_size, $attrs ); ?>
								</a>
							</div>
						<?php } ?>
						<div class="related-post-content">
							<header <?php nevo_do_attr( 'entry_header' ); ?>>
								<?php
								the_title( '<h4 class="entry-title" itemprop="headline">' . $link, '</a></h4>' );
								if ( $avatar || $author || $date || $comment ) {
									?>
									<div class="entry-meta">
										<?php
										foreach ( $items as $item ) {
											$default_display = false;
											$default_display = Nevo()->get_setting( "post_related_display_post_{$item}" ) ? true : false;
											if ( apply_filters( "post_related_display_post_{$item}", $default_display ) ) {
												nevo_do_post_meta_item( "{$item}" );
											}
										}
										?>
									</div>
								<?php } ?>
							</header>
							<?php
							if ( $excerpt_length > 0 ) {
								$excerpt = wp_trim_words( strip_shortcodes( $post->post_content ), $excerpt_length );
								echo '<div class="entry-summary cv-mt-3" '. $itemprop .'><p>' . $excerpt . '</p></div>';
							}
							
					echo '</div></div>';
				echo '</article>';
			}
			wp_reset_postdata();
			echo '</div>';
			echo '</div>';
		}

	}

}
