<?php
class ViewerComponent extends Object {
	
	/**
	 * Holds a reference to the controller that loaded this Component
	 */
		private $controller;
	
	/**
	 * Holds the info for the current viewer retrieved from session
	 * this is populated on every request when there is an active session
	 */
		private $user = null;
		
	/**
	 * this is the session key the viewers personal data is saved under
	 */	
		private $logKey = 'currentlystoneds';
		
	/**
	 * this is the key for the cookie that saves a viewers persistance
	 */
		private $userCookie = 'stvuser';
		
	/**
	 * place holder for an AccountModel this should only be accessed 
	 * through $this->_Account(); 
	 */	
		private $Account = null;
		
	/**
	 * helper component used by this component
	 * the session comp is used to restore the users data
	 */	
		public $components = array('Session', 'Cookie');

	
	/**
	 * initilization method called when class is created
	 * 
	 * @param Object $controller - the controller class that is using this component
	 */
		public function startup(&$controller) {

			$this->controller = $controller;
			$this->user = null;	
			if($this->Session->check( $this->logKey ) ) {
				$this->user = $this->Session->read( $this->logKey );
			}
		}
	
	/**
	 * private method used to reference an account model
	 * this stops the need to create a new account model everytime it is needed
	 */
		private function _Account() {
			
			if( !isset( $this->Account ) ) {
				$this->Account = new Account();
			}
			return $this->Account;		
		}	
		
	/**
	 * when a viewer is logged in he/she must be passed in here and the needed info is saved to session
	 * this is the same information that is loaded into the user property of the controller classes *see _loadUser
	 *
	 * @param array $viewer - the array of data for this viewer a combonation of the accounts, profiles, and themes tables 
	 * @param sting $pswd - the viewers unencrypted password to save to session
	 */	
		private function saveToSession( $viewer , $pswd) {
			
			$sessdata = array(
				'id' => $viewer['Account']['id'],
				'username' => $viewer['Account']['username'],
				'icon' => $viewer['Account']['icon'],
				'gender' => $viewer['Profile']['gender'],
				'type_id' => $viewer['Account']['type'],
				'rank' => $viewer['Role']['rank'],
				'account_type' => $viewer['Role']['name'],
				'theme' => $viewer['Theme']['theme'],
				'layout' => $viewer['Theme']['layout'],
				'component' => $viewer['Theme']['component'],
				'last_visit' => $viewer['Account']['last_visit'],
				'age' => determineAge($viewer['Profile']['dob']),
				'channel' => $viewer['Account']['channel_id'],
				'language' => $viewer['Account']['lang'],
				'emailaccess' => $pswd,
				'billable' => (!empty($viewer['Profile']['cckey']) ) ? 1 : 0
			);	
			
			$this->user = $sessdata; 
			$this->Session->write($this->logKey, $sessdata);
			$this->Session->setAccount( $viewer['Account']['id'] );
		}
		
	/**
	 * attempts to restore a viewers info from cookie data
	 * this will ONLY happen if the users has allowed the computer they are on to be remembered (ie a cookie saved)
	 *
	 * @return array view info if restore was successfull else boolean false
	 */
	 	public function restore() {
			
			if( $this->Cookie->check( $this->userCookie ) ) {
				$key = $this->Cookie->read($this->userCookie, true);
				
				if( $key ) {
					$this->Session->correctViewerSession( $key );
					$user = $this->Session->read( $this->logKey );
					if( isset( $user['emailaccess'] ) &&  $viewer = $this->_Account()->getViewer( $key ) ) {
						$this->login( $viewer, $user['emailaccess'] );
						return $viewer;
					}
				}
			}
			$this->clear();
			return false;
		}
		
	/**
	 * after a viewer has been authenticated this saves there data to session
	 *
	 * @param array $viewer - the user data that to save to session for this viewer
	 * @param string $pswd - the users unencrypted password that must also be saved to session for IMAP access
	 * @return array of viewer data if cookie is found and user is persistant else false;
	 */	
		public function login( $viewer, $pswd ) {
			
			if( $this->Cookie->check( $this->userCookie ) ) {
				$this->Cookie->write($this->userCookie,  $viewer[0]['Account']['id'], '+30 day');
			}
			$this->_Account()->updateVisit( $viewer[0]['Account']['id'] );
			$this->saveToSession( $viewer[0], $pswd );
		}
		
