<?php

/**
 * メールの送信を担う
 */
class MailLogic extends SOY2LogicBase{

	private $config;
	private $mail;

	/**
	 * メール送信
	 * @param string 送信先メールアドレス
	 * @param string 送信先名称
	 * @param string メール件名
	 * @param string メール本文
	 */
	public static function send($to, $label, $subject, $body){
		$this->prepare();
		$this->_send();
	}

	/**
	 * メール送信準備
	 */
	private function prepare(){

		//設定取得
		$this->loadConfig();

		if($this->config->getIsUsePopBeforeSMTP()){
			if($this->config->getReceiveServerType() != SOY2Mail_ServerConfig::RECEIVE_SERVER_TYPE_POP
			&& $this->config->getReceiveServerType() != SOY2Mail_ServerConfig::RECEIVE_SERVER_TYPE_IMAP
			){
				throw new Exception("Invalid receive server type.");
			}

			//before smtp
			$receive = $this->config->buildReceiveMail();
			$receive->open();
			$receive->close();
		}

		//送信先サーバー、FromとReply-Toもここで入る
		$this->mail = $this->config->buildSendMail();

	}

	/**
	 * メール設定取得
	 */
	private function loadConfig(){
		if(!$this->config){
			$logic = SOY2LogicContainer::get("logic.mail.MailConfigLogic");
			$this->config = $logic->get();
		}

		if(!$this->checkConfig()){
			throw new Exception("Invalid mail config.");
		}

	}

	/**
	 * 送信ロジック
	 */
	private function _send($to, $label, $subject, $body){

		//リセット
		$this->reset();

		//文字コード
		$encoding = $this->config->getEncoding();
		$this->mail->setEncoding($encoding);
		$this->mail->setSubjectEncoding($encoding);

		//件名、本文
		$this->mail->setSubject($subject);
		$this->mail->setText($body);

		//送信先
		$this->mail->addRecipient($to, $label);

		/*
		//管理者にコピーを送る設定の時
		if($this->config->isSendWithAdministrator() && $to != $this->config->getAdministratorMailAddress()){
			$this->mail->addBccRecipient($this->config->getAdministratorMailAddress(), $this->config->getAdministratorName());
		}
		*/

		$this->mail->send();

	}


	/**
	 * 件名、本文、受信者、BCC受信者、ヘッダー、添付ファイルをリセット
	 * SOY2MailはsetTextだけではencodedTextが上書きされない
	 */
	private function reset(){
		$this->mail->clearSubject();
		$this->mail->clearText();
		$this->mail->clearRecipients();
		$this->mail->clearBccRecipients();
		$this->mail->clearHeaders();
		$this->mail->clearAttachments();
	}
}
