<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Orders;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Sales\Model\OrderFactory;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;

class MassSendEmail extends Action
{
    /**
     * @var OrderFactory
     */
    protected $orderFactory;
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var Filter
     */
    protected $filter;
    /**
     * @var CollectionFactory
     */
    protected $orderCollectionFactory;

    /**
     * @param Context $context
     * @param Data $helper
     * @param OrderFactory $orderFactory
     * @param Filter $filter
     * @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
     */
    public function __construct(
        Context $context,
        Data $helper,
        OrderFactory $orderFactory,
        Filter $filter,
        CollectionFactory $orderCollectionFactory
    )
    {
        $this->helper = $helper;
        $this->orderFactory = $orderFactory;
        $this->filter = $filter;
        $this->orderCollectionFactory = $orderCollectionFactory;
        parent::__construct($context);
    }

    /**
     * Execute action based on request and return result
     *
     * @return \Magento\Framework\Controller\ResultInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function execute()
    {
        $orders = $this->filter->getCollection($this->orderCollectionFactory->create());

        if ($orders) {
            foreach ($orders as $order) {
                if ($this->helper->canSendEmail($order)) {
                    if ($this->helper->sendMail($order)) {
                        $this->messageManager->addSuccessMessage(sprintf('Store from order %s notified successfully!', $order->getIncrementId()));
                    } else {
                        $this->messageManager->addSuccessMessage(sprintf('Unable to notify store from order %s!', $order->getIncrementId()));
                    }
                } else  {
                    $this->messageManager->addErrorMessage(sprintf('Can not send email for order %s!', $order->getIncrementId()));
                }
            }
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setRefererUrl();
        return $resultRedirect;

    }
}
