<?php
/**
 * Magento 2 Google Analytics 4 (GA4) GTM
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Anowave license that is
 * available through the world-wide-web at this URL:
 * https://www.anowave.com/license-agreement/
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category 	Anowave
 * @package 	Anowave_Ec
 * @copyright 	Copyright (c) 2026 Anowave (https://www.anowave.com/)
 * @license  	https://www.anowave.com/license-agreement/
 */

namespace Anowave\Ec\Model\Cookie;

use Anowave\Ec\Model\Cookie as Cookie;

class AnalyticsSession extends Cookie
{
	/**
	 * Name of cookie that holds client id
	 */
	protected $name = null;
	
	/**
	 * Get cookie value
	 *
	 * @return string
	 */
	public function get(string $measurement_id = '')
	{
	    if (null !== $cookie = $this->raw($measurement_id))
		{
			return $this->extractSession($cookie);
		}

		return null;
	}

	public function raw(string $measurement_id = '')
	{
		if ($measurement_id)
	    {
	        $this->name = '_ga_' . substr($measurement_id, 2);
			
	        $cookie = $this->cookieManager->getCookie($this->name);

	        if ($cookie)
	        {
				return $cookie;
	        }
			else 
			{
				if ($_COOKIE && array_key_exists($this->name, $_COOKIE))
				{
					return $_COOKIE[$this->name];
				}
			}
	    }
	    
	    return null;
	}

	/**
	 * Extract cookie session
	 * 
	 * @param string $cookie
	 * 
	 * @return string
	 */
	public function extractSession(string $cookie = '') : string
	{
		if (0 === strpos($cookie, 'GS2.1.s'))
		{
			preg_match_all('/GS[0-9]\.[0-9]\.s([0-9]+)\${1}/msi', $cookie, $matches);

			if ($matches && 2 === count($matches))
			{
				return $matches[1][0];
			}
		}
		else 
		{
			$cookie_split = explode(chr(46), $cookie);
	            
			return isset($cookie_split[2]) ? $cookie_split[2] : '';
		}

		return '';
	}
}