<?php
/**
 * Post meta elements.
 *
 * @package Nevo
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! function_exists( 'nevo_content_nav' ) ) {
	/**
	 * Display navigation to next/previous pages when applicable.
	 *
	 * @since 0.1
	 *
	 * @param string $nav_id The id of our navigation.
	 */
	function nevo_content_nav( $nav_id ) {
		global $wp_query, $post;
		
		$arrowleft = 'left';
		$arrowright = 'right';
		if (is_rtl()) {
			$arrowleft = 'right';
			$arrowright = 'left';
		}
		// Don't print empty markup on single pages if there's nowhere to navigate.
		if ( is_single() ) {
			$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
			$next = get_adjacent_post( false, '', false );

			if ( ! $next && ! $previous ) {
				return;
			}
		}

		// Don't print empty markup in archives if there's only one page.
		if ( $wp_query->max_num_pages < 2 && ( is_home() || is_archive() || is_search() ) ) {
			return;
		}
		?>
		<nav <?php nevo_do_attr( 'post_navigation', array( 'id' => esc_attr( $nav_id ) ) ); ?>>
			<span class="screen-reader-text"><?php esc_html_e( 'Post navigation', 'nevo' ); ?></span>

			<?php
			if ( is_single() ) : // navigation links for single posts.

				$post_navigation_args = apply_filters(
					'nevo_post_navigation_args',
					array(
						'previous_format' => '<div class="nav-next text-start"><span class="entry-meta d-block">' . apply_filters( 'nevo_previous_post_text', __( 'Previous post', 'nevo' ) ) . '</span><h3 class="prev">%link</h3></div>',
						'next_format' => '<div class="nav-previous text-end"><span class="entry-meta d-block">' . apply_filters( 'nevo_next_post_text', __( 'Next post', 'nevo' ) ) . '</span><h3 class="next">%link</h3></div>',
						'link' => '%title',
						'in_same_term' => apply_filters( 'nevo_category_post_navigation', false ),
						'excluded_terms' => '',
						'taxonomy' => 'category',
					)
				);

				previous_post_link(
					$post_navigation_args['previous_format'],
					$post_navigation_args['link'],
					$post_navigation_args['in_same_term'],
					$post_navigation_args['excluded_terms'],
					$post_navigation_args['taxonomy']
				);

				next_post_link(
					$post_navigation_args['next_format'],
					$post_navigation_args['link'],
					$post_navigation_args['in_same_term'],
					$post_navigation_args['excluded_terms'],
					$post_navigation_args['taxonomy']
				);

			elseif ( is_home() || is_archive() || is_search() ) : // navigation links for home, archive, and search pages.
				
				if ( get_next_posts_link() ) :
					?>
					<div class="nav-next text-start">
						<span class="nevo-icon"><?php echo nevo_get_svg_icon( 'ui', 'bi-chevron-' . $arrowleft, '', 20 ); ?></span>
						<span class="next" title="<?php esc_attr_e( 'Previous', 'nevo' ); ?>"><?php next_posts_link(  apply_filters( 'nevo_next_posts_link_text', __( 'Older posts', 'nevo' ) ) ); ?></span>
					</div>
					<?php
				endif;

				if ( get_previous_posts_link() ) :
					?>
					<div class="nav-previous text-end">
						<span class="previous" title="<?php esc_attr_e( 'Next', 'nevo' ); ?>"><?php previous_posts_link( apply_filters( 'nevo_previous_posts_link_text', __( 'Newer posts', 'nevo' ) ) ); ?></span>
						<span class="nevo-icon"><?php echo nevo_get_svg_icon( 'ui', 'bi-chevron-' .$arrowright, '', 20 ); ?></span>
					</div>
					<?php
				endif;

				if ( function_exists( 'the_posts_pagination' ) ) {
					the_posts_pagination(
						array(
							'mid_size' => apply_filters( 'nevo_pagination_mid_size', 1 ),
							'prev_text' => apply_filters(
								'nevo_previous_link_text',
								sprintf(
									/* translators: left arrow */
									'<span class="previous screen-reader-text">'. __( 'Previous', 'nevo' ) .'</span>%s',
									nevo_get_svg_icon( 'ui', 'bi-chevron-' . $arrowleft, '', 16 )
								)
							),
							'next_text' => apply_filters(
								'nevo_next_link_text',
								sprintf(
									/* translators: right arrow */
									'<span class="next screen-reader-text">'. __( 'Next', 'nevo' ) .'</span>%s',
									nevo_get_svg_icon( 'ui', 'bi-chevron-' .$arrowright, '', 16 )
								)
							),
							'before_page_number' => sprintf(
								'<span class="screen-reader-text">%s</span>',
								_x( 'Page', 'prepends the pagination page number for screen readers', 'nevo' )
							),
						)
					);
				}

				/**
				 * nevo_paging_navigation hook.
				 *
				 * @since 0.1
				 */
				do_action( 'nevo_paging_navigation' );

			endif;
			?>
			<?php //echo 'Page '. ( get_query_var('paged') ? get_query_var('paged') : 1 ) . ' of ' . $wp_query->max_num_pages; ?>
		</nav>
		<?php
	}
}

