<?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\Controller\Index;

use Anowave\Ec\Helper\Constants;

class CookieConsent extends \Magento\Framework\App\Action\Action
{
	/**
	 * @var \Magento\Framework\Controller\Result\JsonFactory
	 */
	protected $resultJsonFactory;
	
	/**
	 * @var \Anowave\Ec\Model\ConsentCookie
	 */
	protected $consentCookieFactory;
	
	/**
	 * @var \Anowave\Ec\Model\ResourceModel\ConsentCookie\CollectionFactory
	 */
	protected $consentCookieCollectionFactory;

	/**
	 * Constructor 
	 * 
	 * @param \Magento\Framework\App\Action\Context $context
	 * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
	 * @param \Anowave\Ec\Model\ConsentCookieFactory $consentCookieFactory
	 * @param \Anowave\Ec\Model\ResourceModel\ConsentCookie\CollectionFactory $consentCookieCollectionFactory
	 */
	public function __construct
	(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
		\Anowave\Ec\Model\ConsentCookieFactory $consentCookieFactory,
	    \Anowave\Ec\Model\ResourceModel\ConsentCookie\CollectionFactory $consentCookieCollectionFactory
	)
	{
		parent::__construct($context);
		
		/**
		 * Set response type factory 
		 * 
		 * @var \Magento\Framework\Controller\Result\JsonFactory
		 */
		$this->resultJsonFactory = $resultJsonFactory;

		/**
		 * Set cookie directive 
		 * 
		 * @var \Anowave\Ec\Controller\Index\Cookie $directive
		 */
		$this->consentCookieFactory = $consentCookieFactory;
		
		/**
		 * Set consent cookie collection factory 
		 * 
		 * @var \Anowave\Ec\Model\ResourceModel\ConsentCookie\CollectionFactory $consentCookieCollectionFactory
		 */
		$this->consentCookieCollectionFactory = $consentCookieCollectionFactory;
	}

	/**
	 * Execute controller
	 *
	 * @see \Magento\Framework\App\ActionInterface::execute()
	 */
	public function execute()
	{ 
	    /**
	     * Get cookies
	     * 
	     * @var array $cookies
	     */
	    $cookies = (array) $this->getRequest()->getParam('cookies');
	    
	    /**
	     * Default errors
	     * 
	     * @var array $errors
	     */
	    $errors = [];
	    
	    if ($cookies)
	    {
	        
	        $map = [];
	        
	        foreach($this->consentCookieCollectionFactory->create()->addFieldToFilter('cookie_name', ['in' => array_keys($cookies)]) as $entity)
	        {
	            $map[] = $entity->getCookieName();
	        }
	        
	        $cookies = array_filter($cookies,function ($key) use ($map) 
            {
                return !in_array($key, $map);
            },
            ARRAY_FILTER_USE_KEY);

			/**
			 * Get known cookies
			 * 
			 * @var []
			 */
			$known = $this->known();
	    
	        foreach ($cookies as $name => $value)
	        {
	            try 
	            {
    	            $cookie = $this->consentCookieFactory->create();
    	            
    	            $cookie->setCookieName($name);

					if (array_key_exists($name, $known))
					{
						$cookie->setCookieDescription($known[$name]['description']);
						$cookie->setCookieSegment($known[$name]['segment']);
					}

    	            $cookie->save();
	            }
	            catch (\Exception $e)
	            {
	                $errors[$name] = false;
	            }
	        }
	    }
	    
		return $this->resultJsonFactory->create()->setData($errors);
	}

