<?php

namespace FiloBlu\Storelocator\Cron;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Psr\Log\LoggerInterface;

/**
 *
 */
class SendMissedStoreEmail
{
    /**
     * @var CollectionFactory
     */
    protected $orderCollectionFactory;
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @param CollectionFactory $orderCollectionFactory
     * @param Data $helper
     * @param LoggerInterface $logger
     */
    public function __construct(
        CollectionFactory $orderCollectionFactory,
        Data $helper,
        LoggerInterface $logger
    ) {
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->helper = $helper;
        $this->logger = $logger;
    }

    /**
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function execute()
    {

        $orders = $this->getPickuInStoreMissedOrders();

        foreach ($orders as $order) {
            if ($this->helper->canSendEmail($order)) {
                $this->helper->sendMail($order);
            }
        }
    }

    /**
     * @return \Magento\Sales\Model\ResourceModel\Order\Collection
     */
    public function getPickuInStoreMissedOrders()
    {
        $collection = $this->orderCollectionFactory->create();
        $collection->addAttributeToSelect('*')
            ->addFieldToFilter('pickup_in_store_id', ['notnull' => true ])
            ->addFieldToFilter('pickup_in_store_email_send_date', ['null' => true ])
            ->addFieldToFilter('status', ['eq' => 'complete' ]);

        return $collection;
    }
}