if ( ! function_exists( 'nevo_modify_posts_pagination_template' ) ) {
	add_filter( 'navigation_markup_template', 'nevo_modify_posts_pagination_template', 10, 2 );
	/**
	 * Remove the container and screen reader text from the_posts_pagination()
	 * We add this in ourselves in nevo_content_nav()
	 *
	 * @since 1.0
	 *
	 * @param string $template The default template.
	 * @param string $class The class passed by the calling function.
	 * @return string The HTML for the post navigation.
	 */
	function nevo_modify_posts_pagination_template( $template, $class ) {
		if ( ! empty( $class ) && false !== strpos( $class, 'pagination' ) ) {
			$template = '<div class="nav-links">%3$s</div>';
		}

		return $template;
	}
}

/**
 * Output requested post meta.
 *
 * @since 1.0
 *
 * @param string $item The post meta item we're requesting.
 */
function nevo_do_post_meta_item( $item ) {
	global $post;
	$user = get_user_by( 'ID', $post->post_author );
	
	if ( 'avatar' === $item ) {
		$user_avatar = get_avatar_url( $user->ID );
		$avatar_size = apply_filters( 'nevo_post_meta_avatar_size', 24 );
		
		echo '<span class="author-avatar rounded-circle"><img class="user-avatar avatar-'. $avatar_size .'" height="'. $avatar_size .'" width="'. $avatar_size .'" src="' . $user_avatar . '" alt="" loading="lazy"></span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}
	
	if ( 'author' === $item ) {
		$schema_type = nevo_get_schema_type();
		$byline = '<span class="byline">%1$s<span class="author%8$s" %5$s><a class="url fn n" href="%2$s" title="%3$s" rel="author"%6$s><span class="author-name"%7$s>%4$s</span></a></span></span> ';

		if ( ! apply_filters( 'nevo_post_author_link', true ) ) {
			$byline = '<span class="byline">%1$s<span class="author%8$s" %5$s><span class="author-name"%7$s>%4$s</span></span></span> ';
		}

		echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			'nevo_post_author_output',
			sprintf(
				$byline,
				apply_filters( 'nevo_inside_post_meta_item_output', '', 'author' ),
				esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
				/* translators: 1: Author name */
				esc_attr( sprintf( __( 'View all posts by %s', 'nevo' ), get_the_author() ) ),
				esc_html( $user->display_name ),
				nevo_get_microdata( 'post-author' ),
				'microdata' === $schema_type ? ' itemprop="url"' : '',
				'microdata' === $schema_type ? ' itemprop="name"' : '',
				' vcard'
			)
		);
	}

	if ( 'date' === $item ) {
		$time_string = '<time class="entry-date published" datetime="%1$s"%5$s>%8$s%2$s</time>';

		$updated_time = get_the_modified_time( 'U' );
		$published_time = get_the_time( 'U' ) + 1800;
		$schema_type = nevo_get_schema_type();
		$date = get_option('nevo_display_date', 'publication');
		
		if ( $updated_time > $published_time ) {
			if ( apply_filters( 'nevo_post_date_show_updated_only', $date === 'update' ? true : false ) ) {
				$time_string = '<time class="entry-date updated-date" datetime="%3$s"%6$s>%7$s%4$s</time>';
			} elseif ( apply_filters( 'nevo_post_date_show_updated_published_only', $date === 'pubupdate' ? true : false ) ) {
				$time_string = ''. $time_string .'<time class="updated" datetime="%3$s"%6$s>%9$s%4$s</time>';
			} else {
				$time_string = $time_string;
			}
		}

		$time_string = sprintf(
			$time_string,
			esc_attr( get_the_date( 'c' ) ),
			esc_html( get_the_date() ),
			esc_attr( get_the_modified_date( 'c' ) ),
			esc_html( get_the_modified_date() ),
			'microdata' === $schema_type ? ' itemprop="datePublished"' : '',
			'microdata' === $schema_type ? ' itemprop="dateModified"' : '',
			apply_filters( 'nevo_post_date_before_updated', '' ),
			apply_filters( 'nevo_post_date_before_published', '' ),
			apply_filters( 'nevo_post_date_before_updated_published', ' &nbsp;-&nbsp; ' )
		);

		$posted_on = '<span class="posted-on">%1$s%4$s</span> ';

		if ( apply_filters( 'nevo_post_date_link', false ) ) {
			$posted_on = '<span class="posted-on">%1$s<a href="%2$s" title="%3$s" rel="bookmark">%4$s</a></span> ';
		}

		echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			'nevo_post_date_output',
			sprintf(
				$posted_on,
				apply_filters( 'nevo_inside_post_meta_item_output', '', 'date' ),
				esc_url( get_permalink() ),
				esc_attr( get_the_time() ),
				$time_string
			),
			$time_string,
			$posted_on
		);
	}

	if ('categories' === $item) {
		$term_separator = apply_filters('nevo_term_separator', _x('&nbsp;&nbsp;', 'Used between list items, there is a space after the comma.', 'nevo'), 'categories');

		$categories = get_the_category();
		$categories_list = array();

		foreach ($categories as $category) {
			$color_code = '';//nevo_category_color(get_cat_id($category->cat_name));
			$category_classes = 'category-' . $category->slug;
			if (!empty($color_code)) {
				$categories_list[] = '<a href="' . get_category_link($category->term_id) . '" style="background:' . nevo_category_color(get_cat_id($category->cat_name)) . '" rel="category tag" class="' . esc_attr($category_classes) . '">' . $category->cat_name . '</a>';
			} else {
				$categories_list[] = '<a href="' . get_category_link($category->term_id) . '"  rel="category tag" class="' . esc_attr($category_classes) . '">' . $category->cat_name . '</a>';
			}
		}

		if (!empty($categories_list)) {
			if ( is_single() ) {
				$attributes = 'nevo-cat-single';
			} else {
				$attributes = 'nevo-cat';
			}
			echo apply_filters(
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				'nevo_category_list_output',
				sprintf(
					'<span class="%4$s cat-links">%3$s<span class="screen-reader-text">%1$s </span>%2$s</span> ',
					esc_html_x('Categories', 'Used before category names.', 'nevo'),
					implode($term_separator, $categories_list),
					apply_filters('nevo_inside_post_meta_item_output', '', 'categories'),
					$attributes
				)
			);
		}
	}
	
	if ( 'tags' === $item ) {
		$term_separator = apply_filters( 'nevo_term_separator', _x( '&nbsp;&nbsp;&nbsp;', 'Used between list items, there is a space after the comma.', 'nevo' ), 'tags' );
		$tags_list = get_the_tag_list( '', $term_separator );

		if ( $tags_list ) {
			echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				'nevo_tag_list_output',
				sprintf(
					'<span class="tags-links">%3$s<span class="screen-reader-text">%1$s </span>%2$s</span> ',
					esc_html_x( 'Tags', 'Used before tag names.', 'nevo' ),
					$tags_list,
					apply_filters( 'nevo_inside_post_meta_item_output', '', 'tags' )
				)
			);
		}
	}

	if ( 'comment' === $item ) {
		if ( ! post_password_required() && ( comments_open() || get_comments_number() ) ) {
			echo '<span class="comments-link custom">';
				?><a href="<?php comments_link() ?>"><?php
				echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					'nevo_inside_post_meta_item_output',
					'',
					'comment'
				);
				comments_number( apply_filters( 'nevo_entry_comments_meta_leave_text', __( '0', 'nevo' ) ),
					apply_filters( 'nevo_entry_comments_meta_few_text', __( '1', 'nevo' ) ), '% '.
					apply_filters( 'nevo_entry_comments_meta_many_text', __( '', 'nevo' ) ) );
				echo '</a>';
			echo '</span> ';
		}
	}
	
	if ( 'views' === $item ) {
		echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			'nevo_post_views_output',
			sprintf(
				'<span class="post-views">%1$s <span class="count-post-views">%2$s %3$s</span></span> ',
				apply_filters( 'nevo_inside_post_meta_item_output', '', 'views' ),
				nevo_count_post_views(),
				'Views'
			)
		);
	}

	/**
	 * nevo_post_meta_items hook.
	 *
	 * @since 1.0
	 */
	do_action( 'nevo_post_meta_items', $item );
}

