<?php

namespace Velis\Notification;

use LogicException;
use Velis\App;
use Velis\Bpm\User;

class MailRecipients
{
    /**
     * @var Recipient[]
     */
    protected array $recipients = [];


    /**
     * @param array $recipients
     */
    public function __construct(array $recipients = [])
    {
        foreach ($recipients as $recipient) {
            $this->add($recipient);
        }
    }

    public function add($recipient)
    {
        if (!$recipient) {
            return;
        }

        if (!($recipient instanceof Recipient)) {
            throw new LogicException('Recipient must be instance of \Velis\Notification\Recipient interface');
        }

        if ($recipient instanceof User && !$recipient->isActive() && !$recipient['signUp'] && !$recipient['bidUser']) {
            if (!App::demoMode() || !$recipient->isDemoAccount()) {
                return;
            }
        }

        if (!$recipient->getEmail()) {
            return;
        }

        $this->recipients[] = $recipient;
    }

    /**
     * @return Recipient[][]
     */
    public function groupByLanguage(): array
    {
        $byLang = [];
        foreach ($this->recipients as $recipient) {
            $language = $recipient->lang_id ?? null;
            $language = $language ?: App::$config->settings->defaultLanguage;

            $byLang[$language][] = $recipient;
        }

        return $byLang;
    }


    public function get(): array
    {
        return array_filter($this->recipients);
    }


    public function groupByLangAndLayout()
    {
        $grouppedRecipients = [];
        $recipients = $this->groupByLanguage();
        foreach ($recipients as $langId => $langRecipients) {
            foreach ($langRecipients as $key => $recipient) {
                if ($recipient instanceof User && $recipient->hasCustomMailTemplate()) {
                    $grouppedRecipients[App::$config->notifications->customerTemplate ?: 'default'][$langId][$key] = $recipient;
                } else {
                    $grouppedRecipients['default'][$langId][$key] = $recipient;
                }
            }
        }
        return $grouppedRecipients;
    }
}
