<?php
/**
 * Google Analytics Cookie Parser.
 *
 * Based on GA_Parse from https://github.com/joaolcorreia/Google-Analytics-PHP-cookie-parser
 *
 * @package     EDD\Pro\CampaignTracker\Campaigns\Parser
 * @copyright   Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.6.3
 */

namespace EDD\Pro\CampaignTracker\Campaigns\Parser;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

/**
 * Parse Google Analytics Cookie.
 *
 * @since 3.6.3
 */
class GoogleAnalytics {

	/**
	 * Parse the Google Analytics cookie and return campaign data.
	 *
	 * @since 3.6.3
	 * @return array|null Campaign data array or null if cookie not present or invalid.
	 */
	public static function parse() {
		if ( ! isset( $_COOKIE['__utmz'] ) ) {
			return null;
		}

		// Sanitize the cookie value first.
		$cookie_value = sanitize_text_field( $_COOKIE['__utmz'] );

		// Parse __utmz cookie with validation.
		// Cookie format: domain_hash.timestamp.session_number.campaign_number.campaign_data
		$parts = preg_split( '[\.]', $cookie_value, 5 );

		// Validate we have at least 5 parts before proceeding.
		if ( count( $parts ) < 5 ) {
			return null; // Malformed cookie, return null gracefully.
		}

		// Campaign data is always the 5th part (index 4).
		$campaign_data = isset( $parts[4] ) ? $parts[4] : '';

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

		// Parse the campaign data.
		parse_str( strtr( $campaign_data, '|', '&' ), $campaign_data );

		// Extract UTM parameters - any combination may be present.
		$parsed = array(
			'source'  => isset( $campaign_data['utmcsr'] ) ? $campaign_data['utmcsr'] : null,
			'name'    => isset( $campaign_data['utmccn'] ) ? $campaign_data['utmccn'] : null,
			'medium'  => isset( $campaign_data['utmcmd'] ) ? $campaign_data['utmcmd'] : null,
			'term'    => isset( $campaign_data['utmctr'] ) ? $campaign_data['utmctr'] : null,
			'content' => isset( $campaign_data['utmcct'] ) ? $campaign_data['utmcct'] : null,
		);

		// AdWords override.
		if ( isset( $campaign_data['utmgclid'] ) ) {
			$parsed['source']  = 'google';
			$parsed['name']    = '';
			$parsed['medium']  = 'cpc';
			$parsed['content'] = '';
			$parsed['term']    = isset( $campaign_data['utmctr'] ) ? $campaign_data['utmctr'] : '';
		}

		// Return null if all values are empty/null.
		// Otherwise return the array with whatever data is present.
		$has_data = array_filter(
			$parsed,
			function( $value ) {
				return ! empty( $value );
			}
		);

		return ! empty( $has_data ) ? $parsed : null;
	}
}
