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

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

class OnepageConfigPlugin
{
    const XML_PATH_ENABLED = 'checkout/getaddress_autocomplete/enabled';
    const XML_PATH_API_KEY = 'checkout/getaddress_autocomplete/api_key';

    private $scopeConfig;

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

    /**
     * Inject config into checkoutConfig returned by Magento\Checkout\Block\Onepage
     *
     * @param Onepage $subject
     * @param array $result
     * @return array
     */
    public function afterGetCheckoutConfig(Onepage $subject, array $result)
    {
        $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((string)$apiKey));

        $result['getaddress_autocomplete'] = [
            'enabled' => $isEnabled && $hasApiKey,
            'has_api_key' => $hasApiKey,
            'is_enabled_flag' => $isEnabled,
        ];

        return $result;
    }
}
