<?php

class ModelUser extends Fiktiv_Model_Abstract
{
    protected $_schema   = 'fiktivkod';
    protected $_name     = 'User';
    protected $_primary  = 'id';
    protected $_rowClass = 'User';

    protected $_referenceMap    = array(
        'ModelBlogPost' => array(
            'columns'           => array('id'),
            'refTableClass'     => 'ModelBlogPost',
            'refColumns'        => array('userId')
        )
    );

    public function findById($id)
    {
        if (is_numeric($id)) {
            return $this->_createUser($this->_dbTable->find($id)->current());
        }

        return null;
    }

    /**
     * Fetch user based on email
     *
     * @return User
     */
    public function findByEmail($email)
    {
        // Atleast 6 character long
        if (is_string($email) && isset($email[5])) {
            
            $user = $this->_createUser($this->_dbTable->fetchRow($this->_dbTable->getAdapter()->quoteInto('email = ?', $email)));

            return $user;
        }

        return null;
    }

    /**
     * Get random user
     *
     * @return User
     */
    public function findRandom()
    {
         return $this->fetchAll(null, 'RAND()', 1)->current();
    }

    
    /**
     * Authenticate user
     *
     * @param string $email
     * @param string $password
     */
    public function login($email, $password)
    {
        $auth = Zend_Auth::getInstance();

        // Setup auth adapter
        $authAdapter = new Zend_Auth_Adapter_DbTable($this->getAdapter(), $this->_name, 'email', 'password');

        // Set credentials
        $authAdapter->setIdentity($email);
        $authAdapter->setCredential(hash('sha256',$password));

        // Authenticate
        $result = $auth->authenticate($authAdapter);
        
        // Check result
        if ($result->isValid()) {
            
            // Keep all but password and salt in session.
            $storage = $auth->getStorage();
            $user = $authAdapter->getResultRowObject(null, array('password', 'salt'));
            $storage->write($user);
            
            return true;
        }

        return false;
    }


    /**
     * Change password
     */
    public function setPassword($userId, $password)
    {

        if ($userId instanceof User)
            $userId = $userId->getId();

        if (!is_numeric($userId))
            return false;

        return $this->update(
                array(
                    'password' => hash('sha256',$password)
                ),
                $this->getAdapter()->quoteInto('id = ?',$userId)
        );
    }
    
}