<?php

/**
 * Plugin Name: DragBlock Post View Counter
 * Description: A plugin to count and restrict multiple views from the same user within a specific timeframe.
 * Version: 1.0
 * Author: Your Name
 * Text Domain: dragblock
 */

function dragblock_record_unique_post_view($post_id)
{
	// Only proceed if this is a single post view
	if (empty($post_id)) {
		return;
	}

	// Retrieve the necessary information
	$ip_address = $_SERVER['REMOTE_ADDR'];
	$user_agent = $_SERVER['HTTP_USER_AGENT'];

	// Generate a unique key using md5
	$unique_key = md5($ip_address . $user_agent);
	$transient_key = DRAGBLOCK_POST_VIEWS_KEY . '__' . $post_id . '__' . $unique_key;

	// Check if the transient exists
	if (false === get_transient($transient_key)) {
		// Increment the view count if the transient does not exist
		$views = (int) get_post_meta($post_id, DRAGBLOCK_POST_VIEWS_KEY, true);
		$views++;
		update_post_meta($post_id, DRAGBLOCK_POST_VIEWS_KEY, $views);

		// Set the transient with a 1-hour expiration
		set_transient($transient_key, true, 3600);
	}
}

add_action('wp_head', 'dragblock_track_unique_post_views');
function dragblock_track_unique_post_views()
{
	// || !is_singular('post')
	// we decided to support all custom post types 
	// to provide flexibility
	if (!is_single() || !is_main_query() || get_post_status() !== 'publish') {
		return;
	}
	global $post;
	if (!isset($post->ID)) {
		return;
	}
	dragblock_record_unique_post_view($post->ID);
}
