<?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\Framework\App\Config\ScopeConfigInterface;
use Anowave\Ec\Helper\Constants;
use Magento\Framework\App\Cache\StateInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Anowave\Ec\Registry\CurrentCustomerGroup;
use Magento\Framework\HTTP\Header;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Cache\Type\FrontendPool;


class Cache extends \Magento\Framework\Cache\Frontend\Decorator\TagScope
{
	const CACHE_LISTING 				= 'ec_cache_listing_';
	const CACHE_DETAILS 				= 'ec_cache_details_';
	const CACHE_LISTING_WIDGET 			= 'ec_cache_listing_widget_';
	const CACHE_LISTING_PRODUCT_WIDGET 	= 'ec_cache_listing_product_widget_';
	const CACHE_CATEGORY_TREE			= 'ec_cache_category_tree';
	
	/**
	 * Cache type code unique among all cache types
	 */
	const TYPE_IDENTIFIER = 'ec_cache';
	
	/**
	 * Cache tag used to distinguish the cache type from all other cache
	 */
	const CACHE_TAG = 'EC';
	
	/**
	 * @var StoreManagerInterface
	 */
	protected $storeManager;
	
	/**
	 * @var Header
	 */
	protected $headerService;

	/**
	 * @var StateInterface
	 */
	protected $cacheState;
	
	/**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

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

	/**
	 * Constructor 
	 * 
	 * @param FrontendPool $cacheFrontendPool
	 * @param StoreManagerInterface $storeManager
	 * @param Header $headerService
	 * @param CustomerRepositoryInterface $customerRepositoryFactory
	 * @param StateInterface $cacheState
	 * @param ScopeConfigInterface scopeConfig
	 */
	public function __construct
	(
		FrontendPool $cacheFrontendPool,
		StoreManagerInterface $storeManager,
		Header $headerService,
		CurrentCustomerGroup $currentCustomerGroup,
	    StateInterface $cacheState,
		ScopeConfigInterface $scopeConfig
	)
	{
		parent::__construct($cacheFrontendPool->get(static::TYPE_IDENTIFIER), static::CACHE_TAG);
		
		/**
		 * Set store manager
		 *
		 * @var \Magento\Store\Model\StoreManagerInterface $storeManager
		 */
		$this->storeManager = $storeManager;
		
		/**
		 * Set header service
		 *
		 * @var \Anowave\Ec\Model\Cache $headerService
		 */
		$this->headerService = $headerService;

		/** 
		 * @var CurrentCustomerGroup
		 */
		$this->currentCustomerGroup = $currentCustomerGroup;

		/**
		 * @var StateInterface $cacheState
		 */
		$this->cacheState = $cacheState;

		/** 
		 * @var ScopeConfigInterface
		 */
		$this->scopeConfig = $scopeConfig;
	}
	
	/**
	 * Enforce marking with a tag
	 *
	 * {@inheritdoc}
	 */
	public function save($data, $identifier, array $tags = [], $lifeTime = null)
	{
		if (!$this->useCache())
		{
			return false;
		}
		
		return parent::save(serialize($data), $this->getCacheId($identifier), [static::CACHE_TAG], 600);
	}
	
	/**
	 * Load cache
	 *
	 * @see \Magento\Framework\Cache\Frontend\Decorator\Bare::load()
	 */
	public function load($identifier)
	{ 
		if (!$this->useCache())
		{
			return false;
		}
		
		return unserialize($this->_getFrontend()->load($this->getCacheId($identifier)));
	}
	
	/**
	 * Generate unique cache id
	 *
	 * @param string $prefix
	 */
	protected function generateCacheId($prefix)
	{
		/**
		 * Push current store to make cache store specific
		 *
		 * @var int
		 */
		$p[] = (int) $this->storeManager->getStore()->getId();
		
		/**
		 * Add website id
		 */
		$p[] = (int) $this->storeManager->getStore()->getWebsiteId();
		
		/**
		 * Add currency
		 */
		$p[] = (string) $this->storeManager->getStore()->getCurrentCurrencyCode();
		
		/**
		 * Check for mobile users
		 */
		if (version_compare(phpversion(), '8.0.0', '<')) 
		{
		    $p[] = \Zend_Http_UserAgent_Mobile::match($this->headerService->getHttpUserAgent(),$_SERVER);
		}
		else 
		{
		    if (!(php_sapi_name() == 'cli'))
		    {
		        if(!empty($_SERVER['HTTP_USER_AGENT']))
		        {
		            $p[] = preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
		        };
		    }
		    else 
		    {
		        $p[] = php_sapi_name();
		    }
		}
		
		/**
		 * Push request URI
		 *
		 * @var string
		 */
		$p[] = $_SERVER['REQUEST_URI'];
		
		foreach (array($_GET, $_POST, $_FILES) as $request)
		{
			if ($request)
			{
				$p[] = $request;
			}
		}

		if ($this->currentCustomerGroup->get() > 0)
		{
			$p[] = (int) $this->currentCustomerGroup->get();
		}

		/**
		 * Add current currency
		 */
		$p[] =  $this->scopeConfig->getValue(Constants::CONFIG_PATH_CURRENCY_CONVERT,\Magento\Store\Model\ScopeInterface::SCOPE_STORE,$this->storeManager->getStore()->getId());

		$p = md5(serialize($p));
		
		/**
		 * Merge
		 */
		return "{$prefix}_{$p}";
	}
	
	/**
	 * Getenerate unique cache id
	 *
	 * @param string $identifier
	 */
	public function getCacheId($identifier)
	{
		return $this->generateCacheId($identifier);
	}
	
	/**
	 * Check if can use cache
	 *
	 * @return bool
	 */
	protected function useCache()
	{
	    return $this->cacheState->isEnabled(static::TYPE_IDENTIFIER);
	}
}