<?php 
class userController extends Zend_Controller_Action
{

    public function init()
    {
        MyWeb_Log_ApplicationLogger::addLog($this,1,4);
        MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'UserController');
        
        // kontrola opravneni
        $authentication = new MyWeb_Controller_Plugin_Authentication();
        $authentication->dispatchLoopStartup($this->_request);
    }

    public function indexAction()
    {
        MyWeb_Log_ApplicationLogger::addLog($this,2,4);
        MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'UserController');
        
        // kontrola opravneni
        $authentication = new MyWeb_Controller_Plugin_Authentication();
        $authentication->dispatchLoopStartup($this->_request);
    }

    public function listAction()
    {
    	try {
        	MyWeb_Log_ApplicationLogger::addLog($this,3,4);
        	MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'UserController');
        
        	// kontrola opravneni
        	$authentication = new MyWeb_Controller_Plugin_Authentication();
        	$authentication->dispatchLoopStartup($this->_request);
        	
        	$modelUser = MyWeb_Model_Database::loadModel('User');
        
        	$this->view->links = NULL;
        	if (Zend_Auth::getInstance()->hasIdentity()){
        		$acl = MyWeb_Acl::getInstance();
        		
        		Zend_Auth::getInstance()->getIdentity()->id_user;
        		Zend_Auth::getInstance()->getIdentity()->user_name;
        		Zend_Auth::getInstance()->getIdentity()->user_name;
        		$url = new Zend_View_Helper_Url();
        		if ($acl->isAllowed(Zend_Auth::getInstance()->getIdentity()->role_role,$this->getRequest()->getControllerName(),'listLinkEdit')){
        			$this->view->links['id_user']['link'] = $url->url(array('controller' => 'user', 'action' => 'edit'), 'default', true);
        			$this->view->links['id_user']['get'][0] = 'id_user';
        		}
        	}
    		$paginator = new MyWeb_Controller_Plugin_Paginator();
        	$paginator->setModel($modelUser);
        	$paginator->setData($this->getRequest()->getParams());
        	$paginator->setRequest($this->getRequest());
        	
        	$this->view->select = $modelUser->createFetchEntrySelect($this->getRequest()->getParams());
        	$this->view->pager = $paginator->getPaginator();
    	}catch (Exception $e){
    		echo $e->getMessage();
		}
    }

    public function list2Action()
    {
    	try {
        	MyWeb_Log_ApplicationLogger::addLog($this,3,4);
        	MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'UserController');
        
        	// kontrola opravneni
        	$authentication = new MyWeb_Controller_Plugin_Authentication();
        	$authentication->dispatchLoopStartup($this->_request);
        	
        	$modelUser = MyWeb_Model_Database::loadModel('User');
        	$form = $modelUser->getForm('search');
        
    		$paginator = new MyWeb_Controller_Plugin_Paginator();
        	$paginator->setModel($modelUser);
        	$paginator->setData($this->getRequest()->getParams());
        	$paginator->setRequest($this->getRequest());
        	
        	//********** Nastaveni javascriptu pro popup window ***********************
        	$jsPopupSlave = MyWeb_JavaScript_Popup_Abstract::createJsPopupSlave();
        	$jsPopupSlave->setIdInput('in');
        	$jsPopupSlave->addIdHidden('inid');
        	$jsPopupSlave->addIdHidden('inid');
        	$jsPopupSlave->addIdHidden('inid');
        	$jsPopupSlave->addIdHidden('inid');
        	$jsPopupSlave->setIdLink('button');
        	$js=$jsPopupSlave->js();
        
        	$jsPopupSlave->setNameFile('slaveList2');
        	//$jsPopupSlave->writeFileJs();
        
        	$this->view->javascriptPopupSlave = $js;
        	$this->view->select = $modelUser->createFetchEntrySelect($this->getRequest()->getParams());
        	$this->view->pager = $paginator->getPaginator();
    	}catch (Exception $e){
    		echo $e->getMessage();
		}
    }

    public function editAction()
    {
        MyWeb_Log_ApplicationLogger::addLog($this,4,4);
        MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'UserController');
        
        // kontrola opravneni
        $authentication = new MyWeb_Controller_Plugin_Authentication();
        $authentication->dispatchLoopStartup($this->_request);
        
        $id_user = $this->getRequest()->getParam('id_user');
        $modelUser = MyWeb_Model_Database::loadModel('User');
        $form = $modelUser->getForm('update');
        $dataUser = $modelUser->fetchEntry($id_user);
        
        if (Zend_Auth::getInstance()->hasIdentity()){
        	$acl = MyWeb_Acl::getInstance();
        	$url = new Zend_View_Helper_Url();
        	if (!$acl->isAllowed(Zend_Auth::getInstance()->getIdentity()->role_role,$this->getRequest()->getControllerName(),'userEditInputTextState')){
        		$form->removeElement('State_id_stateValue');
        	}
        }
        
        //*** prejmenovani hodnot k jmenum ve formulari napr. (state_id_stateValue)
        $dataUserDb['id_user'] = $dataUser['data']['id_user'];
        $dataUserDb['user_name'] = $dataUser['data']['user_name'];
        $dataUserDb['user_userName'] = $dataUser['data']['user_userName'];
        //$dataUserDb['user_passwd'] = $dataUser['data']['user_passwd'];
        $dataUserDb['State_id_stateValue'] = $dataUser['data']['nameState_name'];
        $dataUserDb['State_id_state'] = $dataUser['data']['State_id_state'];
        $dataUserDb['user_registrationDateTime'] = $dataUser['data']['date(user_registrationDateTime)'];
        
        $dataUserDb['State_id_stateInputName'] = 'State_id_state';
        $dataUserDb['State_id_state'] = $dataUser['data']['State_id_state'];
        $dataUserDb['nameState_nameInputName'] = 'nameState_name';
        $dataUserDb['nameState_nameInputValue'] = $dataUser['data']['nameState_name'];
        
        $id_user_db = $dataUser['data']['id_user'];
        $form->setAction('');
        
        
        if ($this->getRequest()->isPost() && 
        	((false !== $this->getRequest()->getPost('send',false)) || (false !== $this->getRequest()->getPost('delete',false)))){
        	if ($form->isValid($this->getRequest()->getPost())){
        		
        		$dataUserFormPost = $form->getValues();
        		foreach ($dataUserFormPost as $key => $value) {
        			$dataUserForm[$key]=$dataUserFormPost[$key];
        		}
        					
        		// !!! v poli post musi byt presne ty same polozky co jsou ve formulari a nesmi byt zadna navic
        		$dataUserForm['controller'] = 'user';
        		$dataUserForm['action'] = 'edit';
        		$dataUserForm['module'] = 'default';
        		$dataUserForm['send'] = 'edit';
        		//$dataUserForm['id_user'] = $dataUserFormPost['id_user']; //
        		$dataUserForm['user_name'] = $dataUserFormPost['user_name'];
        		$dataUserForm['user_userName'] = $dataUserFormPost['user_userName'];
        		if (!empty($dataUserFormPost['user_passwd'])){
        			$dataUserForm['user_passwd'] = $dataUserFormPost['user_passwd'];
        		}
        		$dataUserForm['State_id_stateValue'] = $dataUserFormPost['State_id_stateValue'];
        		
        		// datum registrace je nezmenitelny
        		$dataUserForm['user_registrationDateTime'] = $dataUserDb['user_registrationDateTime'];
        		
        		$dataUserForm['State_id_stateInputName'] = $dataUserFormPost['State_id_stateInputName'];
        		$dataUserForm['State_id_state'] = $dataUserFormPost['State_id_state'];
        		$dataUserForm['nameState_nameInputName'] = $dataUserFormPost['nameState_nameInputName'];
        		$dataUserForm['nameState_nameInputValue'] = $dataUserFormPost['nameState_nameInputValue'];
        		
        		if ($this->getRequest()->isPost() && false !== $this->getRequest()->getPost('delete',false)){
        			$dataUserForm['State_id_state'] = $modelUser->getIdState('disabled', $this->getRequest()->getControllerName());
        			$modelUser->update($dataUserForm, $id_user_db);
        			$this->_redirect('/user/list/');
        		}
        		
        		// overeni jedinecnosti user_userName
        		$validator = new Zend_Validate_Db_NoRecordExists(
        			array(
        				'table' => 'user',
        				'field' => 'user_userName',
        				'exclude' => array(
        					'field' => 'id_user',
        					'value' => $id_user_db
        					)
        				)
        			);
        		
        		if ($this->getRequest()->isPost() && false !== $this->getRequest()->getPost('send',false)){
        			if ($validator->isValid($dataUserForm['user_userName'])) {
        				$modelUser->update($dataUserForm, $id_user_db);
        				//$this->_redirect('/user/edit/id_user/'.$id_user_db);
        			}else {
        				$messages = $validator->getMessages();
        				foreach ($messages as $message) {
        					echo "$message\n";
        				}
        			}
        		}
        	}
        	}else {
        		$form->populate($dataUserDb);
        	}
        			
        			
        			
        			
        	
        			//********** Nastaveni javascriptu pro popup window ***********************
        			$jsPopupMain = MyWeb_JavaScript_Popup_Abstract::createJsPopupMain();
        			$jsPopupMain->setSourceController('user');
        			$jsPopupMain->setSourceAction('edit');
        			$jsPopupMain->addLinkPopupWindow('okno', 'list2');
        			$jsPopupMain->addIdInputs('State_id_stateValue');
        			$jsPopupMain->addControllerLinkOpenWindow('state');
        
        			//lepsi je pro kazde individualni nazev bez indexace
        			$jsPopupMain->addIdHidden(0,'State_id_state');
        			$jsPopupMain->addIdHidden(0,'nameState_nameInputValue');
        			$jsPopupMain->addIdHidden(0,'State_id_stateInputName');
        			$jsPopupMain->addIdHidden(0,'nameState_nameInputName');
        			$jsPopupMain->levelDirectory(4);
        
        			$js=$jsPopupMain->js();
        			$jsPopupMain->setNameFile('mainEdit');
        			//$jsPopupMain->writeFileJs();
        
        
        			$jsPopupMain->setNameFileLink('mainEditLink');
        			$jsPopupMain->addParamGetLinkOpenPopup(0,'tableDatabase_table', 'user');
        			//$jsPopupMain->writeFileJsLinks();
        			$jsOpenLinks = $jsPopupMain->jsOpenLinks();
        
        $this->view->jsOpenLinks = $jsOpenLinks;
        $this->view->javascriptPopupMain = $js;
        $this->view->form=$form;
    }

    
    
    
    public function searchAction()
    {
        MyWeb_Log_ApplicationLogger::addLog($this,5,4);
        MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'UserController');
        
        // kontrola opravneni
        $authentication = new MyWeb_Controller_Plugin_Authentication();
        $authentication->dispatchLoopStartup($this->_request);
        
        $modelUser = MyWeb_Model_Database::loadModel('User');
        $form = $modelUser->getForm('search');
        
        if ($this->getRequest()->isPost() && (false !== $this->getRequest()->getPost('send',false))){
        	if ($form->isValid($this->getRequest()->getPost())){
        		
        		//*** prevod formatu data z m/d/Y na Y-m-d ****
        		$dateTime = $form->getValue('user_registrationDateTime');
        		$dateConverter = new MyWeb_Controller_Plugin_ConverterDate();
        		$dateTime = $dateConverter->convertDateA($dateTime);
        		
        		$this->_redirect('/user/list'.
        		'/user_name/'.$form->getValue('user_name').
        		'/user_userName/'.$form->getValue('user_userName').
        		'/user_registrationDateTime/'.$dateTime.
        		'/State_id_stateValue/'.$form->getValue('State_id_stateValue').
        		'/State_id_stateInputName/'.$form->getValue('State_id_stateInputName').
        		'/State_id_stateInputValue/'.$form->getValue('State_id_stateInputValue').
        		'/Role_id_roleValue/'.$form->getValue('Role_id_roleValue')
        		);
        	}
        }
        
        
        
        //********** Nastaveni javascriptu pro popup window ***********************
        $jsPopupMain = MyWeb_JavaScript_Popup_Abstract::createJsPopupMain();
        $jsPopupMain->setSourceController('user');
        $jsPopupMain->setSourceAction('search');
        $jsPopupMain->addLinkPopupWindow('okno', 'list2');
        $jsPopupMain->addLinkPopupWindow('okno1', 'list2');
        $jsPopupMain->addIdInputs('State_id_stateValue');
        $jsPopupMain->addControllerLinkOpenWindow('state');
        $jsPopupMain->addIdInputs('Role_id_roleValue');
        $jsPopupMain->addControllerLinkOpenWindow('role');
        
        //lepsi je pro kazde individualni nazev bez indexace
        $jsPopupMain->addIdHidden(0,'State_id_stateInputValue');
        $jsPopupMain->addIdHidden(0,'nameState_nameInputValue');
        $jsPopupMain->addIdHidden(0,'State_id_stateInputName');
        $jsPopupMain->addIdHidden(0,'nameState_nameInputName');
        
        $jsPopupMain->addIdHidden(1,'Role_id_roleInputValue');
        $jsPopupMain->addIdHidden(1,'Role_roleInputValue');
        $jsPopupMain->addIdHidden(1,'Role_id_roleInputName');
        $jsPopupMain->addIdHidden(1,'Role_roleInputName');
        
        
        
        $js=$jsPopupMain->js();
        $jsPopupMain->setNameFile('mainSearch');
        $jsPopupMain->writeFileJs();
        
        $jsPopupMain->setNameFileLink('mainSearchLink');
        $jsPopupMain->addParamGetLinkOpenPopup(0,'tableDatabase_table', 'user');
        //$jsPopupMain->writeFileJsLinks();
        $jsOpenLinks = $jsPopupMain->jsOpenLinks();
        
        $this->view->jsOpenLinks = $jsOpenLinks;
        $this->view->javascriptPopupMain = $js;
        $this->view->form=$form;
    }

    public function newAction()
    {
        MyWeb_Log_ApplicationLogger::addLog($this,6,4);
        MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'UserController');
        
        // kontrola opravneni
        $authentication = new MyWeb_Controller_Plugin_Authentication();
        $authentication->dispatchLoopStartup($this->_request);
        
        $modelUser = MyWeb_Model_Database::loadModel('User');
        $modelUserHasRole = MyWeb_Model_Database::loadModel('UserHasRole');
        $modelRole = MyWeb_Model_Database::loadModel('Role');
        
        $form = $modelUser->getForm('insert');
        
        if ($this->getRequest()->isPost() && (false !== $this->getRequest()->getPost('send',false))){
        	$dataUserFormPost = $this->getRequest()->getParams();
        	foreach ($dataUserFormPost as $key => $value) {
        		$dataUserForm[$key]=$dataUserFormPost[$key];
        	}
        		
        		
        	// !!! v poli post musi byt presne ty same polozky co jsou ve formulari a nesmi byt zadna navic
        	$dataUserForm['controller']						=	'user';
        	$dataUserForm['action']							=	'edit';
        	$dataUserForm['module']							=	'default';
        	$dataUserForm['send']							=	'edit';
        	$dataUserForm['State_id_state']					=	$modelUser->getIdState('unconfirmed', 'user');
        	$dataUserForm['user_name']						=	$dataUserFormPost['user_name'];
        	$dataUserForm['user_userName']					=	$dataUserFormPost['user_userName'];
        	$dataUserForm['user_passwd']					=	$dataUserFormPost['user_passwd'];
        	$date = getdate();
        	$dataUserForm['user_registrationDateTime']				=	$date['year']."-".$date['mon']."-".$date['mday'];//'2012-02-10 08:04:01';
        	//data nutna pro pridani do tabulky spojovaci M:N
        	$dataUserForm['Role_id_role']					=	$modelUser->getIdRole('guest');
        	
        	// overeni jedinecnosti user_userName
        	$validator = new Zend_Validate_Db_NoRecordExists(
        		array(
        			'table' => 'user',
        			'field' => 'user_userName'
        			)
        		);
        	
        	
        	
        	if ($form->isValid($this->getRequest()->getPost())){
        		if ($validator->isValid($dataUserForm['user_userName'])) {
        			$modelUser->insert($dataUserForm);
        			//$this->_redirect('/user/edit/id_user/'.$id_user_db);
        		}else {
        			$messages = $validator->getMessages();
        			foreach ($messages as $message) {
        				echo "$message\n";
        			}
        		}
        	}else {
        		$form->populate($dataUserForm);// naplni formular pokud se vyskitla chyba
        	}
        }
        
        //********** Nastaveni javascriptu pro popup window ***********************
        $this->view->jsOpenLinks = '';
        $this->view->javascriptPopupMain = '';
        $this->view->form=$form;
    }

    
    public function loginAction()
    {
    	
        // inicializuje model																							
        $modelUser = MyWeb_Model_Database::loadModel('user');							
        // inicializuje fotmulare																						
        $form = $modelUser->getForm('login');											
        $form->setAction('');
        // otestuje, zda byl odeslan formular																			
        if ($this->getRequest()->isPost() && false !== $this->getRequest()->getPost('submit_login', false)) {	
        	// otestuje korektnost Ä‚ĹźdajÄąĹ»																			
        	if ($form->isValid($this->getRequest()->getPost())) {														
        		$authentication = new MyWeb_Controller_Plugin_Authentication();										
        		$authentication->dispatchLoopStartup($this->_request);													
        	}																											
        }																												
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        // inicializuje model																	
        $modelUser = MyWeb_Model_Database::loadModel('user');
        // inicializuje formulare																
        $form = $modelUser->getForm('logout');				
        // otestuje, zda byl odeslni formulare													
        if ($this->getRequest()->isPost() && false !== $this->getRequest()->getPost('submit_logout', false)) {		
        	// odhlaseni uzivatele															
        	Zend_Auth::getInstance()->clearIdentity();										
        	// stranka smeruje na uvodni stranku											
        	$this->_redirect('/');														
        }																						
        //generovani formulare pohledu															
        $this->view->form = $form;
    }

    public function forbiddenAction()
    {
        
    }


}
