<?php
class classEmail
{
	private $sendEmailByDefault=NULL;
	private $sendSMSByDefault=NULL;
			
	private $users = NULL; //array containing data of single or multiple users , this is in case a generic msg is being sent when no transaction has happened or it might have happened but the recipient is a third party, etc
	
	private $typeOfMsgToSend=NULL; // has been Changed To typeOfMsgToSend
	private $IPAddress=NULL;
	private $timestamp=NULL;
	private $tokenNames=NULL;
	private $tokenValues=NULL;
	private $untokenizedMsgDataArrayFromDB=NULL; 
	
	private $msgRecipientEmailID=NULL; // has been changed to private msgRecipientID & private !
	private $msgRecipientFirstName=NULL; // has been changed to private msgRecipientFirstName & private !
	private $msgRecipientLastName=NULL; // has been changed to private msgRecipientLastName & private !
	private $msgRecipientPhoneNumber=NULL; // has been changed to private msgRecipientLastName & private !		
	
	public function __construct($sendEmailByDefault=1,$sendSMSByDefault=1) 
	{
		$this->sendEmailByDefault=$sendEmailByDefault;
		$this->sendSMSByDefault=$sendSMSByDefault;
	}
	
	public function setDynamicToken($name,$value) 
	{
		$this->$name = $value;
	}
	
	public function getDynamicToken($name) 
	{
		if(isset($this->$name))
		{
			return $this->$name;
		}
	}


	#################################### set functions #####################################
	
	public function setMsgRecipientLastName($msgRecipientLastName) 
	{
		if($msgRecipientLastName!="")
		{
			$this->msgRecipientLastName=$msgRecipientLastName;
		}
		else
		{
			//throw new MyException(111100);
		}
	}
	
	public function setMsgRecipientFirstName($msgRecipientFirstName) 
	{
		if($msgRecipientFirstName!="")
		{
			$this->msgRecipientFirstName=$msgRecipientFirstName;
		}
		else
		{
			throw new MyException(111101);
		}
	}
		
	public function setMsgRecipientEmailID($msgRecipientEmailID) 
	{
		if($msgRecipientEmailID!="")
		{
			$this->msgRecipientEmailID=$msgRecipientEmailID;
		}
		else
		{
			throw new MyException(111102);
		}
	}
		
	public function setMsgRecipientPhoneNumber($msgRecipientPhoneNumber) 
	{
		if($msgRecipientPhoneNumber!="")
		{
			$this->msgRecipientPhoneNumber=$msgRecipientPhoneNumber;
		}
		else
		{
			throw new MyException(111103);
		}
	}
	
	
	# this is in case a generic msg is being sent when no transaction has happened or it might have happened but the recipient is a third party, etc , it will return array containing data of single or multiple users 
	public function setUsers($user=NULL) 
	{ 
		if(!is_null($user))
		{
			$a = new classUser;
			$a->setUserEmail($user); 		
			$this->users[]=array('EmailID' => $a->getEmail(),'FirstName' => $a->getFirstName(),'LastName' => $a->getLastName(),'City' => $a->getCity(),'Country' => $a->getCountry(), 'PhoneNumber' => $a->getPhoneNumber(),//'Province' => $a->getProvince()
			);
		}
	
	}
	public function setUsersUnverified($user=NULL) 
	{ 
		if(!is_null($user))
		{
			$a = new classUser;
			$a->setUserEmailUnverified($user); 		
			$this->users[]=array('EmailID' => $a->getEmail(),'FirstName' => $a->getFirstName(),'LastName' => $a->getLastName(),'City' => $a->getCity(),'Country' => $a->getCountry(), 'PhoneNumber' => $a->getPhoneNumber(),//'Province' => $a->getProvince()
			);
		}
	
	}
	
	public function setUsersSubscribedForNewsLetters($user=NULL) 
	{ 
		if(!is_null($user))
		{
			$a = new classSubscribedUserForNewsLetters;
			
			$a->setSubscribedUserEmail($user); 		
			
			$this->users[]=array('EmailID' => $a->getEmail(),'FirstName' => $a->getFirstName(),'LastName' => $a->getLastName(),'PhoneNumber' => $a->getPhone());
		}
	
	}
	
	function getEmailIDByEmailIdentifier($identifier)
	{
		$query = "SELECT dbMsgID FROM  email_settings WHERE dbMsgIdentify = '$identifier'";
		$queryOb= new classQueryGlobal;
		$emailData = $queryOb->check_fetch_query($query,'select',$server="",$debug_mode="off");
		
		if(isset($emailData[0]['dbMsgID']))
		{
			return $emailData[0]['dbMsgID'];
		}
	}
		
	private function prepareDataForTransmission() 
	{
		$this->getRawMsgDataFromTheDB();
		$this->createTokens();
		$this->tokenizeMsgAndDetails();			
	}

	//////////////////////////TOKENS AND MSG DATA////////////////////////////////////
	
