<?php
/**
 * Recently Viewed Products Tracker.
 *
 * Tracks recently viewed products using a client-side JavaScript approach.
 * A small inline script is injected into wp_footer on single product pages;
 * it reads and updates the preco_recently_viewed cookie directly in the
 * browser. This works correctly even when full-page caching is active
 * (cached pages still execute JS), and avoids any server-side hook ordering
 * or header-timing constraints.
 *
 * Cookie name : preco_recently_viewed
 * Cookie value: pipe-separated list of product IDs (newest first), max 15.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Frontend\Core;

defined( 'ABSPATH' ) || exit;

/**
 * RecentlyViewedTracker class.
 */
class RecentlyViewedTracker {

	/**
	 * Cookie name used to store recently viewed product IDs.
	 */
	const COOKIE_NAME = 'preco_recently_viewed';

	/**
	 * Maximum number of product IDs stored in the cookie.
	 */
	const MAX_ITEMS = 75;

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_footer', array( $this, 'handle_preco_recently_viewed_props' ), 20 );
	}

	/**
	 * Inject an inline script on single product pages that records the
	 * current product ID into the preco_recently_viewed cookie.
	 *
	 * Using wp_footer (JavaScript) instead of a server-side hook means:
	 *  - Works with full-page caching plugins (Varnish, WP Super Cache, etc.)
	 *  - No reliance on server-side cookie write timing.
	 *  - Completely independent of WooCommerce widget activation state.
	 *
	 * @return void
	 */
	public function handle_preco_recently_viewed_props() {
		if ( ! is_singular( 'product' ) ) {
			return;
		}

		$product_id = get_the_ID();
		if ( ! $product_id ) {
			return;
		}
		// Cookie expiry: 10 days (in seconds for JS Date calculation).
		$expiry_days = 10;

		echo wp_kses_post( '<div id="preco_recently_viewed_props" class="preco-hidden" data-product-id="' . esc_attr( $product_id ) . '" data-cookie-name="' . esc_attr( self::COOKIE_NAME ) . '" data-max-items="' . esc_attr( self::MAX_ITEMS ) . '" data-expiry-days="' . esc_attr( $expiry_days ) . '"></div>' );
	}

	/**
	 * Return an array of recently viewed product IDs from the preco cookie.
	 *
	 * @return int[]
	 */
	public static function get_ids() {
		if ( ! isset( $_COOKIE[ self::COOKIE_NAME ] ) ) {
			return array();
		}

		$raw = sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE_NAME ] ) );

		if ( '' === $raw ) {
			return array();
		}

		return array_values(
			array_filter(
				array_map( 'absint', explode( '|', (string) $raw ) )
			)
		);
	}
}
