<?php
/**
 *This controller is responsible for processing actions with users
 *
 *@author Pavel Savchuk
 */
class Backend_UserController extends RCMS_Core_BaseController {

	public function init()
    {
		parent::init();
        $this->checkLogin();
		$this->_model = new Default_Model_UserModel();
	}

    public function indexAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $form = new RCMS_Form_UserForm();
        $form->role->setMultiOptions($this->_model->selectRoles());
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/user.phtml'))
            ));
        $this->view->form = $form;

        if($this->getRequest()->isPost() &&
            $this->view->form->isValid($this->getRequest()->getParams()))
        {
            switch ($this->getRequest()->getParam('submit'))
            {
                case 'Add':
                    $exist = $this->_model->selectUserByLogin($this->view->form->login->getValue());
                    if(intval($exist) == 0) {
                        $user = new RCMS_Object_User_User();
                        $user->setNickName($this->view->form->nickname->getValue());
                        $user->setLogin($this->view->form->login->getValue());
                        $user->setPassword(md5($this->view->form->password->getValue()));
                        $user->setEmail($this->view->form->email->getValue());
                        $user->setRoleId($this->view->form->role->getValue());
                        $user->setIdSeosambaUser(0);
                        $user->setStatus('active');
                        $user->setLastLogin(date("Y-m-d H:i:s"));
                        $user->setRegDate(date("Y-m-d H:i:s"));
                        $user->setIpAddress($_SERVER['REMOTE_ADDR']);
                        $user->save();
                        $this->view->form->reset();
                        $this->view->success = 'User added.';
                    } else {
                        $this->view->error = 'This login is existed.';
                    }
                    break;
                case 'Update':
                    $login = $this->view->form->login->getValue();
                    $user = new RCMS_Object_User_User($this->view->form->id->getValue());
                    $exist = $this->_model->selectUserByLogin($login);
                    
                    if($exist == 0 || ($exist == 1 && $login == $user->getLogin())) {
                        $user->setNickName($this->view->form->nickname->getValue());
                        $user->setLogin($login);
                        if($user->getPassword() != $this->view->form->password->getValue()) {
                            $user->setPassword(md5($this->view->form->password->getValue()));
                        }
                        $user->setEmail($this->view->form->email->getValue());
                        $user->setRoleId($this->view->form->role->getValue());
                        $user->save();                        
                    } else {                        
                        $this->view->error = 'This login is existed.';
                    }
                    $this->view->form->reset();
                    break;
            }
        }
        else
        {
            $errors = $this->view->form->getMessages();            
            $this->view->error = $this->generateError($errors);
        }
        $this->view->users = $this->_model->selectAllUser();
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

/**
 *
 * @param <array> $errors
 * @return <string>
 */
    private function generateError($errors)
    {
        if(!empty($errors) && is_array($errors))
        {
            $message = '';
            foreach($errors as $field => $error)
            {
                switch ($field)
                {
                    case 'nickname':
                        $message .= (isset($error['isEmpty'])?"Nickname field can't be empty.\n":'');
                        $message .= (isset($error['regexNotMatch'])?"Nickname field can only contain letters, digits, spaces, '-' and '_'.\n":'');
                        break;
                    case 'login':
                        $message .= (isset($error['isEmpty'])?"Login field can't be empty.\n":'');
                        $message .= (isset($error['regexNotMatch'])?"Nickname field can only contain letters, digits, '-' and '_'.\n":'');
                        break;
                    case 'password':
                        $message .= (isset($error['isEmpty'])?"Password field can't be empty.\n":'');
                        $message .= (isset($error['stringLengthTooShort'])?"Password field is too short (minimum 5 characters).\n":'');
                        $message .= (isset($error['stringLengthTooLong'])?"Password field is is too long (maximum 255 characters).\n":'');
                        break;
                    case 'email':
                        $message .= (isset($error['isEmpty'])?"Email field can't be empty.\n":'');
                        $message .= (isset($error['regexNotMatch'])?"Email field is wrong.\n":'');
                        break;
                    case 'role':
                        $message .= (isset($error['isEmpty'])?"Role field can't be empty.\n":'');
                        break;
                }
            }
            return nl2br($message);
        }
        return '';
    }

}