	private function getRawMsgDataFromTheDB() //mainly tokens and their values fetched from the email settings table INCLUDES THE RAW MSG BODY 
	{
		$result=mysql_query("select * from email_settings where dbMsgIdentify='" . $this->typeOfMsgToSend . "'");
	
		$row = mysql_fetch_assoc($result);
						
		foreach($row as $key=>$value)
		{
	
			$this->untokenizedMsgDataArrayFromDB[$key]=$value;
		}
	}			

	////////////////Msg Data from the table///////////////////


	private function createTokens() 
	{
		foreach($_SERVER as $sKey=>$sValue)
		{
			if(!is_null($sValue))
			{
				$this->tokenNames[]='{'.$sKey.'}';
				$this->tokenValues[]=$sValue;
			}
		}
		
		foreach($this as $key=>$value)
		{
			if(!is_null($value) AND $key!='users')
			{
				$this->tokenNames[]='{'.$key.'}';
				$this->tokenValues[]=$value;
			}
			
			if($key=='users')
			{
				$howManyUsersWereFilled=count($this->users);
				for($i=0;$i<$howManyUsersWereFilled;$i++)
				{
					
					foreach($this->users[$i] as $userKey=>$userValue)
					{
						if(!is_null($userValue))
						{
							$this->tokenNames[]='{user'.$i.$userKey.'}';
							$this->tokenValues[]=$userValue;
						}
					}
				}
			}
		}
	}
	

	private function replaceTokensWithValues($whatThisFunctionTokenizesShouldBePassedAsAnArgumentHere)
	{
		$thisVariableContainsTokens=$whatThisFunctionTokenizesShouldBePassedAsAnArgumentHere;
		$thisVariablesTokensHaveBeenReplacedWithValues=@str_replace($this->tokenNames,$this->tokenValues,$thisVariableContainsTokens);
		
		return $thisVariablesTokensHaveBeenReplacedWithValues;
	
	}


	private function tokenizeMsgAndDetails()
	{	
		foreach($this->untokenizedMsgDataArrayFromDB as $key=>$value)
		{
			$this->$key=$this->replaceTokensWithValues($value);												
		}
	}

	
	//////////////////////////TOKENS AND MSG DATA////////////////////////////////////
	
	public function sendEmail()
	{
		$mail = new PHPMailer(0); // defaults to using php "mail()"
		
		try 
		{
			$mail->SetFrom(@$this->dbEmailFrom,@$this->dbEmailFromName);
			$mail->AddAddress($this->msgRecipientEmailID,$this->msgRecipientFirstName ." ". $this->msgRecipientLastName);
			$mail->Subject=@$this->dbEmailSubject;
			$mail->MsgHTML(@$this->dbEmailBodyHTML);
			$mail->Send();
		}
		catch(Exception $a)
		{
			throw new MyException("There was an error in Mail Send.","You transaction has been made. But there was an error in sending mail.");
		}
	}

	public function sendSMS()
	{			
		if($this->msgRecipientPhoneNumber!="")
		{
			$query = "INSERT INTO ezine_sms(smsTo,smsMsg,smsType,smsPriority) VALUES('" .@$this->msgRecipientPhoneNumber."','".@$this->dbSMSBody."','".@$this->dbSMSType."','".@$this->dbSMSPriority."')";
			mysql_query($query);
		}
	}

	public	function typeOfMsgToSend($typeOfMsgToSend) # Should Be Changed To typeOfMsgToSend
	{
		switch($typeOfMsgToSend):
		
		case 'emailVerificationSPP':
		break;				
		
		default:
			if($this->msgRecipientEmailID == NULL AND $this->msgRecipientFirstName == NULL AND  $this->msgRecipientFirstName == NULL)
			{
				//////// users[0] will contain the recipient unless its empty, if its null then the developer intends to fill the recipient manually?,but the users array can contain multiple user object 
				$this->typeOfMsgToSend=$typeOfMsgToSend;								
				if (@$this->users[0]['EmailID']!="")
				{
					$this->msgRecipientEmailID=$this->users[0]['EmailID'];
					$this->msgRecipientFirstName=$this->users[0]['FirstName'];
					$this->msgRecipientLastName=$this->users[0]['LastName'];
					//$this->msgRecipientPhoneNumber=$this->users[0]['PhoneNumber'];														
				}
					
							
			}
			else
			{ 
				//throw new MyException("Type of Email to Be Sent was not declared or was invalid.","Internal error"); // has the transaction happened ? then why wud there be an internal error, do we want to confuse the user by telling him an internal error when the transaction has already happened, iz scenario mei the user should see no notices, email nahi gai so what, magar admin should be notified bcoz it wud mean a failure in our coding						
			}
		break;
		endswitch;
		
		$this->typeOfMsgToSend=$typeOfMsgToSend;			
		$this->prepareDataForTransmission();
	
		if($this->sendEmailByDefault==1)
		{
			$this->sendEmail();
		}
		
		if($this->sendSMSByDefault==1)
		{
			$this->sendSMS();
		}			
	
	}


	

}		
?>