<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class provides email template functions
 *
 * @package    Email
 * @category   Helpers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Email_Template {
	// Our components that need resolving
	private $_components = array('subject','message_text','message_html');
	// Our Email Data
	private $_data = array();
	// Our Email Template Object
	private $_etto;

	public function __construct($template,$language_id=NULL) {
		$eto = ORM::factory('Email_Template',array('name'=>$template));

		if (! $eto->loaded())
			throw new Kohana_Exception('Email template :template not defined in DB',array(':template'=>$template));

		if (is_null($language_id))
			$language_id = Config::language();

		$this->_etto = $eto->translate
			->where_open()
			->where('language_id','=',$language_id)
			->or_where('language_id','=',Config::language())
			->where_close()
			->find();

		if (! $this->_etto->loaded())
			throw new Kohana_Exception('No template (:template) found for user language (:language_id) or default language (:default_lang)',
				array(':template'=>$eto->name,':language_id'=>$language_id,':default_lang'=>Config::language()));
	}

	public function __set($key,$value) {
		switch ($key) {
			case 'bcc':
			case 'to':
				if (! is_array($value) OR ! array_intersect(array('email','account'),array_keys($value)))
					throw new Kohana_Exception('Values for to should be an array of either "mail" or "account", however :value was given',array(':value'=>serialize($value)));

				$this->_data[$key] = $value;
				break;

			case 'module':
				$this->_data[$key] = $value;
				break;

			case 'module_data':
				$this->_data[$key] = $value;
				break;

			case 'variables':
				// Our variables should be an array
				if (! is_array($value))
					throw new Kohana_Exception('Values for variables should be an array, however :value was given',array(':value'=>$value));

				$this->_data[$key] = $value;
				break;

			default:
				throw new Kohana_Exception('Unknown variable :key (:value)',array(':key'=>$key,':value'=>is_string($value) ? $value : serialize($value)));
		}
	}

	public function __get($key) {
		switch ($key) {
			case 'bcc':
			case 'to':
				if (empty($this->_data[$key]))
					return array();

				elseif (isset($this->_data[$key]['email']))
					return $this->_data[$key]['email'];

				elseif (isset($this->_data[$key]['account'])) {
					$list = array();

					foreach ($this->_data[$key]['account'] as $id) {
						$ao = ORM::factory('Account',$id);
						if ($ao->loaded())
							$list[$ao->email] = $ao->name();
					}

					return $list;
				}

				break;

			case 'variables':
				return $this->_data[$key];

			default:
				throw new Kohana_Exception('Unknown variable :key (:value)',array(':key'=>$key,':value'=>is_string($value) ? $value : serialize($value)));
		}
	}

	public static function instance($template) {
		return new Email_Template($template);
	}

	public function send(array $admin=array()) {
		$e = Email::connect();
		$sm = Swift_Message::newInstance()
			->setFrom(Kohana::$config->load('config')->email_from);

		foreach ($this->_components as $component) {
			if ($this->_etto->loaded()) {
				$s = $this->_etto->complete($this->_data['variables'],$component);

				switch ($component) {
					case 'message_html':
						$sm->setBody($s,'text/html');
						break;
					case 'message_text':
						$sm->setBody($s,'text/plain');
						break;
					case 'subject':
						$sm->setSubject($s);
						break;

					default:
						throw new Kohana_Exception('Component :component has not been configured in :method',array(':component'=>$component,':method'=>__METHOD__));
				}
			} else {
				$sm->setSubject(_('Email from').' '.Company::instance()->name());
				$sm->setBody(print_r($this->_data['variables'],TRUE),'text/plain');
			}
		}

		if ($x=Arr::merge($this->bcc,Kohana::$config->load('debug.email_bcc_admin')))
			$sm->setBcc($x);

		if ($admin OR ($admin = Config::testmail($this->_etto->template->name))) {
			$sm->setTo($admin);
			$sa = array(1);

		} else {
			$sm->setTo($this->to);
			$sa = $this->to_accounts();
		}

		// @todo - Setup queue mode
		$result = $e->send($sm);
		// Store our email log.
		$elo = ORM::factory('Email_Log');

		if ($result)
			foreach ($sa as $id) {
				$elo->clear();

				$elo->account_id = $id;
				$elo->email = implode(',',array_keys($this->to));
				$elo->email_template_translate_id = $this->_etto->id;
				$elo->data = $this->_data['variables'];

				if (isset($this->_data['module']) AND isset($this->_data['module_data'])) {
					$elo->module_id = $this->_data['module'];
					$elo->module_data = $this->_data['module_data'];
				}
			
				$elo->save();
			}

		return ($result AND $elo->saved()) ? $elo->id : $result;
	}

	private function to_accounts() {
		// @todo Set the default account in a configuration file.
		$default = array(1);

		if (! isset($this->_data['to']) OR ! is_array($this->_data['to']) OR ! array_intersect(array('email','account'),array_keys($this->_data['to'])))
			return $default;

		return isset($this->_data['to']['account']) ? $this->_data['to']['account'] : $default;
	}

	/**
	 * Work out all the required variables for this message
	 */
	public function variables() {
		$result = array();

		foreach ($this->_components as $v)
			foreach ($this->_etto->variables($v) as $x => $y)
				if (! in_array($y,$result))
					array_push($result,$y);

		return $result;
	}
}
?>
