<?php

class Core_Doctrine_Model_UserTable extends Core_Doctrine_Table implements
    Core_Doctrine_Table_Interface,
    Core_User_IdentityDiscovery_Interface,
    Core_User_Credentials_Interface
{
    const CONTENT_TYPE_ID = 7;

    protected $_defaults = array(
        'select'  => array(
            '*',
        ),
        'limit'   => 10,
        'offset'  => 0,
    );

    /**
     * Returns an instance of this class.
     *
     * @return UserTable
     */
    public static function getInstance()
    {
        return Doctrine_Core::getTable('User');
    }

    public function checkCredentials($email, $password)
    {
        $query = $this->createQuery()
                      ->select('*')
                      ->andWhere('email = ?', $email)
                      ->andWhere('password = ?', $password)
                      ->execute();

        return (bool) $query->count();
    }

    public function save(Doctrine_Record $entity)
    {
        $config = Core_Application::get('resourceFinder')
            ->find('sharedForm', new Core_Dispatcher_Location, array('name' => 'user.yml'));
        $this->_validate($entity, $config);

        $entity->save();

        return $entity;
    }

    protected function _validate(Doctrine_Record $entity, $formIni)
    {
        $config = new Core_Config($formIni);
        $form   = new Core_Form($config);

        // Whatever request method is fine
        $form->setMethod(Core_Application::get('Request')->getMethod());

        if ($entity->exists()) {
            $form->getElement('email')->getValidator('unique')->setExclude(array('user_id' => $entity->id));
            $form->password->required = false;
        }

        // Populate values by hand, values do not come from the request per se
        $form->populate($entity->toArray());

        if (!$form->isValid()) {
            $errors = $form->getErrors();

            $exception = new Core_Validate_Exception('Error while validating values');
            $exception->setErrors($errors);

            throw $exception;
        } else {
            return true;
        }
    }

    /**
     * @param array $params
     * @param string $searchString
     *
     * @return array
     *
     * this method finds all users containing $searchString
     * in their first or last name
     */
    public function getAny(array $params, $searchString = '')
    {
        $query = $this->generateQuery($params);

        if (strlen($searchString)) {
            $query->andWhere(
                'CONCAT(first_name, " ", last_name) LIKE :query',
                array(
                    'query' => '%'. $searchString .'%'
                )
            );
        }
        $query->andWhere('deleted_at is null');

        $items = $query->fetchArray();
        $result = array(
            'items'  => $items,
            'count'  => count($items),
            'total'  => $query->count(),
            'limit'  => $params['limit'],
            'offset' => $params['offset'],
        );

        return $result;
    }
}
