<?php

namespace FiloBlu\Storelocator\Model\Rma;

use Magento\Framework\App\Area;
use Magento\Rma\Model\Rma;

class History extends Rma\Status\History
{
    /**
     * Sending authorizing email with RMA data
     *
     * @param Rma $rma
     * @param string $rootConfig
     * @return $this
     * @throws \Magento\Framework\Exception\LocalizedException
     * @throws \Magento\Framework\Exception\MailException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    protected function _sendRmaEmailWithItems(Rma $rma, $rootConfig)
    {
        $storeId = $rma->getStoreId();
        $order = $rma->getOrder();

        $this->_rmaConfig->init($rootConfig, $storeId);
        if (!$this->_rmaConfig->isEnabled()) {
            return $this;
        }

        $this->inlineTranslation->suspend();

        $copyTo = $this->_rmaConfig->getCopyTo();
        $copyMethod = $this->_rmaConfig->getCopyMethod();

        if ($order->getCustomerIsGuest()) {
            $template = $this->_rmaConfig->getGuestTemplate();
            $customerName = $order->getBillingAddress()->getName();
        } else {
            $template = $this->_rmaConfig->getTemplate();
            $customerName = $rma->getCustomerName();
        }

        $sendTo = [['email' => $order->getCustomerEmail(), 'name' => $customerName]];
        if ($rma->getCustomerCustomEmail()) {
            $sendTo[] = ['email' => $rma->getCustomerCustomEmail(), 'name' => $customerName];
        }
        if ($copyTo && $copyMethod == 'copy') {
            foreach ($copyTo as $email) {
                $sendTo[] = ['email' => $email, 'name' => null];
            }
        }

        $returnAddress = $this->rmaHelper->getReturnAddress('html', [], $storeId);

        if ($order->getData('pickup_in_store_id')) {
            $returnAddress = $this->addressRenderer->format($order->getShippingAddress(), 'html');
        }


        $bcc = [];
        if ($copyTo && $copyMethod == 'bcc') {
            $bcc = $copyTo;
        }
        $store = $this->_storeManager->getStore($storeId);

        foreach ($sendTo as $recipient) {
            $transport = $this->_transportBuilder->setTemplateIdentifier($template)
                ->setTemplateOptions(['area' => Area::AREA_FRONTEND, 'store' => $storeId])
                ->setTemplateVars(
                    [
                        'rma' => $rma,
                        'rma_id' => $rma->getId(),
                        'rma_data' => [
                            'status_label' => is_string($rma->getStatusLabel()) ?
                                $rma->getStatusLabel() : $rma->getStatusLabel()->render(),
                        ],
                        'order' => $order,
                        'order_data' => [
                            'customer_name' => $order->getCustomerName(),
                        ],
                        'created_at_formatted_1' => $rma->getCreatedAtFormated(1),
                        'store' => $store,
                        'return_address' => $returnAddress,
                        'item_collection' => $rma->getItemsForDisplay(),
                        'formattedShippingAddress' => $this->addressRenderer->format(
                            $order->getShippingAddress(),
                            'html'
                        ),
                        'formattedBillingAddress' => $this->addressRenderer->format(
                            $order->getBillingAddress(),
                            'html'
                        ),
                        'supportEmail' => $store->getConfig('trans_email/ident_support/email'),
                        'storePhone' => $store->getConfig('general/store_information/phone'),
                    ]
                )
                ->setFrom($this->_rmaConfig->getIdentity())
                ->addTo($recipient['email'], $recipient['name'])
                ->addBcc($bcc)
                ->getTransport();

            $transport->sendMessage();
        }

        $this->setEmailSent(true);

        $this->inlineTranslation->resume();

        return $this;
    }
}
