<?php
/**
 * Post view counter for 'most viewed' meta info
 *
 * @since 0.8.8
 */
namespace Greyd\Search;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

new Postviews_Counter();
class Postviews_Counter {


	public function __construct() {
		add_action( 'wp_head', array( $this, 'track_postviews' ) );

		// To keep the count accurate, lets get rid of prefetching
		remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );

		// add dynamic tag
		add_filter( 'greyd_default_dynamic_tags', array( $this, 'add_dynamic_tag' ) );
	}

	public static function track_postviews() {

		$settings = Settings::get_setting( array( 'site', 'advanced_search' ) );

		// return if not enabled or not on single
		if ( ! is_single() || ! $settings || $settings['postviews_counter'] !== 'true' || is_user_logged_in() ) {
			return;
		}

		self::set_postviews( get_the_ID() );
	}

	public static function set_postviews( $post_id ) {
		$count_key = 'postviews_count';
		$count     = get_post_meta( $post_id, $count_key, true );

		if ( empty( $count ) ) {
			$count = 1;
		} else {
			$count = intval( $count ) + 1;
		}

		update_post_meta( $post_id, $count_key, $count );
	}

	/**
	 * Add the dynamic tag '_post-views_'
	 *
	 * @filter greyd_default_dynamic_tags
	 */
	public function add_dynamic_tag( $tags ) {
		$tags[] = 'post-views';
		return $tags;
	}
}
