<?php

namespace Autogedal\Retragere\Model;

use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Framework\App\Area;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class Mail implements MailInterface
{
    private const XML_PATH_NOTIFY_EMAILS = 'retragere_settings/general/notify_emails';

    /**
     * @var TransportBuilder
     */
    private $transportBuilder;

    /**
     * @var StateInterface
     */
    private $inlineTranslation;

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    public function __construct(
        TransportBuilder $transportBuilder,
        StateInterface $inlineTranslation,
        ScopeConfigInterface $scopeConfig
    ) {
        $this->transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @inheritdoc
     */
    public function send($email, array $variables)
    {
        $storeId = $variables['data']['store_id'] ?? null;

        $this->inlineTranslation->suspend();
        try {
            $this->configureTransport($variables, $storeId)
                ->addTo($email)
                ->getTransport()
                ->sendMessage();

            foreach ($this->getNotifyEmails($storeId) as $notifyEmail) {
                $this->configureTransport($variables, $storeId)
                    ->addTo($notifyEmail)
                    ->getTransport()
                    ->sendMessage();
            }
        } finally {
            $this->inlineTranslation->resume();
        }
    }

    /**
     * @param array $variables
     * @param int|null $storeId
     * @return TransportBuilder
     */
    private function configureTransport(array $variables, $storeId)
    {
        return $this->transportBuilder
            ->setTemplateIdentifier('retragere_confirmare')
            ->setTemplateOptions(
                [
                    'area' => Area::AREA_FRONTEND,
                    'store' => $storeId ?? 1
                ]
            )
            ->setTemplateVars($variables)
            ->setFromByScope('general', $storeId);
    }

    /**
     * @param int|null $storeId
     * @return string[]
     */
    private function getNotifyEmails($storeId)
    {
        $emails = (string)$this->scopeConfig->getValue(
            self::XML_PATH_NOTIFY_EMAILS,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );

        if ($emails === '') {
            return [];
        }

        $result = [];
        foreach (explode(',', $emails) as $email) {
            $email = trim($email);
            if ($email !== '') {
                $result[] = $email;
            }
        }

        return $result;
    }
}
