<?php

declare(strict_types=1);

namespace FiloBlu\Storelocator\Controller\Adminhtml\System;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;

/**
 *
 */
class Gmaps extends Action
{

    /**
     * @var \FiloBlu\Storelocator\Helper\Data
     */
    private $helperData;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \FiloBlu\Storelocator\Helper\Data $helperData
     */
    public function __construct(Context $context, Data $helperData)
    {
        parent::__construct($context);
        $this->helperData = $helperData;
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|(\Magento\Framework\Controller\Result\Json&\Magento\Framework\Controller\ResultInterface)|\Magento\Framework\Controller\ResultInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $response->setHttpResponseCode(200);
            $response->setData(['response' => $this->geocode('00184 Roma RM, Italia')]);
        } catch (Throwable $throwable) {
            $response->setHttpResponseCode(500);
            $response->setData(['response' => $throwable->getMessage()]);
        }

        return $response;
    }

    /**
     * @param $address
     * @return false|string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function geocode($address)
    {
        $address = urlencode($address);

        $key = $this->helperData->getConfig('filoblu_storelocator_section/general/gmaps_api_key_server_side');
        $url = $this->helperData->getConfig(
                'filoblu_storelocator_section/geocode/gmaps_geocode_api_url'
            ) . "?address=$address&key=$key";

        $response = file_get_contents($url);
        return json_encode(json_decode($response, true), JSON_PRETTY_PRINT);
    }
}
