<?php
/**
 * Custom hooks functions are define.
 *
 * @package MatrixAddons
 * @subpackage trainify
 * @since 1.0.0
 */

/*-----------------------------------------------------------------------------------------------------------------------*/

/**
 * Related Posts section
 *
 * @since 1.0.0
 */
if( ! function_exists( 'trainify_related_posts_section' ) ) :
	function trainify_related_posts_section() {
		echo '<div class="tff-related-section-wrapper">';
		$trainify_related_option = get_theme_mod( 'trainify_framework_enable_related_posts', 'show' );
		if( $trainify_related_option == 'hide' ) {
			return;
		}
		$trainify_related_title = get_theme_mod( 'trainify_framework_related_posts_title', __( 'Related Posts', 'trainify' ) );
		if( !empty( $trainify_related_title ) ) {
			echo '<h2 class="tff-related-title tff-clearfix">'. esc_html( $trainify_related_title ) .'</h2>';
		}
		global $post;
        if( empty( $post ) ) {
            $post_id = '';
        } else {
            $post_id = $post->ID;
        }
        $categories = get_the_category( $post_id );
        $category_ids = array();
        if ( $categories ) {
            foreach( $categories as $category_ed ) {
                $category_ids[] = $category_ed->term_id;
            }
        }
		$trainify_post_count = apply_filters( 'trainify_related_posts_count', 3 );
		
		$related_args = array(
			'no_found_rows'            	=> true,
			'update_post_meta_cache'   	=> false,
			'update_post_term_cache'   	=> false,
			'ignore_sticky_posts'      	=> 1,
			'orderby'                  	=> 'rand',
			'post__not_in'             	=> array( $post_id ),
			'category__in'				=> $category_ids,
			'posts_per_page' 		   	=> $trainify_post_count
		);
		$related_query = new WP_Query( $related_args );
		if( $related_query->have_posts() ) {
			echo '<div class="tff-related-posts-wrap tff-clearfix">';
			while( $related_query->have_posts() ) {
				$related_query->the_post();
				?>
				<div class="tff-single-post tff-clearfix">
					<div class="tff-single-post-inner">
						<?php if(has_post_thumbnail( get_the_ID() )): ?>
							<div class="tff-post-thumb">
								<a href="<?php the_permalink(); ?>">
									<?php the_post_thumbnail( 'trainify-thumb-600x600' ); ?>
								</a>
							</div><!-- .tff-post-thumb -->
						<?php endif; ?>
						<div class="tff-post-content">
							<h3 class="tff-post-title small-size"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
							<div class="tff-post-meta">
								<?php trainify_posted_on(); ?>
							</div>
						</div><!-- .tff-post-content -->
					</div><!-- .tff-single-post-inner -->
				</div><!-- .tff-single-post -->
				<?php
			}
			echo '</div><!-- .tff-related-posts-wrap -->';
		}
		wp_reset_postdata();
		echo '</div><!-- .tff-related-section-wrapper -->';
	}
endif;

/**
 * Managed functions for related posts section
 *
 * @since 1.0.0
 */
add_action( 'trainify_related_posts', 'trainify_related_posts_section', 10 );