<?php

namespace App\Service;

use Pimcore\Logger;
use Pimcore\Mail;
use Pimcore\Model\Asset;
use Pimcore\Model\Document;

class MailManager
{
	/**
	 * @var Document\Service
	 */
	protected $documentService;

	/**
	 * @param Document\Service
	 */
	public function __construct(Document\Service $documentService)
	{
		$this->documentService = $documentService;
	}

/**
	 * @param Document\Email|string  $pathOrTemplate
	 * @param string                 $language
	 * @param string                 $to
	 * @param string                 $from
	 * @param array                  $params
	 * @param Asset $attachment
	 * @param string                 $replyTo
	 *
	 * @return bool
	 */
	public function sendMail($pathOrTemplate, $language, $to = null, $from = null, $params = null, $attachment = null, $replyTo = null)
	{
		if ($pathOrTemplate instanceof Document\Email) {
			$document = $pathOrTemplate;
		} else {
			$document = Document\Email::getByPath($pathOrTemplate);
			if (!$document) {
				return false;
			}
			// try to load translated template
			if ($document->getProperty('language') != $language) {
				$translations = $this->documentService->getTranslations($document);
				if (isset($translations[$language])) {
					$translatedDocument = Document\Email::getById($translations[$language]);
					if ($translatedDocument) {
						$document = $translatedDocument;
					}
				}
			}
		}
		if (!$document instanceof Document\Email) {
			return false;
		}

		$mail = new Mail();

		$mail->setDocument($document);

		if ($to) {
			$mail->to($to);
		}
		if ($from) {
			$mail->from($from);
		}

		if ($replyTo) {
			$mail->addReplyTo($replyTo);
		}
		if ($params) {
			$mail->setParams($params);
		}

		if ($attachment instanceof Asset) {
			$mail->attach($attachment->getData(), $attachment->getFilename(), $attachment->getMimeType());
		}

		try {
			$mail->send();

			return true;
		} catch (\Exception $e) {
			Logger::error('MAIL - '.$e->getMessage()."\n".$e->getTraceAsString());

			return false;
		}
	}
}
