<?php
/**
 * Parses first-party attribution and analytics bridge cookies.
 *
 * @package Carticy\Conversions\Capture
 */

declare(strict_types=1);

namespace Carticy\Conversions\Capture;

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

/**
 * Pure parsing helpers used by both runtime capture and deterministic harnesses.
 */
final class AttributionCookieParser {

	public const FIRST_TOUCH_COOKIE = 'carticy_conversions_first_touch';
	public const LAST_TOUCH_COOKIE  = 'carticy_conversions_last_touch';
	public const GA_CLIENT_COOKIE   = 'carticy_conversions_ga_client_id';
	public const GA_SESSION_COOKIE  = 'carticy_conversions_ga_session_id';
	public const FBP_COOKIE         = '_fbp';
	public const FBC_COOKIE         = '_fbc';

	/**
	 * Parse a first-party attribution JSON cookie.
	 *
	 * @param string $value Cookie value.
	 * @return array<string, mixed>
	 */
	public function parse_touch_cookie( string $value ): array {
		$decoded = json_decode( rawurldecode( $value ), true );

		return is_array( $decoded ) ? $decoded : array();
	}

	/**
	 * Extract GA client ID from a native _ga cookie or bridge value.
	 *
	 * @param string $value Cookie value.
	 * @return string
	 */
	public function parse_ga_client_id( string $value ): string {
		$value = trim( $value );
		if ( 1 === preg_match( '/^\d+\.\d+$/', $value ) ) {
			return $value;
		}

		if ( 1 === preg_match( '/^GA\d+\.\d+\.(\d+\.\d+)$/', $value, $matches ) ) {
			return $matches[1];
		}

		return '';
	}

	/**
	 * Extract a real GA4 session ID from native GS1/GS2 cookie formats.
	 *
	 * @param string $value Cookie value.
	 * @return string
	 */
	public function parse_ga_session_id( string $value ): string {
		$value = trim( $value );
		if ( 1 === preg_match( '/^\d+$/', $value ) ) {
			return $value;
		}

		if ( 1 === preg_match( '/^GS\d+\.\d+\.(\d+)\./', $value, $matches ) ) {
			return $matches[1];
		}

		if ( 1 === preg_match( '/(?:^|[.$])s(\d+)(?:[.$]|$)/', $value, $matches ) ) {
			return $matches[1];
		}

		return '';
	}
}
