<?php

require_once("class.phpmailer.php");
		
	
	/*	
		$user = array(
        'email'=>'cyrpro1974@gmail.com',
        'name'=>'YONG CHO'
	    );
	 
	    $data = array(
	        'detail'=>'Your awesome detail here',
	        'name'  => $user['name']
	    );
	 
	 
	    Mail::send('emails.welcome', $data, function($message) use ($user)
	    {
	        $message->from('cyrpro1974@gmail.com', 'YONG RYUN CHO');
	        $message->to($user['email'], $user['name'])->subject('Welcome!');
	    });
	 
	    return Response::json(array('success' => true));
	    */


class EmailController extends BaseController {

	public function sendResetEmail($email, $username, $password) {
		
		/*
		return $this->sendEmail($email, "This is for the temporary password", 
			"Your URCedit account has been reset and you can now log in and begin to build your system.  Here is your temporary password.  \n\n Username : ".
			$username."  \n\n Password : ".$password."\n\n Thank you!\n URCedit Team");
		*/

		return EmailController::sendEmail($email, "This is for the temporary password",
			'<p>Your Online Editor&nbsp;account has been reset and you can&nbsp;now log in and begin to build your system.<br />'.
			'Here is your temporary password.</p><p><o:p></o:p></p><p>username :&nbsp;'.$username.
			'<o:p></o:p></p><p>Password :&nbsp;'.$password.
			'<o:p></o:p></p><p>&nbsp;</p><p>Thank you!</p><p><span style="line-height: 1.6;">URC</span></p><p><o:p></o:p></p>');
	
	}

	public function sendURCEmail($email, $password) {

		//return $this->sendEmail($email, "This is for registering an account", 
		//	"Welcome! \n\n Your URCedit account has been setup and you can now log in and begin to build your system.  Here is your temporary password.  \n\n Password : ".
		//		$password."\n\n Thank you!\n URCedit Team");

		return EmailController::sendEmail($email, "This is for the temporary password",
			'<h2>Welcome!<o:p></o:p></h2>'.
			'<p>Your Online Editor&nbsp;account has been setup and you can&nbsp;now log in and begin to build your system.<br />'.
			'Here is your temporary password.</p><p><o:p></o:p></p><p>Password :&nbsp;'.$password.
			'<o:p></o:p></p><p>&nbsp;</p><p>Thank you!</p><p><span style="line-height: 1.6;">URC</span></p><p><o:p></o:p></p>');
	}

	public static function sendEmail($email, $subject, $body) {

		$mail = new PHPMailer();

		$mail->IsSMTP();
		$mail->Host = Config::get('editorenv.urcEMailServerAddr');
		$mail->Port = Config::get('editorenv.urcEMailServerPort');
		//$mail->SMTPDebug = 2;

		$mail->SMTPAuth = true;
		$mail->Username = Config::get('editorenv.urcEMailServerUser');
		$mail->Password = Config::get('editorenv.urcEMailServerPass');
		
		$mail->SetFrom(Config::get('editorenv.urcEMailSender'), 'Administrator');
		//$mail->AddReplyTo("name@yourdomain.com","First Last");
		
		$mail->AddAddress($email);

		$mail->Subject = $subject;

		//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
		$mail->MsgHTML($body);

		//$mail->Body = $body;
		//$mail->WordWrap = 50;

		if(!$mail->Send())
		{
			//ErrorDebug::write('Mail Error : '.$mail->ErrorInfo.$mail->Username);
			return false;
		}
		else
		{
			return true;
		}

		//return false;
	}

	public function doClass($funcType) {
	
		if($funcType == 'forget_password') {

			$email = Input::get('email');

			$userChk = DB::table('user')->join('user_detail', function($join) use ($email)
			{				
				$join->on('user.id', '=', 'user_detail.user_id')
					->where('user_detail.user_email', '=', $email)->where('user.editor', '=', Config::get('editorenv.editor_type'));
			})->first();

			if(!$userChk) {
				
				$rmsDealer = new RMSDealer();
				if($rmsDealer->isExistingUser($email)) {
					return Response::json(array('result' => false, 'error' => 'DEALER_ACCOUNT'));
				}

				return Response::json(array('result' => false, 'error' => 'unknown user'));
			}

			//new Password
			$password = StringGenerator::doGen(10, 'az09', 1);

			$userObj = new User;
			$userObj->where('id', '=', $userChk->id)->
				update(array('password' => Crypt::encrypt($password)));
						
			//Send Email
			if(!$this->sendResetEmail($email, $userChk->username, $password)) {
				return Response::json(array('result' => false, 'error' => 'fail to send a email'));
			}
			
			return Response::json(array('result' => true));
		}

		if($funcType == 'register_email') {

			$rules = array(
				'modelType' => 'Required',
				'key' => 'Required|min:16',
				'email' => 'Required|Between:3,255|Email');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}
			
			$modelType = Input::get('modelType');//HCM-C1';
			$keyValue = Input::get('key');
			$email = Input::get('email');

			$progKey = BStationManager::genKeyFromUserData($modelType, $keyValue);
			if($progKey === false) {
				return Response::json(array('result' => false, 'error' => 'invalid type key'));
			}

			//check registered Bstation
			$mac_addr = '';
			$modelTypeId = '';
			$randId = '';
			if(BStationManager::getDataFromKey($progKey, $mac_addr, $modelTypeId, $randId) !== true) {
				return Response::json(array('result' => false, 'error' => 'invalid type key'));
			}

			//Key Check			
			if(Config::get('editorenv.debugSkipBStationChk') != true) {
				$mgr = new BStationManager(URCValues::WAIT_SEC); 
				if($mgr->customCheckKey($progKey) !== true) {
					return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
				}
			}

			$chkBStation = DB::table('a_bstations')->where('mac', '=', $mac_addr)->first();
			if($chkBStation) {
				$urcSystem = new URCSystemData(-1);//JWT->Auth::id());			
				if(!$urcSystem->deleteBStationFromOther($chkBStation)) {
					return Response::json(array('result' => false, 'error' => 'The basestation is already being used'));
				}
			}

			//Save to DB
			//DB::insert('insert into reg_email (email, password) values (?, ?)', array(Input::get('email'), 'ggege'));
			$password = StringGenerator::doGen(10, 'AZ09', 1);

			//DB Update
			$regemail = new EmailReg;
			$regemail->saveRegEmail($email, $password, $progKey);
			
			//Send Email
			if(Config::get('editorenv.debugSkipEmail') != true) {
				if(!$this->sendURCEmail($email, $password)) {
					return Response::json(array('result' => false, 'error' => 'fail to send a email'));
				}
			}
			
			return Response::json(array('result' => true));
		}
		
		return Response::json(array('result' => false, 'error' => 'unknown command'));
	}

	

}