<?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.
 */
class UserIdentity extends CUserIdentity {

    private $_id;

    /**
     * Authenticates a user.
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {
        $username = strtolower($this->username);
        $salt = '$2a$10$1qAz2wSx3eDc4rFv5tGb5t';
        $password = crypt($this->password, $salt);
        $user = User::model()->find('LOWER(username)=? AND isActive=? ', array($username, 'Y'));
        session_start();
        if ($user === null) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else if (($user->password !== $password) && ($_SESSION["username"] != $username)) {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        } else {

            $this->_id = $user->id;
            $this->setState('fullname', $user->fullname);
            $this->setState('have_access', $user->level > 0 ? false : true);
            $this->setState('user_id', $user->id);
            $this->setState('is_admin', $user->level == 0 ? true : false);
            $mas_com = new MasCompany();
            $arr_company = $mas_com->getMasCompanyDetails($user->company_id);
            $this->setState('company_name', $arr_company->company_name);
            $this->setState('company_logo', $arr_company->company_logo);
            $this->setState('pdf_company_logo', "pdf_" . $arr_company->company_logo);
            $this->setState('billing_address', $arr_company->billing_address);
            $this->setState('import_key', 0);
            $authorised_user = 0;
            if ($user->level == 0)
                $authorised_user = 1;

            $this->setState('authorised_user', $authorised_user);
            if ($user->user_group_id > 0) {
                $userGroupmodel = MasUserGroup::model()->findByPk($user->user_group_id);
                $permissionArray = array();
                if (!empty($userGroupmodel->permissions)) {
                    $permissionArray = CJSON::decode($userGroupmodel->permissions);
                    $formatted_array = array_map(function($num) {
                        return (is_numeric(trim($num)) ? number_format(floatval($num), 0, '', '') : $num);
                    }, $permissionArray);
                } else {
                    $formatted_array = array();
                }
                $this->setState('havePermissionOn', array_merge($formatted_array));
            } else {
                $this->setState('havePermissionOn', array());
            }
            $this->username = $user->username;
            $this->errorCode = self::ERROR_NONE;
        }
        return $this->errorCode == self::ERROR_NONE;
    }

    public function getId() {
        return $this->_id;
    }

}
