<?php

/**
 * UsersController - User accounts management
 * 
 * @author Lukáš Havlíček
 * @version 1.0
 */
class Admin_UsersController extends Zend_Controller_Action 
{
	
	
	public function init()
	{
		$this->view->topmenu = 6;
		$this->view->leftmenu = 2;
	}
	/**
	 * The default action - show the home page
	 */
    public function indexAction() 
    {
		$page = (int) $this->_getParam('page');
    	if ($page < 1  || !$page) $page = 1;
    	
    	$sort = $this->_getParam('sort', '');
    	if ($sort != 'ASC' && $sort != 'DESC') $sort = '';
    	
    	$order = $this->_getParam('order', '');
    	
    	if (!$order && !$sort) {
    		$orderby = 'id_user DESC';
    	} else {
    		$orderby = $order . ' ' . $sort;
    	}
    	
    	$this->view->page = $page;
    	$this->view->order = $order;
    	$this->view->sort = $sort;
    	
    	$table = new Users();
    	
    	
    	$select = $table->select()->where('user_active_request = 1');
    	$this->view->requests = $table->fetchAll($select);
    	
		$select = $table->select();
						
						
		$search = urldecode($this->_request->getParam('search'));
		if ($search) {
			if (strpos($search, ' ')) {
				$parts = explode(' ', $search);
				$select->where('user_firstname LIKE ?', '%' . $parts[0] . '%');
				$select->where('user_surname LIKE ?', '%' . $parts[1] . '%');
			} else {
				$select->where('user_firstname LIKE ?', '%' . $search . '%');
				$select->orWhere('user_surname LIKE ?', '%' . $search . '%');
				$select->orWhere('login LIKE ?', '%' . $search . '%');
			}
			
		}
		
		$this->view->search = urlencode($search);
		
		$select->order($orderby);
    	
    	$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($select));
    	$paginator->setCurrentPageNumber($page);
    	$paginator->setItemCountPerPage(30);
    	$paginator->setPageRange(10);
    	
