<?php
	require_once( $GLOBALS["site_root"] . "/includes/models/Mail.inc.php" );

	class TemplateMailModel extends MailModel {
		protected $iTemplateId = 0;

		public function __construct( $param = null , $lang = "hu" ) {
			parent::__construct( $lang );
			if (!isset( $param )) return;
			// default parameter
			if (is_numeric( $param )) {
				$this->setTemplateFromId( $param );
			} else if (is_array( $param )) {
				foreach ($param as $template) {
					if ($this->setTemplateFromName( $template )) break;
				}
			} else if (is_string( $param )) {
				$this->setTemplateFromName( $param );
			}
		}

		public function setTemplateFromId( $id ) {
			$this->iTemplateId = $id;
		}

		public function getTemplateIdFromName( $name ) {
			$site_language_id = $GLOBALS["languages"][$this->sLanguage];
			$query = sprintf( "select mail_template_id from mail_templates where template_name='%s' and site_language_id=%d",
				FNTH_db_addslashes( $name ) , $site_language_id );
			return FNTH_db_get_field( $query , "mail_template_id" );
		}

		public function getTemplateNameFromId( $mail_template_id ) {
			$query=sprintf("select template_name from mail_templates where mail_template_id=%d",$mail_template_id);
			return FNTH_db_get_field( $query , "template_name" );
		}

		public function setTemplateFromName( $name ) {
			$mail_template_id = $this->getTemplateIdFromName( $name );
			if (!$mail_template_id) return false;
			$this->iTemplateId = $mail_template_id;
			return true;
		}

		public function sendMail( $email = "lorenzo@fotonsoft.hu" ) {
			$query = sprintf( "select * from mail_templates where mail_template_id=%d" , $this->iTemplateId );
			$row = FNTH_db_get_row( $query );
			if (!$row) {
				trigger_error( sprintf( "No such template: %d" , $this->iTemplateId ) );
				return false;
			}
			$this->setHtml( true );
			$this->setPlain( true );
			$this->setSubject( $row["template_subject"] );
			$this->setBody( $row["template_content"] );
			return parent::sendMail( $email );
		}
	}
?>
