<?php
/**
 * Analytics Tracker — Records events into the capiflow_analytics table.
 *
 * Thin wrapper over DB_Manager::increment_analytics() with:
 * - Currency auto-detection
 * - Event name sanitization + VARCHAR(50) truncation
 * - GDPR consent filter hook
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core;

defined( 'ABSPATH' ) || exit;

class Analytics_Tracker {

	/**
	 * Record an analytics event into the daily aggregate table.
	 *
	 * Call sites:
	 *  - Proxy_Endpoint::handle() — for all proxy events (PageView, AddToCart, etc.)
	 *  - Plugin_Loader::handle_deferred_purchase_analytics() — for Purchase events (5-min delay)
	 *
	 * @param string      $event_name Event name slug (e.g. 'Purchase', 'AddToCart').
	 * @param string      $source     'both' (pixel + server) or 'server' (server-only rescued).
	 * @param float       $revenue    Order total in store currency. 0.0 for non-Purchase events.
	 * @param float       $recovered  Revenue credited to server-only recovery. 0.0 if pixel also fired.
	 * @param string|null $currency   ISO-4217 code (e.g. 'USD', 'BDT'). null = auto-detect from WC.
	 */
	public static function record(
		string $event_name,
		string $source,
		float $revenue = 0.0,
		float $recovered = 0.0,
		?string $currency = null
	): void {
		// Consent enforcement gate — respects CMP signals when toggle is enabled.
		// Uses the unified capiflow_has_tracking_consent filter (same as Purchase + Proxy).
		if ( get_option( 'capiflow_consent_enforcement', false )
		     && ! apply_filters( 'capiflow_has_tracking_consent', true ) ) {
			return;
		}

		// Sanitize + truncate to VARCHAR(50) — browser sends user-controlled event_name.
		// Without this: garbage names → SQL strict mode fatal; or wp_options bloat.
		$event_name = substr( sanitize_text_field( $event_name ), 0, 50 );
		if ( '' === $event_name ) {
			return;
		}

		// Normalize source — only two valid values.
		if ( ! in_array( $source, array( 'both', 'server' ), true ) ) {
			$source = 'both';
		}

		// Auto-detect currency when not explicitly passed.
		// currency column is NOT NULL — omitting causes SQL errors in strict mode.
		if ( null === $currency ) {
			$currency = function_exists( 'get_woocommerce_currency' )
				? get_woocommerce_currency()
				: 'USD';
		}

		DB_Manager::increment_analytics(
			$event_name,
			$source,
			$revenue,
			$recovered,
			strtoupper( $currency ) // Normalize: 'bdt' → 'BDT'
		);
	}
}
