<?php
/**
 * Local visit statistics tracker.
 *
 * FIXES:
 *  BUG 2 — __isAjaxCall() replaced with wp_doing_ajax()
 *  BUG 8 — __DIE() debug method removed
 *
 * @package FENSE_BPVT
 */

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

class FENSE_BPVT_STATS
{
	
	private string $dbKeyPrefix = 'bpvt_stats_';
	private string $transientKey = '';
	private stdClass $post;
	private stdClass $db;
	private bool $ran = false;
	private string $url = '';
	
	public function __construct()
	{
		$this->db = new stdClass();
		$this->post = new stdClass();
		$this->init();
	}
	
	private function init(): void
	{
		if ( $this->ran ) {
			return;
		}
		if ( !$this->isEnabled() ) {
			return;
		}
		
		$this->post = $GLOBALS['post'] ?? $this->post;
		$this->url = (string)( get_permalink() ?: '' );
		
		if ( $this->hasCookie() ) {
			return;
		}
		
		$this->buildKey();
		$this->save();
	}
	
	private function save(): void
	{
		$existing = FENSE_BPVT_Cache::wp_get( $this->transientKey );
		$this->db->visits = ( is_object( $existing ) ? (int)$existing->visits : 0 ) + 1;
		
		FENSE_BPVT_Cache::wp_set( $this->transientKey, $this->db, DAY_IN_SECONDS );
		$this->setCookie();
		$this->ran = true;
	}
	
	private function buildKey(): void
	{
		$this->db->id = $this->post->ID ?? null;
		$this->db->title = $this->post->post_title ?? null;
		$this->db->url = $this->url;
		$this->transientKey = $this->dbKeyPrefix . md5( $this->url );
	}
	
	private function setCookie(): void
	{
		setcookie(
			'bpvt_st_visit', '1', time() + DAY_IN_SECONDS,
			COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true
		);
	}
	
	private function hasCookie(): bool
	{
		return !empty( $_COOKIE['bpvt_st_visit'] );
	}
	
	private function isEnabled(): bool
	{
		// Login page is always eligible.
		if ( isset( $GLOBALS['pagenow'] ) && $GLOBALS['pagenow'] === 'wp-login.php'
			&& doing_action( 'login_init' ) ) {
			return true;
		}
		
		if ( !doing_action( 'wp' ) ) {
			return false;
		}
		
		// BUG 2 FIX: wp_doing_ajax() (was: function_exists('DOING_AJAX') — always false)
		if ( wp_doing_ajax() ) {
			return false;
		}
		if ( is_admin() || is_user_logged_in() ) {
			return false;
		}
		
		return (bool)get_option( FENSE_BPVT_PLUGIN::DB_KEY . 'enable_stats' );
	}
}
