<?php
declare(strict_types=1);

namespace Autogedal\CookieLimit\Helper;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Stdlib\Cookie\PhpCookieManager;
use Magento\Store\Model\ScopeInterface;

/**
 * Helper class for cookie limit configuration
 */
class Config
{
    /**
     * Configuration path for maximum cookies
     */
    const CONFIG_PATH_MAX_COOKIES = 'autogedal_cookie/limits/max_cookies';

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(ScopeConfigInterface $scopeConfig)
    {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * Get the configured maximum number of cookies allowed
     *
     * @param string|null $scopeType
     * @param int|string|null $scopeCode
     * @return int
     */
    public function getMaxCookies($scopeType = ScopeInterface::SCOPE_STORE, $scopeCode = null): int
    {
        $configValue = $this->scopeConfig->getValue(
            self::CONFIG_PATH_MAX_COOKIES,
            $scopeType,
            $scopeCode
        );

        // If config value is 0, disable limit checking by returning a very high number
        if ($configValue === '0' || $configValue === 0) {
            return PHP_INT_MAX;
        }

        // If config value is not set or invalid, use the default RFC recommendation
        if (empty($configValue) || !is_numeric($configValue)) {
            return PhpCookieManager::MAX_NUM_COOKIES;
        }

        return (int)$configValue;
    }

    /**
     * Check if cookie limit checking is enabled
     *
     * @param string|null $scopeType
     * @param int|string|null $scopeCode
     * @return bool
     */
    public function isCookieLimitEnabled($scopeType = ScopeInterface::SCOPE_STORE, $scopeCode = null): bool
    {
        $configValue = $this->scopeConfig->getValue(
            self::CONFIG_PATH_MAX_COOKIES,
            $scopeType,
            $scopeCode
        );

        return $configValue !== '0' && $configValue !== 0;
    }
}