<?php

namespace FiloBlu\Storelocator\Helper;

use Exception;
use FiloBlu\Storelocator\Model\Rma\Returntostore;
use FiloBlu\Storelocator\Model\StoresFactory;
use FiloBlu\Storelocator\Model\TagsFactory;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Area;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Asset\Repository;
use Magento\Rma\Api\RmaRepositoryInterface;
use Magento\Rma\Model\Shipping;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Address\Renderer;
use Magento\Store\Model\App\Emulation;
use Magento\Store\Model\Information;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;

use function array_key_exists;
use function in_array;
use function is_array;
use function is_string;

/**
 *
 */
class Data extends AbstractHelper
{
    /**
     * @var string
     */
    const CONFIG_IMAGE_DIR_PREFIX = 'filoblu/storelocator/';
    /**
     * @var string
     */
    const STORES_IMAGE_DIR_PREFIX = 'filoblu/storelocator/stores/image/';
    /**
     * @var StoreManagerInterface
     */
    protected $_storeManager;
    /**
     * @var Returntostore
     */
    protected $_returntostore;
    /**
     * @var StateInterface
     */
    protected $_inlineTranslation;
    /**
     * @var \Magento\Payment\Helper\Data
     */
    protected $_paymentHelper;
    /**
     * @var TransportBuilder
     */
    protected $_transportBuilder;
    /**
     * @var Renderer
     */
    protected $_addressRenderer;
    /**
     * @var \Magento\Rma\Helper\Data
     */
    protected $_rmaData;
    /**
     * @var State
     */
    protected $state;
    /**
     * @var Emulation
     */
    protected $appEmulation;
    /**
     * @var RegionFactory
     */
    protected $regionFactory;
    /**
     * @var StoresFactory
     */
    protected $storesFactory;
    /**
     * @var DateTime
     */
    protected $date;
    /**
     * @var TagsFactory
     */
    private $_tagsFactory;
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;
    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;
    /**
     * @var \Magento\Framework\View\Asset\Repository
     */
    private $assetRepo;
    /**
     * @var \Magento\Framework\App\RequestInterface
     */
    private $request;
    /**
     * @var \Magento\Framework\UrlInterface
     */
    private $urlBuilder;
    /**
     * @var \Magento\Rma\Api\RmaRepositoryInterface
     */
    private $rmaRepository;
    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    private $resourceConnection;

