<?php
/**
 * Description of AuthController
 *
 */
class AuthController extends Fiktiv_Controller_Action
{
    /**
     * Let the user connect with a world of
     * possibilities
     */
    public function loginAction()
    {
        // Redirect if user is logged in
        if (Zend_Auth::getInstance()->hasIdentity())
            $this->_redirect('/');


        // Do authentication magic
        $form = new Zend_Form();

        $emailElement = new Zend_Form_Element_Text('email');
        $emailElement->setLabel($this->translate('u:email'))
                     ->setRequired(true)
                     ->addValidator('NotEmpty', true)
                     ->addValidator('EmailAddress', true);

        $emailElement->getValidator('EmailAddress')->setMessage('u:ERROR_FORM_EMAIL_INVALID', Zend_Validate_EmailAddress::INVALID_FORMAT);
        $emailElement->getValidator('NotEmpty')->setMessage('u:ERROR_FORM_EMPTY', Zend_Validate_NotEmpty::IS_EMPTY);


        $passwordElement = new Zend_Form_Element_Password('password');
        $passwordElement->setLabel($this->translate('u:password'))
                        ->setRequired(true)
                        ->addValidator('NotEmpty', true);

        $passwordElement->getValidator('NotEmpty')->setMessage('u:ERROR_FORM_EMPTY', Zend_Validate_NotEmpty::IS_EMPTY);

        $buttonElement = new Zend_Form_Element_Submit('login');

        $form->addElements(array($emailElement, $passwordElement, $buttonElement));

        if ($this->_request->isPost() && $form->isValid($this->_request->getParams())) {

            $users = new ModelUser();

            if ($users->login($this->_request->getParam('email'), $this->_request->getParam('password'))) {

                // TODO: redirect user
                $this->_redirect('/');
            } else {
                // TODO: Wrong email / password
            }
        }

        $this->view->form = $form;

    }

    /**
     * This baby makes sure the user is
     * no longer connected to the site
     */
    public function logoutAction()
    {
        // Destroy the magic!
        $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity())
            $auth->clearIdentity();

        $this->_redirect('/');
    }

}