<?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;

class SendEmail extends Action
{
    /**
     * @var OrderFactory
     */
    protected $orderFactory;
    /**
     * @var Data
     */
    protected $helper;

    /**
     * @param Context $context
     * @param Data $helper
     * @param OrderFactory $orderFactory
     */
    public function __construct(
        Context $context,
        Data $helper,
        OrderFactory $orderFactory
    )
    {
        $this->helper = $helper;
        $this->orderFactory = $orderFactory;
        parent::__construct($context);
    }

    public function execute()
    {

        $request = $this->getRequest();

        $orderId = $request->get('id');



        if ($orderId) {

            $order = $this->orderFactory->create()->load($orderId);

            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;

    }
}
