<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

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

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

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

    protected $helperData;

    /**
     * @param Context $context
     * @param Filter $filter
     * @param CollectionFactory $collectionFactory
     * @param Data $helper
     */
    public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory, Data $helper)
    {
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        $this->helperData = $helper;
        parent::__construct($context);
    }

    /**
     * Execute action
     *
     * @return Redirect
     * @throws LocalizedException|Exception
     */
    public function execute()
    {
        $collection = $this->filter->getCollection($this->collectionFactory->create());

        $url_suffix = $this->helperData->getConfig('filoblu_storelocator_section/general/url_suffix');

        foreach ($collection as $item) {
            $urlKey = preg_replace(['/[^a-z0-9-]/i', '/[ ]{2,}/', '/[ ]/'], [' ', ' ', '-'], $item->getTitle());
            $urlKey .= '-' . substr(md5($item->getLatitude() . $item->getLongitude()), 0, 5) . $url_suffix;
            $item->setUrlKey(strtolower($urlKey));
            $item->save();
        }

        $this->messageManager
            ->addSuccessMessage(__('Completed url updated for a total of %1 record(s).', $collection->getSize()));

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