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

/**
 * This class provides email template functions
 *
 * @package    OSB
 * @subpackage Email_Template
 * @category   Helpers
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Email_Template {
	// We'll store the template here
	private $template;
	private $etto;
	private $email_data = array();
	// @todo Default lang should be the site setup
	private $default_lang = 1;
	private $components = array('subject','message_text','message_html');

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

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

		if (is_null($language_id))
			$language_id = $this->default_lang;

		$this->etto = $this->template->email_template_translate->where('language_id','=',$language_id)->find();
		if (! $this->etto->loaded())
			$this->etto = $this->template->email_template_translate->where('language_id','=',$this->default_lang)->find();

		// @todo Change this to log/email the admin
		return;
		#throw new Kohana_Exception('No template (:template) found for user language (:language_id) or default language (:default_lang)',
		#	array(':template'=>$this->template->name,':language_id'=>$language_id,':default_lang'=>$this->default_lang));
	}

	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->email_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->email_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->email_data[$key]))
					return array();

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

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

					foreach ($this->email_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->email_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 variables() {
		$return = array();

		foreach ($this->components as $v)
			foreach ($this->etto->variables($v) as $x => $y)
				if (! in_array($y,$return))
					array_push($return,$y);

		return $return;
	}

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

		foreach ($this->components as $component) {
			if ($this->etto->loaded()) {
				$s = $this->etto->resolve($this->email_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::name());
				$sm->setBody(print_r($this->email_data['variables'],TRUE),'text/plain');
			}
		}

		if (isset($this->email_data['bcc']))
			$sm->setBcc($this->bcc);

		if ($admin OR ($admin = Config::testmail($this->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);

		if ($result) {
			// Store our email log.
			$elo = ORM::factory('email_log');

			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->email_data['variables'];
				$elo->save();
			}
		}

		return $result;
	}

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

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

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