<?php

SOY2::import("action.asp.NewAccountForm");
class SendRegistrationCodeAction extends SOY2Action{

	protected function execute(SOY2ActionRequest &$request,SOY2ActionForm &$form,SOY2ActionResponse &$response){
		
		$account = $this->getUserSession()->getAttribute("NewAccount");
		
		if(empty($_POST) || !$account || $account->hasError()){
			$this->getFlashSession()->setAttribute("failedSendRegistrationCode",true);
			return SOY2Action::FAILED;
		}
		
		try{
			//管理者情報の作成
			$dao = SOY2DAOFactory::create("asp.ASPUserDAO");
			$user = new ASPUser();
			SOY2::cast($user,$account);
			$user->setNickName($user->getLastName()." ".$user->getFirstName());
			
			//パスワードの暗号化を実行
			$user->setPassword(crypt($user->getPassword(),$user->getEmail()));
			
			
			/*　トランザクション開始 */
			$dao->begin();
			$id = $dao->insert($user);
			$user->setId($id);
			
			$queueDao = SOY2DAOFactory::create("asp.CertificationQueueDAO");
			$queue = new CertificationQueue();
			$queue->setUserId($user->getId());
			$queue->setSiteId($account->getSiteId());
			$queue->setTimeLimit(time() + 24 * 60 * 60);
			
			//登録コードの発行
			$crypt = crypt($user->getEmail());
			$queue->setRegisterCode(base64_encode(substr($crypt,strlen($crypt)-15)));
			
			$queueDao->insert($queue);
			
			//メールの送信
			$this->sendEmail($user,$queue);
						
			$dao->commit();
			/*　トランザクション終了 */
			
			//セッションに入っているデータの消去
			$this->getUserSession()->setAttribute("NewAccount",null);
			
			//こっそり登録コードをデータに投入
			//if(defined("SOYCMS_VERSION") && SOYCMS_VERSION == "developing") $this->getUserSession()->setAttribute("RegisterCode",$queue->getRegisterCode());
			
			
		}catch(Exception $e){
			$dao->rollback();
			$this->getFlashSession()->setAttribute("failedSendRegistrationCode",true);
			
			return SOY2Action::FAILED;
		}		
		
		return SOY2Action::SUCCESS;
    }
    
    /**
     * 登録コードの入ったメールを送信
     */
    function sendEmail($user,$queue){
    	$mailLogic = SOY2Logic::createInstance("logic.asp.ASPMailLogic");
		$mailLogic->sendActivationMail($user,$queue);
    }
}
?>