add_filter( 'nevo_inside_post_meta_item_output', 'nevo_do_post_meta_prefix', 10, 2 );
/**
 * Add svg icons or text to our post meta output.
 *
 * @since 1.0
 * @param string $output The existing output.
 * @param string $item The item to target.
 */
function nevo_do_post_meta_prefix( $output, $item ) {
	
	$disable = nevo_get_post_setting('display_post_avatar' );
	
	if ( 'author' === $item && ! $disable ) {
		$output = __( '	By', 'nevo' ) . ' ';
	}
	
	if ( 'date' === $item ) {
		$output = '<span class="nevo-icon">'. nevo_get_svg_icon( 'ui', 'bi-clock', '', 14 ) .'</span> ';
	}

	if ( 'tags' === $item ) {
		$output = __( 'Tags : ', 'nevo' ) . ' ';
	}

	if ( 'comment' === $item ) {
		$output = '<span class="nevo-icon">'. nevo_get_svg_icon( 'ui', 'bi-chat', '', 14 ) .'</span> ';
	}
	if ( 'views' === $item ) {
		$output = '<span class="nevo-icon">'. nevo_get_svg_icon( 'ui', 'bi-eye-fill', '', 20 ) .'</span> ';
	}

	return $output;
}

/**
 * Display post meta items based on their individual filters.
 *
 * @param array  $items        The post meta items.
 * @param string $setting_values The setting values.
 */
