<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

use Exception;
use FiloBlu\Storelocator\Helper\Data;
use FiloBlu\Storelocator\Model\ResourceModel\Stores\CollectionFactory;
use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Ui\Component\MassAction\Filter;

/**
 * Class MassGeocode
 */
class MassGeocode extends Action
{
    /**
     * @var Filter
     */
    protected $filter;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    /**
     * @var context
     */
    protected $context;

    /**
     * @var geocode
     */
    protected $geocode;

    /**
     * @var geocode
     */
    protected $helper;

    /**
     * @var \FiloBlu\Storelocator\Model\StoresFactory
     */
    private $storesFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \FiloBlu\Storelocator\Controller\Adminhtml\Stores\Geocode $geocode
     * @param \FiloBlu\Storelocator\Helper\Data $helper
     * @param \Magento\Ui\Component\MassAction\Filter $filter
     * @param \FiloBlu\Storelocator\Model\ResourceModel\Stores\CollectionFactory $collectionFactory
     * @param \FiloBlu\Storelocator\Model\StoresFactory $storesFactory
     */
    public function __construct(
        Context $context,
        Geocode $geocode,
        Data $helper,
        Filter $filter,
        CollectionFactory $collectionFactory,
        StoresFactory $storesFactory
    ) {
        $this->geocode = $geocode;
        $this->helper = $helper;
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        parent::__construct($context);
        $this->storesFactory = $storesFactory;
    }

    /**
     * Execute action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     * @throws \Magento\Framework\Exception\LocalizedException|\Exception
     */
    public function execute()
    {
        $collection = $this->filter->getCollection($this->collectionFactory->create());
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        $msgSuccess = '';
        $msgNotFound = '';

        foreach ($collection as $item) {
            $id = $item->getData('store_id');

            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->helper->geocode($address);

                    if ($geocodeData) {
                        $model->setLatitude($geocodeData[0]);
                        $model->setLongitude($geocodeData[1]);
                        $model->save();
                        $msgSuccess .= '</br>' . 'Geolocation data has been updated. Address found ' . $id . ' - ' . $geocodeData[2];
                    } else {
                        $msgNotFound .= '</br>' . "We can\'t find an address to update geolocation data for id " . $id;
                    }
                } catch (Exception $e) {
                    $this->messageManager->addError($e->getMessage());
                    return $resultRedirect->setPath('*/*/');
                }
            }
        }

        if ($msgSuccess) {
            $this->messageManager->addSuccess($msgSuccess);
        }

        if ($msgNotFound) {
            $this->messageManager->addError($msgNotFound);
        }

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        return $resultRedirect->setPath('*/*/');
    }

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