    	$this->view->data = $paginator;
    }
    
    public function activateAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	if ($id) $this->changeState($id, 1);
    	$this->_redirect('/admin/users');
    }
    
    public function deactivateAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	if ($id) $this->changeState($id, 0);
    	$this->_redirect('/admin/users');
    }
    
    private function changeState($id, $state)
    {
    	$table = new Users();
    	$row = $table->fetchRow($table->select()->where('id_user = ?', (int) $id));
    	if ($row) {
    		$row->user_active = (int) $state;
    		$row->user_active_request = 0;
    		$row->save();
    		$this->_redirect('/admin/users/index/msg/4');
    	} else {
    		$this->_redirect('/admin/users');
    	}
    }
    
    public function addAction()
    {
    	$form = $this->getForm();
    	
    	if ($this->_request->isPost()) {
    		
    		if ($form->isValid($_POST)) {
    			$table = new Users();
    			$values = $form->getValues();
    			
    			$password = $table->generatePassword(8);

    			$values['password'] = sha1($password);
    			$values['user_active'] = 1;
    			$values['week_start'] = 'mon';
    			$values['lang'] = 'cs';
    						
    			if ($table->insert($values))
    			{
    				$mailer = new Mailer();
    				$values['password'] = $password;
    				$mailer->send('registrationByAdmin', $values['email'], $values);
    			}
    			$this->_redirect('/admin/users/index/msg/1');
    			
    		} else {
    			
    			$form->populate($form->getUnfilteredValues());
    			if ($form->isErrors()) {
    				$helper = new FormHelper();
    				$errors = $helper->errorsToString($form);
    				$this->view->errors = $errors;
    			}
                        	
    		}
    		
    	}
    	
    	$this->view->form = $form;
    	
    	$this->view->edit = 0;
    	$this->render('add-edit');
    }
    
    public function editAction()
    {
    	$form = $this->getForm();
    	$table = new Users();
    	
    	if ($this->_request->isPost()) {
    		
    		if ($form->isValid($_POST)) {
    			
    			$values = $form->getValues();
    			$where  = $table->getAdapter()->quoteInto('id_user = ?', $values['id_user']);
    			unset($values['id_user']);
    			$table->update($values, $where);
    			$this->_redirect('/admin/users/index/msg/2');
    			
    		} else {
    			
    			$form->populate($form->getUnfilteredValues());
    			if ($form->isErrors()) {
    				$helper = new FormHelper();
    				$errors = $helper->errorsToString($form);
    				$this->view->errors = $errors;
    			}
                        	
    		}
    		
    	}
    	
    	$id = (int) $this->_getParam('id');
    	
    	$row = $table->fetchRow($table->select()->where('id_user = ?', $id));
    	$form->populate($row->toArray());
    	
    	$this->view->form = $form;
    	$this->view->edit = 1;
    	
    	//member of groups
    	$tableCont = new UserGroup();
    	$this->view->data = $tableCont->getGroups($id);
    	
    	$this->render('add-edit');
    }
    
    private function getForm()
    {
    	$form = new Zend_Form();
    	$form->clearDecorators();
    				
    	$form->addElement(new Zend_Form_Element_Text(array(
    					'name'	=> 'login',
    					'label' => 'uzivatelske-jmeno-f',
    					'required' => true
    				)));
    	
    	$form->addElement(new Zend_Form_Element_Text(array(
    					'name'	=> 'user_firstname',
    					'label' => 'jmeno-f'
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Text(array(
    					'name'	=> 'user_surname',
    					'label' => 'prijmeni-f'
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Text(array(
    					'name'	=> 'email',
    					'label'	=> 'e-mail-f'
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Select(array(
    					'name'	=> 'super_admin',
    					'label'	=> 'typ-uzivatele-f',
    					'multioptions' => array(0 => 'Běžný uživatel', 1 => 'Administrátor')
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Hidden(array(
    					'name'	=> 'id_user'
    				)));
    	
    	return $form;
    }
    
    public function deleteAction()
    {
    	$id   = (int) $this->_getParam('id', 0);
    	$thru = (int) $this->_getParam('thru', 0);
    	
    	$table = new Users();
    	
    	if ($thru && $id) {
    		$table->delete($table->getAdapter()->quoteInto('id_user = ?', $id));
    		$this->_redirect('/admin/users');
    	}
    	
    	if ($this->_request->isPost()) {
    		$id = (int) $this->_request->getPost('id');
    		if ($id) {
    			$table->delete($table->getAdapter()->quoteInto('id_user = ?', $id));
    			$this->_redirect('/admin/users/index/msg/3');
    		} else {
    			$this->_redirect('/admin/users');
    		}
    	} else {
    		$row = $table->fetchRow($table->select()->where('id_user = ?', $id));
    		if ($row) {
    			$this->view->data = $row;
    		} else {
    			$this->_redirect('/admin/users');
    		}
    	}
    }
    
    public function allDocsAction()
    {
    	$id = $this->_getParam('id', 0);
    	$table = new UserGroup();
    	
    	$rows = $table->fetchAll($table->select()->where('id_user = ?', $id)->where('active = 1'));
    	$groups = array();
    	foreach ($rows as $i) {
    		$groups[] = $i->id_group;
    	}
    	
    	$result = array();
    	
    	if (count($groups)) {
    	
	    	$rights = new Rights();
	    	$select = $rights->select()->setIntegrityCheck(false)
	    					 ->from(array('r' => 'iso_rights_group_category'), array(
	    					 			'r.id_rights',
	    					 			'r.id_group',
	    					 			'g.group_name',
	    					 			'c.category_name',
	    					 			'd.id_document',
	    					 			'd.doc_name'
	    					 		))
	    				     ->joinLeft(array('c' => 'iso_categoryies'), 'c.id_category = r.id_category')
	    				     ->joinLeft(array('g' => 'iso_groups'), 'g.id_group = r.id_group')
	    				     ->join(array('d' => 'iso_documents'), 'r.id_category = d.id_category')
	    				     ->where('r.id_group IN (' . implode(',', $groups) .')')
	    				     ->where('r.rights_active = 1')
	    				     ->where('r.read = 1');
	    				     
	    				    
	    	$rows = $rights->fetchAll($select);
	    	$result = array();
	    	
	    	foreach ($rows as $i) {
	    		
	    		if (!isset($result[$i->id_document])) {
	    		
	    			$result[$i->id_document] = $i->toArray();
	    			$result[$i->id_document]['group_name'] = array($i->id_group => $result[$i->id_document]['group_name']);
	    		} else {
	    			$result[$i->id_document]['group_name'][$i->id_group] = $i->group_name;
	    		}
	    	}
    	}
    	
    	$users = new Users();
    	$row = $users->fetchRow($users->select()->where('id_user = ?', $id));

    	$this->view->data = $result;	
    	$this->view->item = $row;	
    }
    
    public function activateMemberAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	$user = (int) $this->_getParam('user', 0);
    	if ($id && $user) $this->changeMemberState($id, $user, 1);
    	$this->_redirect('/admin/users/edit/id/' . $user . '#groups');
    }
    
    public function deactivateMemberAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	$user = (int) $this->_getParam('user', 0);
    	if ($id && $user) $this->changeMemberState($id, $user, 0);
    	$this->_redirect('/admin/users/edit/id/' . $user . '#groups');
    }
    
    private function changeMemberState($id, $user, $state)
    {
    	$table = new UserGroup();
    	$row = $table->fetchRow($table->select()->where('id_group = ?', (int) $id)->where('id_user = ?', (int) $user));
    	if ($row) {
    		$row->active = (int) $state;
    		$row->save();
    		$this->_redirect('/admin/users/edit/id/' . $user. '/msg/5#groups');
    	} else {
    		$this->_redirect('/admin/users/edit/id/' . $user . '#groups');
    	}
    }
}
