<?php
/**
 * FrontendSpectatorTrackingHook class.
 *
 * Handles tracking of active product viewers on the frontend.
 *
 * @package Ilabs\Firevert\Modules\SpectatorViews\Hooks\Frontend
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\SpectatorViews\Hooks\Frontend;

use Ilabs\Firevert\Modules\SpectatorViews\Services\SpectatorTrackingService;

/**
 * Class FrontendSpectatorTrackingHook
 */
final class FrontendSpectatorTrackingHook {

	/**
	 * SpectatorTrackingService instance.
	 *
	 * @var SpectatorTrackingService
	 */
	private SpectatorTrackingService $tracking_service;

	/**
	 * Constructor.
	 *
	 * @param SpectatorTrackingService $tracking_service Service instance for tracking.
	 */
	public function __construct( SpectatorTrackingService $tracking_service ) {
		$this->tracking_service = $tracking_service;
	}

	/**
	 * Registers the tracking hook.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'template_redirect', array( $this, 'track_product_view' ) );
	}

	/**
	 * Tracks viewer if on a single product page.
	 *
	 * @return void
	 */
	public function track_product_view(): void {
		if ( ! is_product() ) {
			return;
		}

		$product_id   = get_the_ID();
		$visitor_hash = SpectatorTrackingService::hash_visitor();

		$this->tracking_service->ping( (int) $product_id, $visitor_hash );
	}
}
