<?php

namespace Vn\Web;

require_once 'libphp-phpmailer/autoload.php';

use Vn\Lib\UserException;

class Mailer {
	private $conf;

	function __construct($db) {
		$this->conf = $db->getObject(
			'SELECT host, port, secure, sender, senderName, user, password
				FROM hedera.mailConfig'
		);
	}

	function createObject($mailTo, $body, $subject) {
		$conf = $this->conf;

		$mail = new \PHPMailer();
		$mail->isSMTP();
		$mail->Host = $conf->host;

		if (!empty($conf->user)) {
			$mail->SMTPAuth = TRUE;
			$mail->Username = $conf->user;
			$mail->Password = base64_decode($conf->password);
		} else
			$mail->SMTPAuth = FALSE;

		if ($conf->secure) {
			$mail->SMTPSecure = 'ssl';
			$mail->Port = 465;
		}

		$mail->setFrom($conf->sender, $conf->senderName);
		$mail->IsHTML(TRUE);
		$mail->Subject = $subject;
		$mail->Body = $body;
		$mail->CharSet = 'UTF-8';

		$mailList = explode(',', $mailTo);

		foreach ($mailList as $to)
			$mail->AddAddress($to);

		return $mail;
	}

	function send($mailTo, $body, $subject) {
		$mail = $this->createObject($mailTo, $body, $subject);

		if (!$mail->Send())
			throw new UserException('Send error: '.$mail->ErrorInfo);
	}
}