<?php

require_once VENDORS_PATH . 'SwiftMailer/lib/swift_required.php';

/**
 * Email
 *
 * @author Arkadiusz Rychlik <a.rychlik at eppe.com.pl>
 */
class Rtn_Email {

	private $config;
	private $view;

	public function __construct() {
		$this->config = new Zend_Config_Ini(APPLICATION_PATH.'configs/mail.ini', APPLICATION_ENV);
		
		$this->view = new Zend_View([
			'scriptPath' => Rtn_Finder_File_View::find('', 'email.phtml')
		]);
	}
	
	public function getConfig() {
		return $this->config;
	}

    public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true){
		return $this->config->baseUrl . $this->view->url($urlOptions,$name,$reset,$encode);
	}
	
	/**
	 * Wysyła wiadomość e-mail wg. templatki
	 * @param string $subject
	 * @param string $message
	 * @param string $toEmail
	 * @param string $toName
	 * @throws Rtn_Exception_Module
	 */
	public function send($subject, $message, $toEmail, $toName=null){
		$fromEmail = $this->config->from->email;
		$fromName = $this->config->from->name;
		$assetsUrl = $this->config->assetsUrl;
		$baseUrl = $this->config->baseUrl;
		
		if(!$fromEmail || !$fromName || !$assetsUrl || !$baseUrl){
			throw new Rtn_Exception_Module(__('mail.ini missing or corrupted'));
		}
		
		$html = $this->view->assign([
			'assetsUrl' => $this->config->assetsUrl,
			'message' => $message
		])->render('email.phtml');

		$msg = Swift_Message::newInstance();

		$msg->setSubject($subject);
		$msg->setFrom($fromEmail,$fromName);
		$msg->setTo($toEmail,$toName);

		$msg->setBody($html, 'text/html', 'UTF-8');

		return Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($msg);
	}
	
}
