<?php
namespace PortalPeople\GetAddressAutocomplete\Block\Checkout;

use Magento\Framework\View\Element\Template;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Csp\Helper\CspNonceProvider;

class ConfigBlock extends Template
{
    const XML_PATH_ENABLED = 'checkout/getaddress_autocomplete/enabled';
    const XML_PATH_API_KEY = 'checkout/getaddress_autocomplete/api_key';

    protected $scopeConfig;
    protected $jsonSerializer;
    protected $cspNonceProvider;

    public function __construct(
        Template\Context $context,
        ScopeConfigInterface $scopeConfig,
        Json $jsonSerializer,
        CspNonceProvider $cspNonceProvider,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->scopeConfig = $scopeConfig;
        $this->jsonSerializer = $jsonSerializer;
        $this->cspNonceProvider = $cspNonceProvider;
    }

    public function getCspNonce(): string
    {
        return (string)$this->cspNonceProvider->getNonce();
    }

    public function getAddressAutocompleteConfig()
    {
        $isEnabled = (bool)$this->scopeConfig->getValue(
            self::XML_PATH_ENABLED,
            ScopeInterface::SCOPE_STORE
        );

        $apiKey = $this->scopeConfig->getValue(
            self::XML_PATH_API_KEY,
            ScopeInterface::SCOPE_STORE
        );

        $hasApiKey = !empty(trim($apiKey));
        $isActive = $isEnabled && $hasApiKey;

        $config = [
            'getaddress_autocomplete' => [
                'enabled' => $isActive,
                'has_api_key' => $hasApiKey,
                'is_enabled_flag' => $isEnabled,
            ]
        ];

        return $this->jsonSerializer->serialize($config);
    }
}