	/**
	 * Get known cookies
	 * 
	 * @return array
	 */
	private function known() : array 
	{
		return 
		[
			'_ga' => 
			[
				'name' 			=> __('Google Analytics'),
				'description' 	=> __('Main cookie used by Google Analytics, enables the service to distinguish one visitor from another and lasts for 2 years.'),
				'segment'		=> Constants::COOKIE_CONSENT_ANALYTICS_GRANTED_EVENT
			],
			'_fbp' => 
			[
				'name' 			=> __('Meta'),
				'description' 	=> __('Facebook Pixel advertising first-party cookie. Used by Meta to track visits across websites to deliver a series of advertisement products such as real time bidding from third party advertisers.'),
				'segment'		=> Constants::COOKIE_CONSENT_MARKETING_GRANTED_EVENT
			],
			'mage-cache-sessid' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('The value of this cookie triggers the cleanup of local cache storage. Used by Magento.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'mage-messages' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('This cookie tracks error messages and other notifications that are shown to the user, such as the cookie consent message, and various error messages. Used by Magento.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'mage-cache-storage-section-invalidation' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Forces local storage of specific content sections that should be invalidated. Used by Magento.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'mage-cache-storage' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Forces local storage of specific content sections that should be invalidated. Used by Magento.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'mage-cache-storage' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Forces local storage of specific content sections that should be invalidated. Used by Magento.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'mage-cache-storage' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('A security measure that appends a random string to all form submissions to protect the data from Cross-Site Request Forgery (CSRF). Used by Magento.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'recently_compared_product_previous' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Used by Magento to store product IDs of previously compared products.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'recently_compared_product' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Used by Magento to store product IDs of recently compared products.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'recently_viewed_product_previous' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Used by Magento to store product IDs of recently previously viewed products for easy navigation.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'recently_viewed_product' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Used by Magento to store product IDs of recently viewed products for easy navigation.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			's_cc' => 
			[
				'name' 			=> __('Adobe'),
				'description' 	=> __('Adobe Site Catalyst cookie, determines whether cookies are enabled in the browser.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			's_fid' => 
			[
				'name' 			=> __('Adobe'),
				'description' 	=> __('Used as the fallback identification method going forward'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'X-Magento-Vary' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Used by Magento for configuration setting that improves performance when using Varnish static content caching.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'lang' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Session-based cookie that remembers the users selected language version of a website.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'form_key' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('A security measure that appends a random string to all form submissions to protect the data from Cross-Site Request Forgery (CSRF). Used by Magento.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'product_data_storage' => 
			[
				'name' 			=> __('Magento'),
				'description' 	=> __('Used by Magento to store configuration for product data related to Recently Viewed / Compared Products.'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'cookieConsentGranted' => 
			[
				'name' 			=> __('Consent'),
				'description' 	=> __('Used to track visitor choice regarding general cookie usage'),
				'segment'		=> Constants::COOKIE_CONSENT_GRANTED_EVENT
			],
			'cookieConsentMarketingGranted' => 
			[
				'name' 			=> __('Consent'),
				'description' 	=> __('Used to track visitor choice regarding marketing cookies'),
				'segment'		=> Constants::COOKIE_CONSENT_MARKETING_GRANTED_EVENT
			],
			'cookieConsentPreferencesGranted' => 
			[
				'name' 			=> __('Consent'),
				'description' 	=> __('Used to track visitor choice regarding preferences cookies'),
				'segment'		=> Constants::COOKIE_CONSENT_PREFERENCES_GRANTED_EVENT
			],
			'cookieConsentAnalyticsGranted' => 
			[
				'name' 			=> __('Consent'),
				'description' 	=> __('Used to track visitor choice regarding analytics cookies'),
				'segment'		=> Constants::COOKIE_CONSENT_ANALYTICS_GRANTED_EVENT
			],
			'cookieConsentUserdata' => 
			[
				'name' 			=> __('Consent'),
				'description' 	=> __('Used to track visitor choice regarding user data'),
				'segment'		=> Constants::COOKIE_CONSENT_AD_USER_DATA_EVENT
			],
			'cookieConsentPersonalization' => 
			[
				'name' 			=> __('Consent'),
				'description' 	=> __('Used to track visitor choice regarding ad personalization'),
				'segment'		=> Constants::COOKIE_CONSENT_AD_PERSONALIZATION_EVENT
			]
		];
	}
}