<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

use Exception;
use FiloBlu\Storelocator\Helper\Data;
use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\View\Result\Redirect;

/**
 *
 */
class Geocode extends Action
{
    /**
     * @var \FiloBlu\Storelocator\Model\StoresFactory
     */
    private $storesFactory;
    /**
     * @var \FiloBlu\Storelocator\Helper\Data
     */
    private $helperData;

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

    /**
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        /** @var Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {
                $model = $this->storesFactory->create();
                $model->load($id);
                $address = $model->getData('street') . ' ' .
                    $model->getData('postcode') . ' ' .
                    $model->getData('city') . ' ' .
                    $model->getData('country');

                $geocodeData = $this->helperData->geocode($address);
                if ($geocodeData) {
                    $model->setLatitude($geocodeData[0]);
                    $model->setLongitude($geocodeData[1]);
                    $model->save();
                    $this->messageManager->addSuccess(
                        __('Geolocation data has been updated. Address found ' . $geocodeData[2])
                    );
                } else {
                    $this->messageManager->addError(__('We can\'t find an address to update geolocation data.'));
                }

                return $resultRedirect->setPath('*/*/edit', ['id' => $id]);
            } catch (Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['id' => $id]);
            }
        }
        $this->messageManager->addError(__('We can\'t find a store to update geolocation data.'));
        return $resultRedirect->setPath('*/*/edit', ['id' => $this->getRequest()->getParam('id')]);
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('FiloBlu_Storelocator::storelocator_save');
    }
}