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

use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class ConfigProvider implements ConfigProviderInterface
{
    const XML_PATH_ENABLED = 'checkout/getaddress_autocomplete/enabled';
    const XML_PATH_API_KEY = 'checkout/getaddress_autocomplete/api_key';

    protected $scopeConfig;

    public function __construct(
        ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    public function getConfig()
    {
        $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;

        // Always return the config structure so JavaScript knows about it
        $config = [
            'getaddress_autocomplete' => [
                'enabled' => $isActive,
                'has_api_key' => $hasApiKey,
                'is_enabled_flag' => $isEnabled,
            ]
        ];

        return $config;
    }
}

