<?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;

class Onetrust extends Directive
{
	/**
	 * Cookie name for cookie that keeps customer consent
	 * 
	 * @var string
	 */
	protected $name = \Anowave\Ec\Helper\Constants::COOKIE_ONETRUST_OPTANON;
	
	protected $config = [];

	public function get()
	{
		$value = parent::get();

		if (!$value)
		{
			return null;
		}

		parse_str($value, $data);

		return $data;
	}

	public function getGroups() : array 
	{
		$value = $this->get();

		if ($value && is_array($value) &&array_key_exists('groups', $value))
		{
			$groups = explode(chr(44), $value['groups']);

			return array_map(function($group) 
			{
				list($group_id, $group_consent) = explode(':', $group);

				return 
				[
					'group_id' 		=> $group_id, 
					'group_consent' => (bool) $group_consent
				];
			}, 
			$groups);
		}

		return [];
	}

	/**
	 * Set config 
	 * 
	 * @param array $config
	 * 
	 * @return self
	 */
	public function setConfig(array $config = []) : self 
	{
		$this->config = $config;

		return $this;
	}

	public function getConfig() : array 
	{
		return $this->config;
	}

	/**
	 * Check consent 
	 * 
	 * @return bool
	 */
	public function hasConsent() : bool
	{
		$groups = $this->getGroups();

		/**
		 * Simulate groups
		 */
		if (1)
		{
			$groups = 
			[
				[
					'group_id' => 'C0001',
					'group_consent' => true,
				],
				[
					'group_id' => 'C0004',
					'group_consent' => false,
				],
				[
					'group_id' => 'C0002',
					'group_consent' => true,
				],
				[
					'group_id' => 'C0003',
					'group_consent' => true,
				],
			];
		}

		$consent_group = $this->config['anonymize_group'] ?? null;

		if (!$consent_group)
		{
			return true;
		}
		
		/**
		 * OptanonConsent cookie not found and/or consent groups not identified
		 */
		if (!$groups)
		{
			return true;
		}
		else 
		{
			foreach($groups as $group)
			{
				if ($consent_group === $group['group_id'] && false === $group['group_consent'])
				{
					return false;
				}
			}
		}

		return true;
	}
}