<?php

namespace KupShop\KupShopBundle\Email;

class UserRegisterEmail extends BaseEmail
{
    protected static $name = 'Registrace uživatele';
    protected static $type = 'USER_REGISTER';
    protected static $priority = 0;

    protected $subject = 'Právě jsme Vás zaregistrovali';
    protected $template = 'email/email_user_register.tpl';

    protected \User $user;

    public static string $type_test_email = 'users';

    public function testEmail(): array
    {
        if (!isset($this->user)) {
            $this->setTestEntity();
        }

        return parent::testEmail();
    }

    public static function getPlaceholders()
    {
        $placeholders = [
            'EMAIL_UZIVATELE' => [
                'text' => 'E-mail uživatele',
            ],
        ];

        return [self::$type => $placeholders] + (parent::getPlaceholders() ?? []);
    }

    public function replacePlaceholdersItem($placeholder)
    {
        if ($placeholder == 'EMAIL_UZIVATELE') {
            return $this->user->email;
        }

        return parent::replacePlaceholdersItem($placeholder);
    }

    public function sendEmail($message, $logComment = null)
    {
        if ($bcc = (\Settings::getDefault()->archive_email ?? null)) {
            $message['bcc'] = [$bcc];
        }

        return parent::sendEmail($message);
    }

    public function setTestEntity(?string $id = null): void
    {
        $user = (new \User())::createFromId($id ?: sqlQueryBuilder()->select('MAX(id)')->from('users')->execute()->fetchOne());
        $this->setUser($user);
    }

    public function getTestType(): ?string
    {
        return self::$type_test_email;
    }

    public function setUser(\User $user): UserRegisterEmail
    {
        $this->user = $user;

        return $this;
    }

    public function getUser(): \User
    {
        return $this->user;
    }
}