    /**
     * @param Context $context
     * @param StoreManagerInterface $storeManager
     * @param Repository $assetRepo
     * @param Returntostore $_returntostore
     * @param TagsFactory $_tagsFactory
     * @param OrderRepositoryInterface $orderRepository
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param RegionFactory $regionFactory
     * @param StoresFactory $storesFactory
     * @param StateInterface $inlineTranslation
     * @param \Magento\Payment\Helper\Data $paymentHelper
     * @param TransportBuilder $transportBuilder
     * @param Renderer $addressRenderer
     * @param \Magento\Rma\Helper\Data $rmaData
     * @param State $state
     * @param Emulation $appEmulation
     * @param DateTime $date
     * @param \Magento\Rma\Api\RmaRepositoryInterface $rmaRepository
     * @param \Magento\Framework\App\ResourceConnection $resourceConnection
     */
    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager,
        Repository $assetRepo,
        Returntostore $_returntostore,
        TagsFactory $_tagsFactory,
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        RegionFactory $regionFactory,
        StoresFactory $storesFactory,
        StateInterface $inlineTranslation,
        \Magento\Payment\Helper\Data $paymentHelper,
        TransportBuilder $transportBuilder,
        Renderer $addressRenderer,
        \Magento\Rma\Helper\Data $rmaData,
        State $state,
        Emulation $appEmulation,
        DateTime $date,
        RmaRepositoryInterface $rmaRepository,
        ResourceConnection $resourceConnection
    ) {
        $this->_storeManager = $storeManager;
        $this->scopeConfig = $context->getScopeConfig();
        $this->assetRepo = $assetRepo;
        $this->request = $context->getRequest();
        $this->urlBuilder = $context->getUrlBuilder();
        $this->_returntostore = $_returntostore;
        $this->_tagsFactory = $_tagsFactory;
        $this->orderRepository = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->regionFactory = $regionFactory;
        $this->storesFactory = $storesFactory;
        $this->_inlineTranslation = $inlineTranslation;
        $this->_paymentHelper = $paymentHelper;
        $this->_transportBuilder = $transportBuilder;
        $this->_addressRenderer = $addressRenderer;
        $this->_rmaData = $rmaData;
        $this->state = $state;
        $this->appEmulation = $appEmulation;
        $this->date = $date;
        $this->rmaRepository = $rmaRepository;
        parent::__construct($context);
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * @param $address
     * @return array|false
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function geocode($address)
    {
        // url encode the address
        $address = urlencode($address);

        // google map geocode api url
        $key = $this->getConfig('filoblu_storelocator_section/general/gmaps_api_key_server_side');
        $url = $this->getConfig(
            'filoblu_storelocator_section/geocode/gmaps_geocode_api_url'
        ) . "?address=$address&key=$key";

        // get the json response
        $resp_json = file_get_contents($url);

        // decode the json
        $resp = json_decode($resp_json, true);

        // response status will be 'OK', if able to geocode given address
        if ($resp['status'] !== 'OK') {
            return false;
        }

        // get the important data
        $lati = $resp['results'][0]['geometry']['location']['lat'];
        $longi = $resp['results'][0]['geometry']['location']['lng'];
        $formatted_address = $resp['results'][0]['formatted_address'];

        // verify if data is complete
        if (!$lati || !$longi || !$formatted_address) {
            return false;
        }
        // put the data in the array
        $data_arr = [];

        array_push(
            $data_arr,
            $lati,
            $longi,
            $formatted_address
        );

        return $data_arr;
    }

    /**
     * @param $config_path
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getConfig($config_path, $storeId = 0)
    {
        if (!$storeId) {
            $storeId = $this->_storeManager->getStore()->getId();
        }

        return $this->scopeConfig->getValue(
            $config_path,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }


    /**
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getBaseUrlConfigImage()
    {
        return $this->_storeManager->getStore()->getBaseUrl(
            UrlInterface::URL_TYPE_MEDIA
        ) . self::CONFIG_IMAGE_DIR_PREFIX;
    }

    /**
     * @return string by erry
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getBaseUrl()
    {
        return $this->_storeManager->getStore()->getBaseUrl();
    }

    /**
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getBaseUrlStoresImage()
    {
        return $this->_storeManager->getStore()->getBaseUrl(
            UrlInterface::URL_TYPE_MEDIA
        ) . self::STORES_IMAGE_DIR_PREFIX;
    }

    /**
     * @param $fileId
     * @param array $params
     * @return mixed by erry
     */
    public function getViewFileUrl($fileId, array $params = [])
    {
        try {
            $params = array_merge(['_secure' => $this->request->isSecure()], $params);
            return $this->assetRepo->getUrlWithParams($fileId, $params);
        } catch (LocalizedException $e) {
            return $this->urlBuilder->getUrl('', ['_direct' => 'core/index/notFound']);
        }
    }

    /**
     * @param null $orderId
     * @return array
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getTagFilterHandle($orderId = null)
    {
        // READ TAGS
        $alltags = $this->_tagsFactory->create()->getAllAvailableTags();
        $tags = [];

        if (count($alltags) > 0) {
            foreach ($alltags as $tag) {
                $tags[$tag->getName()] = $tag->getId();
            }
        }

        if (!is_null($orderId) &&
            $this->getTagFiltersEnabled() == 1 &&
            is_array($this->getTagFiltersLabels()) &&
            is_array($this->getTagCategoryFilterIds())) {
            $categories = $this->_returntostore->getItemsCategoriesByOrderId($orderId);
            $setting = [];
            $flatted_categories = [];
            $counter = 0;
            array_walk_recursive($categories, static function ($a) use (&$flatted_categories) {
                $flatted_categories[] = $a;
            }); // flat multidimensional array
            $categories = $flatted_categories;
            $tag_setting = $this->getTagFiltersLabels();
            if (is_array($this->getTagCategoryFilterIds())) {
                $setting = $this->getTagCategoryFilterIds();
            }
            foreach ($categories as $cat) {
                if (in_array($cat, $setting)) { // $cat = all my categories  $setting = my outlet ids
                    $counter++;
                }
            }

            if ($counter > 0) {
                // outlet result -> consider Storelocator Setting tag ids

                foreach ($tags as $key => $tag_ids) {
                    if (is_array($tag_setting) && !in_array($key, $tag_setting)) {
                        unset($tags[$key]);
                    }
                }
            } else {
                // monobrand result -> consider tag ids excluded
                foreach ($tags as $key => $tag_ids) {
                    if (is_array($tag_setting) && in_array($key, $tag_setting)) {
                        unset($tags[$key]);
                    }
                }
            }
        }
        return $tags;
    }

    /**
     * @return mixed by erry
     */
    public function getTagFiltersEnabled()
    {
        return $this->scopeConfig->getValue(
            'filoblu_storelocator_section/return_to_store/enable_tag_filter_by_category',
            ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * @return false|string[]
     */
    public function getTagFiltersLabels()
    {
        $enabled = $this->getTagFiltersEnabled();
        $return = false;
        if ($enabled == '1') {
            $params = $this->scopeConfig->getValue(
                'filoblu_storelocator_section/return_to_store/tag_filter_by_category',
                ScopeInterface::SCOPE_STORE
            );
            $params = unserialize($params);
            foreach ($params as $label) {
                if (array_key_exists('tag_filter_label', $label)) {
                    $return = $label['tag_filter_label'];
                    $return = explode(',', $return);
                }
            }
        }
        return $return;
    }

    /**
     * @return false|string[]
     */
    public function getTagCategoryFilterIds()
    {
        $enabled = $this->scopeConfig->getValue(
            'filoblu_storelocator_section/return_to_store/enable_tag_filter_by_category',
            ScopeInterface::SCOPE_STORE
        );
        $return = false;
        if ($enabled == '1') {
            $params = $this->scopeConfig->getValue(
                'filoblu_storelocator_section/return_to_store/tag_filter_by_category',
                ScopeInterface::SCOPE_STORE
            );
            $params = unserialize($params);
            foreach ($params as $ids) {
                if (array_key_exists('tag_category_filter_id', $ids)) {
                    $return = $ids['tag_category_filter_id'];
                    $return = explode(',', $return);
                }
            }
        }
        return $return;
    }

    /**
     * @param $orderId
     * @return array|null
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getItemsCategoriesByOrderId($orderId = null)
    {
        return $this->_returntostore->getItemsCategoriesByOrderId($orderId);
    }

    /**
     * @param $hash
     * @return OrderInterface
     * @throws NoSuchEntityException
     */
    public function getOrderByHash($hash)
    {
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('pickup_in_store_hash', $hash)
            ->addFilter('shipping_method', $this->getAllowedShippingMethods(), 'in')
            ->create();

        $result = $this->orderRepository->getList($searchCriteria)->getItems();
        $order = array_shift($result);
        if (!$order) {
            throw NoSuchEntityException::singleField('hash', $hash);
        }

        return $order;
    }

    /**
     * @param $hash
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getRmaByHash($hash){
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('return_to_store_hash', $hash)
            ->create();

        $result = $this->rmaRepository->getList($searchCriteria)->getItems();
        $rma = array_shift($result);
        if (!$rma) {
            throw NoSuchEntityException::singleField('hash', $hash);
        }

        return $rma;
    }

    /**
     * @param OrderInterface $order
     */
    public function saveOrder(OrderInterface $order)
    {
        $this->orderRepository->save($order);
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getPickupInStoreEnabled($storeId = 0)
    {
        return $this->getConfig('carriers/pickupinstore/active', $storeId);
    }

    /**
     * @param $storeId
     * @return mixed
     */
    public function getReturnToStoreEnabled($storeId = 0)
    {
        return $this->scopeConfig->getValue(
            'carriers/returninstore/pickrma_enable',
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getRmaMailCopyTo($storeId = 0)
    {
        return $this->getConfig('sales_email/magento_rma/copy_to', $storeId);
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getCustomercareTestEmail($storeId = 0)
    {
        return $this->getConfig('carriers/returninstore/pickrma_customercare_test_email_recipient', $storeId);
    }

    /**
     * @param $rma
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function sendRmaMail($rma)
    {
        if ($this->state->getAreaCode() === 'adminhtml') {
            $this->state->emulateAreaCode(
                Area::AREA_FRONTEND,
                [$this, '_sendRmaMail'],
                [$rma]
            );
        } else {
            $this->_sendRmaMail($rma);
        }
    }

    /**
     * @param $rma
     * @return void
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function _sendRmaMail($rma)
    {
        $storeId = $this->_storeManager->getStore()->getId();

        if (!$this->getRmaToStoreEnabled($storeId)) {
            return;
        }

        $storeDetailsId = $rma->getData('return_to_store_id');
        $shop = $this->getStoreDetails($storeDetailsId);

        $rmaStoreId = $rma->getStoreId();


        $customerCareEmail = $this->getCustomercareEmail($storeId);
        $returnToStoreEmail = $rma->getReturnToStoreEmail($storeId);

        $mailReceiver = $returnToStoreEmail ?: $customerCareEmail;

        $this->_inlineTranslation->suspend();

        $this->appEmulation->startEnvironmentEmulation($rmaStoreId);

        $mailTo = $this->getConfig('carriers/returninstore/pickrma_sender_email_to_store_identity', $storeId);

        $template = $this->getConfig('carriers/returninstore/pickrma_email_to_store_template', $storeId);

        $data = [];

        if (!$this->getUseStandardRmaMailFlow($storeId) && (int)$rma->getReturnToStoreId($storeId)) {
            if ($rma->getStatus() === 'pending') {
                $mailReceiver = $customerCareEmail;
                $template = $this->getReturnInStoreEmailTemplate($storeId);
            }

            if ($rma->getStatus() === 'authorized') {
                $data = $this->getStoreDetails($storeId);

                if ($this->getUseTestEmailRecipients($storeId) && $this->getStoreTestEmail($storeId))
                {
                    $mailReceiver = $this->getStoreTestEmail($storeId);
                }
            }
        }

        try {
            $returnAddress = $this->_rmaData->getReturnAddress('html', $data, $storeId);
            $order = $rma->getOrder();

            $transport = $this->_transportBuilder
                ->setTemplateIdentifier($template)
                ->setTemplateOptions(
                    [
                        'area'  => Area::AREA_FRONTEND,
                        'store' => $rmaStoreId //$this->_storeManager->getStore()->getStoreId()
                    ]
                )
                ->setFromByScope($mailTo, $rmaStoreId)
                ->setTemplateVars(
                    [
                        'rma'                        => $rma,
                        'order'                      => $order,
                        'order_id'                   => $order->getId(),
                        'order_increment_id'         => $order->getIncrementId(),
                        'order_is_virtual'           => $order->getIsVirtual(),
                        'order_is_not_virtual'       => !$order->getIsVirtual(),
                        'order_store_id'             => $order->getStoreId(),
                        'order_pickup_in_store_hash' => $order->getPickupInStoreHash(),
                        'order_email_customer_note'  => $order->getEmailCustomerNote(),
                        'shop'                       => $shop,
                        'store'                      => $rma->getOrder()->getStore(),
                        'billing'                    => $order->getBillingAddress(),
                        'payment_html'               => $this->_paymentHelper->getInfoBlockHtml(
                            $order->getPayment(),
                            $this->_storeManager->getStore()->getId()
                        ),
                        'return_address'           => $returnAddress,
                        'item_collection'          => $rma->getItemsForDisplay(),
                        'formattedShippingAddress' => $this->_addressRenderer->format(
                            $order->getShippingAddress(),
                            'html'
                        ),
                        'formattedBillingAddress'  => $this->_addressRenderer->format(
                            $order->getBillingAddress(),
                            'html'
                        ),
                        'sendRejectionEmail'       => true,
                        'rma_data' => [
                            'return_to_store_hash' => $rma->getReturnToStoreHash(),
                            'store_id'             => $rma->getStoreId(),
                        ]
                    ]
                )
                ->addTo($mailReceiver)
                ->getTransport();
            $transport->sendMessage();

            $this->_inlineTranslation->resume();
            $this->appEmulation->stopEnvironmentEmulation();
        } catch (Exception $exception) {
            $this->_inlineTranslation->resume();
            $this->appEmulation->stopEnvironmentEmulation();
            $this->_logger->error($exception->getMessage(), ['exception' => $exception]);
        }
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getRmaToStoreEnabled($storeId = 0)
    {
        return $this->getConfig('carriers/returninstore/pickrma_email_to_store_enabled', $storeId);
    }

    /**
     * @param $storeId
     * @return array
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getStoreDetails($storeId)
    {
        $store = $this->storesFactory->create()->load($storeId);

        return [
            'city'      => $store->getCity(),
            'countryId' => null,
            'postcode'  => $store->getPostcode(),
            'region_id' => $store->getRegionId(),
            'street1'   => $store->getStreet(),
            'street2'   => null,
            'firstname' => $this->getConfig(Shipping::XML_PATH_CONTACT_NAME),
            'country'   => $store->getCountry(),
            'region'    => $store->getRegion(),
            'company'   => $store->getTitle(),
            'telephone' => $this->getConfig(Information::XML_PATH_STORE_INFO_PHONE),
            'email'     => null,// Information::XML_PATH_STORE_INFO_PHONE,
        ];
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getCustomercareEmail($storeId = 0)
    {
        return $this->getConfig('carriers/returninstore/pickrma_customercare_email_recipient', $storeId);
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getUseStandardRmaMailFlow($storeId = 0)
    {
        return $this->getConfig('carriers/returninstore/pickrma_use_standard_mail_flow', $storeId);
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getReturnInStoreEmailTemplate($storeId = 0)
    {
        return $this->getConfig('carriers/returninstore/pickrma_customercare_mail_template', $storeId);
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getUseTestEmailRecipients($storeId = 0)
    {
        return $this->getConfig('carriers/returninstore/pickrma_use_test_email_recipients', $storeId);
    }

    /**
     * @param $storeId
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getStoreTestEmail($storeId = 0)
    {
        return $this->getConfig('carriers/returninstore/pickrma_store_test_email_recipient', $storeId);
    }

    /**
     * @param OrderInterface | Order $order
     * @return bool
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function canSendEmail($order): bool
    {
        if (!$this->getConfig('carriers/pickupinstore/active', $order->getStoreId())) {
            return false;
        }

        $selectedOrderStatus = $this->getConfig('carriers/pickupinstore/sender_email_order_status');

        if ($order->getStatus() != $selectedOrderStatus) {
            return false;
        }

        if (!$order->getPickupInStoreEmail()) {
            return false;
        }

        if (!$this->isOrderedWithPickUpInStore($order)) {
            return false;
        }

        if (!$order->getShippingAddress()) {
            return false;
        }

        if (!$this->isAllowedShippingMethods($order)) {
            return false;
        }

        if ($order->getPickupInStoreEmailSendDate()) {
            return false;
        }

        return true;
    }

    /**
     * @param OrderInterface $order
     * @return bool
     */
    public function isOrderedWithPickUpInStore(OrderInterface $order)
    {
        if (!$order->getData('pickup_in_store_id')) {
            return false;
        }

        return true;
    }

    /**
     * @param  OrderInterface $order
     * @return bool
     * @throws NoSuchEntityException
     */
    public function sendMail($order)
    {
        if (!$this->getConfig('carriers/pickupinstore/email_to_store_enabled')) {
            return false;
        }

        // Check if email to store is disabled per specific store
        $store = $this->storesFactory->create()->load($order->getData('pickup_in_store_id'));

        if($store->getData('email_to_store_disabled')){
            return false;
        }

        $this->_inlineTranslation->suspend();

        $billingAddress = $order->getBillingAddress();

        $templateVars = [
            'order'                      => $order,
            'order_id'                   => $order->getId(),
            'order_increment_id'         => $order->getIncrementId(),
            'order_is_virtual'           => $order->getIsVirtual(),
            'order_is_not_virtual'       => !$order->getIsVirtual(),
            'order_store_id'             => $order->getStoreId(),
            'order_pickup_in_store_hash' => $order->getPickupInStoreHash(),
            'order_email_customer_note'  => $order->getEmailCustomerNote(),
            'billing'                    => $billingAddress,
            'payment_html'               => $this->getPaymentHtml($order),
            'store'                      => $order->getStore(),
            'addresses'                  => $order->getAddresses(),
            'formattedShippingAddress'   => $this->getFormattedShippingAddress($order),
            'formattedBillingAddress'    => $this->getFormattedBillingAddress($order),
            'order_data'                 => [
                'pickup_in_store_hash' => $order->getData('pickup_in_store_hash'),
                'id'                   => $order->getId(),
                'increment_id'         => $order->getIncrementId(),
                'is_not_virtual'       => !$order->getIsVirtual(),
                'store_id'             => $order->getStoreId(),
                'email_customer_note'  => $order->getEmailCustomerNote(),
                'created_at_formatted'  => $order->getCreatedAtFormatted(2),
            ]
        ];

        $templateOptions = [
            'area'  => Area::AREA_FRONTEND,
            'store' => $this->_storeManager->getStore()->getStoreId(),
        ];

        try {
            $this->_transportBuilder
                ->setTemplateIdentifier($this->getConfig('carriers/pickupinstore/email_to_store_template'))
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars($templateVars)
                ->setFrom($this->getConfig('carriers/pickupinstore/sender_email_to_store_identity'))
                ->addTo($order->getPickupInStoreEmail());

            $bcc = $this->getConfig('carriers/pickupinstore/email_to_store_bcc_email');
            if (is_string($bcc) && $bcc != '') {
                $this->_transportBuilder->addBcc(explode(',', $bcc));
            }

            $transport = $this->_transportBuilder->getTransport();
            $transport->sendMessage();

            $this->_inlineTranslation->resume();

            //Save Email send Date
            $order->setPickupInStoreEmailSendDate($this->date->gmtDate());
            $this->orderRepository->save($order);

            return true;
        } catch (Exception $exception) {
            $this->_inlineTranslation->resume();
            $this->_logger->error($exception->getMessage(), ['exception' => $exception]);
        }

        return false;
    }

    /**
     * @param $order
     * @return string
     * @throws NoSuchEntityException
     */
    public function getPaymentHtml($order)
    {
        return $this->_paymentHelper->getInfoBlockHtml(
            $order->getPayment(),
            $this->_storeManager->getStore()->getId()
        );
    }

    /**
     * @param $order
     * @return string|null
     */
    public function getFormattedShippingAddress($order)
    {
        return $order->getIsVirtual()
            ? null
            : $this->_addressRenderer->format($order->getShippingAddress(), 'html');
    }

    /**
     * @param $order
     * @return string|null
     */
    public function getFormattedBillingAddress($order)
    {
        return $this->_addressRenderer->format($order->getBillingAddress(), 'html');
    }

    /**
     * @param Order $order
     * @return bool
     */
    public function isAllowedShippingMethods($order) {
        return in_array($order->getShippingMethod(), $this->getAllowedShippingMethods(), true);
    }

    /**
     * @return string[]
     */
    public function getAllowedShippingMethods(){
        return [
            'pickupinstore_pickupinstore',
            'viewide_shipping_viewide_shipping'
        ];
    }

    /**
     * @param \Magento\Quote\Model\Quote|\Magento\Quote\Api\Data\CartInterface $quote
     * @return bool
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function canSendEmailToStore($quote) {

        if($this->getConfig('carriers/pickupinstore/email_to_store_enabled', $quote->getStoreId())) {
            return false;
        }

        $connection = $this->resourceConnection->getConnection();

        $select = $connection->select()
                             ->from(
                                 'filoblu_storelocator_stores',
                                 ['email_to_store_disabled']
                             );

        if($quote->getPickupInStoreId()){
            $select->where('store_id = ?', $quote->getPickupInStoreId());
        }

        if($quote->getPickupInStoreCode()) {
            $select->where('store_code = ?', $quote->getPickupInStoreCode());
        }

        $emailToStoreDisabled = $connection->fetchOne($select);

        return !$emailToStoreDisabled;
    }
}
