<?php

class CheckRegisterCodeAction extends SOY2Action{
    
    protected function execute(SOY2ActionRequest &$request,SOY2ActionForm &$form,SOY2ActionResponse &$response){
    	
    	$email = @$_REQUEST["email"];
    	$registerCode = @$_REQUEST["register_code"];

		$mailLogic = SOY2Logic::createInstance("logic.asp.ASPMailLogic");
		
		try{
    		
    		if(!$email || !$registerCode){
    			throw new Exception("email and register_code are required.");
    		}
    	
    		
    		//コードからUserIDを取得
	    	$queueDao = SOY2DAOFactory::create("asp.CertificationQueueDAO");
	    	$result = $queueDao->getByRegisterCode($registerCode);
	    	
	    	//なかったら失敗
	    	if(count($result)<1){
	    		throw new Exception("Can not find queue by ".$registerCode);
	    	}
    		
    		$userDao = SOY2DAOFactory::create("asp.ASPUserDAO");
	    	$user = null;
	    	$correctQueue = null;
	    	
	    	foreach($result as $queue){
	    		$user = $userDao->getById($queue->getUserId());
	    		
	    		//メールアドレスが一致していなかったらアウト
	    		if($user->getEmail() != $email){
	    			return SOY2Action::FAILED;
	    		}
	    		
	    		$correctQueue = clone($queue);
	    		break;
	    	}
	    	if(is_null($user)){
	    		throw new Exception();
	    	}
    	
	    	//サイトの作成を行う。
	    	SOY2::import("domain.cms.SiteConfig");
	    	$siteId = $correctQueue->getSiteId();
	    	$logic = SOY2Logic::createInstance("logic.admin.Site.SiteLogic");
			$result = $logic->createSite($siteId,"新しいサイト:".$siteId,SiteConfig::CHARSET_UTF_8);
			
			if($result === false){
				throw new Exception();
			}		
					
		
			try{
				//サイトとの関連を作成する
				$userSiteDao = SOY2DAOFactory::create("asp.UserSiteDAO");
				$userSiteDao->begin();
				$userSite = new UserSite();
				$userSite->setSiteId($result);
				$userSite->setUserId($user->getId());
		    	$userSiteDao->insert($userSite);
		    	
		    	//Queueの削除を行う
		    	$queueDao->deleteByUserId($correctQueue->getUserId());
		    	
		    	$userSiteDao->commit();
		    	
		    	//ファイルマネージャを作成
		    	SOY2::import("util.CMSFileManager");
		    	CMSFileManager::Root(SOYCMS_TARGET_DIRECTORY);
		    	CMSFileManager::insertAll(SOYCMS_TARGET_DIRECTORY . $siteId ."/");
		    	
		    	
			}catch(Exeption $e){
				$userSiteDao->rollback();
				throw $e;
			}
			
			//メールを送信する
			$this->sendRegistreMail($user,$siteId);
			
    	}catch(Exception $e){
    		return SOY2Action::FAILED;	
    	}
		
		return SOY2Action::SUCCESS;
    }
    
    function sendRegistreMail($user,$siteId){
    	$mailLogic = SOY2Logic::createInstance("logic.asp.ASPMailLogic");
		$mailLogic->sendRegisterMail($user,UserInfoUtil::getSiteURLBySiteId($siteId));
    }
    
}
?>