<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

use FiloBlu\Storelocator\Model\Google\Api;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\View\Result\Page;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Ui\Component\MassAction\Filter;
use FiloBlu\Storelocator\Model\ResourceModel\Stores\CollectionFactory;

/**
 * Class MassSendGmb
 */
class MassSendGmb extends Action
{
    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var Filter
     */
    protected $filter;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;
    /**
     * @var \FiloBlu\Storelocator\Model\Google\Api
     */
    protected $googleApi;
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface|null
     */
    protected $config = null;


    /**
     * @param Context $context
     * @param Filter $filter
     * @param CollectionFactory $collectionFactory
     * @param Api $googleApi
     * @param ScopeConfigInterface $config
     */
    public function __construct(
        Context $context,
        Filter $filter,
        CollectionFactory $collectionFactory,
        Api $googleApi,
        ScopeConfigInterface $config
    ) {
        parent::__construct($context);
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        $this->googleApi = $googleApi;
        $this->config = $config;
    }

    /**
     * @return ResponseInterface|ResultInterface
     * @throws LocalizedException
     */
    public function execute()
    {
        if (!$this->config->getValue('filoblu_storelocator_section/google_my_business/gmb_enabled')) {
            $this->messageManager->addError(__('Google My Business Integration is not enabled'));
            return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/');
        }

        if ($this->googleApi->getClient()->isAccessTokenExpired()) {
            $this->messageManager->addError(__('Access token expired. Please go to [ System -> Configuration -> FiloBlu -> Storelocator -> Google My Business ] to login in'));
            return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/');
        }

        $collection = $this->filter->getCollection($this->collectionFactory->create());

        foreach ($collection as $store) {
            if ($store->getGmbLocationName()) {
                //                    $objReturn = $this->_googleApi->getLocation($store->getGmbLocationName());
                //                    $this->messageManager->addNotice(__('StoreID:' . $store->getId() . " already exists on Google My Business"));
                $objReturn = $this->googleApi->updateLocation($store->getGmbLocationName(), $store);

                if (is_string($objReturn)) {
                    $this->messageManager->addError(__('Error updating StoreID:' . $store->getId() . ' - Message: ' . $objReturn));
                } else {
                    $this->messageManager->addNotice(__('StoreID:' . $store->getId() . ' updated on Google My Business'));
                }
            } else {
                $objReturn = $this->googleApi->createLocation($store);

                if (is_string($objReturn)) {
                    $this->messageManager->addError(__('Error for StoreID:' . $store->getId() . ' - Message: ' . $objReturn));
                } else {
                    $store->setGmbLocationName($objReturn->getName());
                    $store->save();
                    $this->messageManager->addSuccess(__('StoreID:' . $store->getId() . ' created on Google My Business'));
                }
            }
        }


        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('*/*/');
    }

    /**
     * Is the user allowed to view the store grid.
     *
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('FiloBlu_Storelocator::storelocator');
    }
}
