<?php
declare(strict_types=1);

namespace Tanzsport\ContaoFormationenBundle\Controller\Api;

use Contao\BackendTemplate;
use Contao\Email;
use Contao\UserGroupModel;

trait EmailTrait
{
    public function mailen(\stdClass $data, string $template): bool
    {
        $template = new BackendTemplate($template);
        $template->data = $data;
        $template->dev = $this->isDev();

        $from = $this->getConfig('adminEmail');
        $to = [];
        $cc = [];
        $userGroups = UserGroupModel::findBy('td_erg_bereich', $data->liga->bereich);
        if ($userGroups) {
            while ($userGroups->next()) {
                $userGroup = $userGroups->current();
                if ($userGroup->td_erg_email && !in_array($userGroup->td_erg_email, $to)) {
                    $to[] = $userGroups->current()->td_erg_email;
                }
                if ($userGroup->td_erg_cc && !in_array($userGroup->td_erg_cc, $cc)) {
                    $cc[] = $userGroups->current()->td_erg_cc;
                }
            }
        }
        if (count($to) == 0) {
            $to[] = $from;
        }

        $email = new Email();
        $email->subject = $this->buildSubject($data);
        $email->from = $from;
        $email->html = $template->parse();
        $email->sendCc($cc);

        return $email->sendTo($to);
    }

    protected abstract function buildSubject(\stdClass $data): string;

    protected abstract function isDev(): bool;

    protected abstract function getConfig(string $key);
}
