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

use Magento\PageCache\Model\DepersonalizeChecker;
use Anowave\Ec\Registry\CurrentCustomer;
use Anowave\Ec\Registry\CurrentCustomerGroup;
use Magento\Framework\View\LayoutInterface;
use Magento\Customer\Model\Session;

class DepersonalizePlugin
{
	/**
	 * @var DepersonalizeChecker
	 */
	protected $depersonalizeChecker;
	
	/**
	 * @var Session
	 */
	protected $customerSession;

	/**
	 * @var CurrentCustomer
	 */
	protected $currentCustomer;

	/**
	 * @var CurrentCustomerGroup
	 */
	protected $currentCustomerGroup;

	/**
	 * Constructor 
	 * 
	 * @param DepersonalizeChecker $depersonalizeChecker
	 * @param Session $customerSession
	 * @param CustomerGroup $customerGroup
	 */
	public function __construct
	(
		DepersonalizeChecker $depersonalizeChecker,
		Session $customerSession,
		CurrentCustomer $currentCustomer,
		CurrentCustomerGroup $currentCustomerGroup
	) 
	{
		/**
		 * Set depersonalize checker 
		 * 
		 * @var \DepersonalizeChecker $depersonalizeChecker
		 */
		$this->depersonalizeChecker = $depersonalizeChecker;
		$this->customerSession 		= $customerSession;
		$this->currentCustomer 		= $currentCustomer;
		$this->currentCustomerGroup = $currentCustomerGroup;
	}
	
	/**
	 * After generate Xml
	 *
	 * @param LayoutInterface $subject
	 * @param \Magento\Framework\View\LayoutInterface $result
	 * @return \Magento\Framework\View\LayoutInterface
	 */
	public function afterGenerateXml(LayoutInterface $subject, $result)
	{	  
		if (is_null($this->currentCustomer->get()) && 0 < (int) $this->customerSession->getCustomerId())
		{
			/**
			 * Register current customer
			 */
			$this->currentCustomer->set((int) $this->customerSession->getCustomerId());

			/**
			 * Register current customer group
			 */
			$this->currentCustomerGroup->set((int) $this->customerSession->getCustomerGroupId());
		}

		return $result;
	}
}