<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 *
 * @version 0.1
 * @package application.components
 */
class UserIdentity extends CUserIdentity {

    private $_id;
    private $_role;

    /**
     * Authenticates a user using the User data model.
     * @param boolean $is_reqested_from_client identify whether the client application (POS) or the web application has requested this method
     *
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {	
	//Getting Information for this username and check if this LDAP user have record at system
	$user = User::model()->active()->findByAttributes(array('username' => $this->username));
	if ($user === null) {
	    $this->errorCode = self::ERROR_USERNAME_INVALID;
	} else

	if ($user->getType() == "LDAP") {
	    //LDAP Authentication
	    $this->userLDAPAuthentication($user);
	} else {
	    //System Authentication
	    // Password maching
	    $this->userSystemAuthentication($user);
	}



	return!$this->errorCode;
    }

    /**
     * set user id and role and register login action in audit trail
     * @param User the current user
     */
    function setUserPropertyWithAuditTrail($user) {
	$this->_id = $user->id;
	$this->_role = $user->role;
	$this->errorCode = self::ERROR_NONE;
	//Add log for the log in operation
//	$log = new AuditTrail;
//	$log->user_id = $user->id;
//	$log->stamp = date("Y-m-d H:i:s");
//	$log->new_value = date("Y-m-d H:i:s");
//	$log->field = "date";
//	$log->model_id = "";
//	$log->action = 'Log In';
//	$log->model = 'Log In';
//	$log->save(false);
    }

    /**
     * System Authentication
     * @param User the current user
     */
    function userSystemAuthentication($user) {
	//System Authentication
	// Password maching
	if ($user->password !== $user->encrypt($this->password)) {
	    $this->errorCode = self::ERROR_PASSWORD_INVALID;
	} else {
	    UserIdentity::setUserPropertyWithAuditTrail($user);
	}
    }

    /**
     * LDAP Authentication
     * @param User the current user
     */
    function userLDAPAuthentication($user) {
	//Test Binding by email and password to check if there is LDAP User or not
	$binding_result = LDAP::bind($user->email, $this->password);
	if ($binding_result === "both_servers_failed") {
	    return "both_servers_failed";
	} else {
	    if ($binding_result) {
		UserIdentity::setUserPropertyWithAuditTrail($user);
	    } else {
		UserIdentity::userSystemAuthentication($user);
	    }
	}
    }

    /**
     * Get user id
     * @return String The id of the user
     */
    public function getId() {
	return $this->_id;
    }

    /**
     * Get user role
     * @return String The role of the user
     */
    public function getRole() {
	return $this->_role;
    }

}