<?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->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->fetchRow($this->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)
    {
        // Find the user first, to fetch salt.
        $user = $this->findByEmail($email);
        if (!$user) {
            return false;
        }
        
        $hash = $this->_hash($password, $user->salt);
        
        // Setup auth adapter
        $authAdapter = new Zend_Auth_Adapter_DbTable($this->getAdapter(), 
                $this->_name, 'email', 'password');

        // Set credentials
        $authAdapter->setIdentity($email);
        $authAdapter->setCredential($hash);

        // Authenticate
        $auth = Zend_Auth::getInstance();
        $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;
        }
        
        $salt = $this->_generateSalt(128);
        $hash = $this->_hash($password, $salt);

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

    protected function _generateSalt()
    {
        return md5(uniqid(rand(), true));
    }

    protected function _hash($data, $salt)
    {
        return hash('sha256', $salt . $data);
    }
}