function nevo_display_entry_meta_items( $setting_values ) {
    $items = apply_filters( 'nevo_header_entry_meta_items',
		array(
			'avatar',
			'author',
			'tags',
			'categories',
			'date',
			'comment',
			'views',
		)
	);
	foreach ( $items as $item ) {
        $default_display = false;
		$setting_value = isset( $setting_values[ $item ] ) ? $setting_values[ $item ] : false;

        if ( ( $setting_value || $setting_value === 'true' ) && $setting_value !== 'false' ) {
            $default_display = true;
        }
        
        if ( apply_filters( "nevo_disable_entry_meta_{$item}", $default_display ) ) {
            nevo_do_post_meta_item( $item );
        }
    }
}

function nevo_entry_meta_items_setting_values() {
	return apply_filters( 'nevo_entry_meta_items_setting_values', array(
		'avatar' => nevo_get_post_setting('display_post_avatar' ),
		'author' => nevo_get_post_setting('display_post_author' ),
		'date' => nevo_get_post_setting('display_post_date' ),
		'comment' => nevo_get_post_setting('display_post_comment'),
	));
}

if ( ! function_exists( 'nevo_categories_meta' ) ) {
	/**
	 * Build the post meta.
	 *
	 * @since 1.0
	 */
	function nevo_categories_meta() {
		$setting_values = array(
			'categories' => nevo_get_post_setting('display_post_categories' ),
		);
		nevo_display_entry_meta_items($setting_values);
	}
}

if ( ! function_exists( 'nevo_post_meta' ) ) {
	/**
	 * Build the post meta.
	 *
	 * @since 1.0
	 */
	function nevo_post_meta() {
		?>
		<div class="entry-meta">
			<?php 
			$setting_values = nevo_entry_meta_items_setting_values();
			nevo_display_entry_meta_items($setting_values);
			?>
		</div>
		<?php
	}
}

if ( ! function_exists( 'nevo_footer_meta' ) ) {
	/**
	 * Build the footer post meta.
	 *
	 * @since 1.0
	 */
	function nevo_footer_meta() {
		if (get_the_tag_list()) {
			?>
			<footer <?php nevo_do_attr( 'footer_entry_meta' ); ?>>
				<?php 
				$setting_values = array(
					'tags' => Nevo()->get_setting( 'post_single_display_post_tags' ),
				);
				nevo_display_entry_meta_items($setting_values);
				?>
			</footer>
			<?php
		}
	}
}

add_action( 'nevo_after_endwhile', 'nevo_do_post_navigation', 10 );
/**
 * Add our post navigation after endwhile loops.
 *
 * @since 1.0
 * @param string $template The template of the current action.
 */
function nevo_do_post_navigation() {
	if ( ! is_singular() && apply_filters( 'nevo_show_post_navigation', true ) ) {
		nevo_content_nav( 'nav-below' );
	}
}


function nevo_count_post_views() {
	
	// Số lượt xem cần đặt cho trước.
	$starting_views = apply_filters( 'nevo_starting_views', 0 );
	
	// Kiểm tra xem bài viết này đã được xem bao nhiêu lần.
	$views = wp_cache_get(get_the_ID(), 'post_views');

	// Nếu số lượt xem chưa được lưu trữ trong bộ nhớ cache, hãy truy vấn vào cơ sở dữ liệu để lấy số lượt xem hiện tại.
	if($views === false) {
		$views = (int) get_post_meta(get_the_ID(), 'post_views', true);
		
		// bắt đầu đếm từ số 100 nếu chưa có trong post_meta
		$views = ($views !== '') ? $views : $starting_views;

		// Lưu trữ số lượt xem vào bộ nhớ cache và cập nhật số lượt xem trong cơ sở dữ liệu.
		wp_cache_set(get_the_ID(), $views, 'post_views');
		update_post_meta(get_the_ID(), 'post_views', $views);
	}

	// Trả về số lượt xem của bài viết.
	return $views;
}