		public function reconfirm( $id ) {
			
			return $this->Session->correctViewerSession( $id );				
		}
		
	/**
 	 * logges the viewer out by deleting all data in session and any saved cookie data
	 */
	 	public function logout() {
			
			$this->clear();
			if( $this->Cookie->check($this->userCookie) ) {
				$this->Cookie->delete($this->userCookie);
			}
		}
		
				
		public function clear() {
		
			$this->Session->clearAccount( $this->user['id'] );
			$this->Session->delete($this->logKey);
			$this->user = null;
		}
	
	/**
	 * checks to see if the active account has stored CC info and would there for
	 * be able to be billed for things on the site
	 *
	 * @return Boolean - true if the account can be billed else false;
	 */
		public function isBillable() {
			
			return (isset( $this->user['billable'] ) && $this->user['billable'] == 1 ) ? true : false;
		}
		 
	/**
	 * get the active users id
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * #param mixed $default - a default value to return if the there is no viewer id
	 * @return int - the id of the user or null
	 */		
		public function getId( $default=null ) {
			
			//print($this->user['id']);
			return isset( $this->user['id'] ) ? $this->user['id'] : $default;
		}
		
	/**
	 * get the active users username
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return string - the username of the user or null
	 */		
		public function getName() {
		
			return isset( $this->user['username'] ) ? $this->user['username'] : null;
		}
	
	/**
	 * get the active users icon
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return string - the file name of the users icon or null
	 */		
		public function getIcon() {
				
			return isset( $this->user['icon'] ) ? $this->user['icon'] : null;
		}
	
	/**
	 * get the active users account type
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return string - the name of the type of account this user has or null
	 */		
		public function getTypeName() {
				
			return isset( $this->user['account_type'] ) ? $this->user['account_type'] : null;
		}	
		
	/**
	 * get the active users account type
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return string - the name of the type of account this user has or null
	 */		
		public function getTypeId() {
				
			return isset( $this->user['type_id'] ) ? $this->user['type_id'] : null;
		}		
		
	/**
	 * get the active users age
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return string - the age of the user or null
	 */		
		public function getAge() {
				
			return isset( $this->user['age'] ) ? $this->user['age'] : null;
		}
	
	/**
	 * get the active users gender
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return string - the gender of the user or null
	 */	
		public function getGender() {
				
			return isset( $this->user['gender'] ) ? $this->user['gender'] : null;
		}
	
	/**
	 * get date the date the active user last visited the site
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return string - the date the user last logged into the site
	 */	
		public function getLastVisit() {
				
			return isset( $this->user['last_visit'] ) ? $this->user['last_visit'] : null;
		}
		
	/**
	 * get all of the user data
	 * if the user does not have an account or is not logged in this will return null
	 *
	 * @return array - the user data
	 */	
		public function getData() {
			
			return $this->user;
		}
	
	/**
	 * get the users rank
	 * this is the rank of their "account_type" role
	 * this rank may not be their highest clearance level depending on other role assignments
	 * but this is the max rank they are allowed to assign
	 * defaults to 0 if the viewer is not logged in
	 *
	 * @return int - the users rank
	 */	
		public function getRank() {
		
			return isset( $this->user['rank'] ) ? $this->user['rank'] : 0;
		}
	
	/**
	 * get the language the users perfers
	 * defaults to english if nothing was set
	 *
	 * @return string - the language 
	 */	
		public function getLanguage() {
			
			return isset( $this->user['language'] ) ? $this->user['language'] : 'english';
		}
	
	/**
	 * get the current uses email address ( username + @stoned.com )
	 *
	 * @return string - the users email address with domain 
	 */	
		public function getEmail() { 
			
			return $this->user['username'].'@stoned.com';
		}
	
	/**
	 * get the current uses unencrypted password
	 * this is used only by the email controller to log into the IMAP email server.
	 * I would like to find a way around having to store this in session
	 *
	 * @return string - the users unencrypted password
	 */	
		public function getPassword() { 
		
			return $this->user['emailaccess'];
		}
	
	/**
	 * utility method to return the correct pronoun for the user
	 *
	 * @return string - his if user is a male else her
	 */
		public function getGenderPronoun() {
			
			return ($this->user['gender'] == 'male') ? 'his' : 'her';
		}
}
?>