<?php
/**
 * File to tracking eCommerce functionality.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class to handle eCommerce tracking common functionality.
 *
 * Subclasses (WooCommerce, EDD) inherit send_request() from
 * SimpleStats_Tracking_Base via this abstract.
 */
abstract class SimpleStats_Ecommerce_Tracking extends SimpleStats_Tracking_Base {

	/** Order-meta keys for the visitor session captured at checkout. */
	const META_VISITOR_UUID = '_simplestats_visitor_uuid';
	const META_SESSION_UUID = '_simplestats_session_uuid';
	const META_EVENT_UUID   = '_simplestats_event_uuid';

	/**
	 * Read the visitor session UUIDs from the request cookies.
	 *
	 * Returns an empty array unless both the visitor and session uuids are
	 * present (the minimum the backend needs to resolve a session).
	 *
	 * @return array Keys: visitor_uuid, session_uuid, event_uuid — or empty.
	 */
	protected function read_session_cookies() {
		// Pixel-set session identifiers, read on ordinary storefront page loads.
		// There is no form submission to guard here, so no nonce applies; each
		// value is sanitized as it is read.
		// phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPressVIPMinimum.Variables.RestrictedVariables.cache_constraints___COOKIE
		if ( empty( $_COOKIE['visitor_uuid'] ) || empty( $_COOKIE['visitor_session_uuid'] ) ) {
			return array();
		}

		return array(
			'visitor_uuid' => sanitize_text_field( wp_unslash( $_COOKIE['visitor_uuid'] ) ),
			'session_uuid' => sanitize_text_field( wp_unslash( $_COOKIE['visitor_session_uuid'] ) ),
			'event_uuid'   => isset( $_COOKIE['visitor_session_event_uuid'] ) ? sanitize_text_field( wp_unslash( $_COOKIE['visitor_session_event_uuid'] ) ) : '',
		);
		// phpcs:enable WordPress.Security.NonceVerification.Recommended, WordPressVIPMinimum.Variables.RestrictedVariables.cache_constraints___COOKIE
	}

	/**
	 * Hash an email for pseudonymous customer identity.
	 *
	 * SHA-256 of the trimmed, lowercased email. Returns null for an empty
	 * email so no identity is sent. Must match the backend's expectation.
	 *
	 * @param string $email Raw email address.
	 * @return string|null
	 */
	protected function hash_email( $email ) {
		$email = trim( strtolower( (string) $email ) );

		if ( empty( $email ) ) {
			return null;
		}

		return hash( 'sha256', $email );
	}
}
