<?php

/**
 * UsersController - User accounts management
 * 
 * @author Lukáš Havlíček
 * @version 1.0
 */
class Admin_GroupsController extends Zend_Controller_Action 
{
	
	
	public function init()
	{
		$this->view->topmenu = 6;
		$this->view->leftmenu = 3;
	}
	/**
	 * The default action - show the home page
	 */
    public function indexAction() 
    {
		$table = new Groups();
		$select = $table->select()
						->order('group_name ASC');
		
		$page = (int) $this->_getParam('page');
    	if ($page < 1  || !$page) $page = 1;
    	
    	$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($select));
    	$paginator->setCurrentPageNumber($page);
    	$paginator->setItemCountPerPage(30);
    	$paginator->setPageRange(10);
    	
    	$this->view->data = $paginator;
    	$this->view->msg = (int) $this->_getParam('msg', 0);
    }
    
    public function addAction()
    {
    	$form = $this->getForm();
    	
    	if ($this->_request->isPost()) {
    		
    		if ($form->isValid($_POST)) {
    			$table = new Groups();
    			$table->insert($form->getValues());
    			$this->_redirect('/admin/groups/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 Groups();
    	
    	if ($this->_request->isPost()) {
    		
    		if ($form->isValid($_POST)) {
    			
    			$values = $form->getValues();
    			$where  = $table->getAdapter()->quoteInto('id_group = ?', $values['id_group']);
    			unset($values['id_group']);
    			$table->update($values, $where);
    			$this->_redirect('/admin/groups/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_group = ?', $id));
    	$form->populate($row->toArray());
    	
    	$this->view->form = $form;
    	$this->view->edit = 1;
    	
    	//members
    	$tableCont = new UserGroup();
    	$this->view->data = $tableCont->getUsers($id);
    	
    	//rights
    	$rights = new Rights();
    	$select = $rights->select()
    					 ->where('id_group = ?', $id);
    	$rows = $rights->fetchAll($select);
    	$rightsArray = array();
		foreach ($rows as $i) {
			$rightsArray[$i->id_category] = array('id_rights' =>$i->id_rights, 
												  'rights_active' =>$i->rights_active,
												  'rights_read' =>$i->read,
												  'rights_add' =>$i->add,
												  'rights_edit' =>$i->edit,
												  'rights_del' =>$i->del,
												  );
		}
		$cats = new Categoryies();

		$this->view->cats = $cats->getMenu();
    	$this->view->rights = $rightsArray;

    	$this->render('add-edit');
    }
    
    public function editRightsAction()
    {
    	$request = $this->getRequest();
    	if ($request->isPost()) {
    		
			$id_group = $request->getPost('id_group');

			if (!$id_group) $this->redirect('/');
			
			$read = $request->getPost('read');
			$add = $request->getPost('add');
			$edit = $request->getPost('edit');
			$del = $request->getPost('del');
    		
			$table = new Rights();
			
			foreach ($read as $k => $i) {
				$data['read']	= $i;
				$data['add']	= $add[$k]; 
				$data['edit']	= $edit[$k]; 
				$data['del']	= $del[$k];
				
				if ($data['add'] || $data['edit'] || $data['del']) {
					$data['read'] = 1;
				}
				
				$table->update($data, 'id_rights = ' . (int) $k);
			}
			
			$this->_redirect('/admin/groups/edit/id/' . $id_group . '#rights');
    	}
    	$this->_redirect('/admin/groups');
    }
    
    private function getForm()
    {
    	$form = new Zend_Form();
    	$form->clearDecorators();
    				
    	$form->addElement(new Zend_Form_Element_Text(array(
    					'name'	=> 'group_name',
    					'label' => 'nazev-skupiny-f',
    					'required' => true
    				)));
    	
    	$form->addElement(new Zend_Form_Element_Checkbox(array(
    					'name'	=> 'group_active',
    					'label' => 'skupina-je-aktivni-f'
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Text(array(
    					'name'	=> 'group_note',
    					'label'	=> 'poznamka-f'
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Hidden(array(
    					'name'	=> 'id_group'
    				)));
    	
    	return $form;
    }
    
    public function deleteAction()
    {
    	$id   = (int) $this->_getParam('id', 0);
    	$thru = (int) $this->_getParam('thru', 0);
    	
    	$table = new Groups();
    	
    	if ($thru && $id) {
    		$table->delete($table->getAdapter()->quoteInto('id_group = ?', $id));
    		$this->_redirect('/admin/groups');
    	}
    	
    	if ($this->_request->isPost()) {
    		$id = (int) $this->_request->getPost('id');
    		if ($id) {
    			$table->delete($table->getAdapter()->quoteInto('id_group = ?', $id));
    			$this->_redirect('/admin/groups/index/msg/3');
    		} else {
    			$this->_redirect('/admin/groups');
    		}
    	} else {
    		$row = $table->fetchRow($table->select()->where('id_group = ?', $id));
    		if ($row) {
    			$this->view->data = $row;
    		} else {
    			$this->_redirect('/admin/groups');
    		}
    	}
    }
    
    public function activateAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	if ($id) $this->changeState($id, 1);
    	$this->_redirect('/admin/groups');
    }
    
    public function deactivateAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	if ($id) $this->changeState($id, 0);
    	$this->_redirect('/admin/groups');
    }
    
    private function changeState($id, $state)
    {
    	$table = new Groups();
    	$row = $table->fetchRow($table->select()->where('id_group = ?', (int) $id));
    	if ($row) {
    		$row->group_active = (int) $state;
    		$row->save();
    		$this->_redirect('/admin/groups/index/msg/4');
    	} else {
    		$this->_redirect('/admin/groups');
    	}
    }
    
    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/groups/edit/id/' . $id . '#members');
    }
    
    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/groups/edit/id/' . $id . '#members');
    }
    
    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/groups/edit/id/' . $id . '/msg/5#members');
    	} else {
    		$this->_redirect('/admin/groups/edit/id/' . $id . '#members');
    	}
    }
    
    public function deleteMemberAction()
    {
    	
    	$id   = (int) $this->_getParam('id', 0);
    	$user = (int) $this->_getParam('user', 0);
    	$thru = (int) $this->_getParam('thru', 0);
    	
    	$table = new UserGroup();
    	
    	if ($thru && $id && $user) {
    		$table->delete('id_group = ' . $id . ' AND id_user = ' . $user);
    		$this->_redirect('/admin/groups/edit/id/' . $id . '#members');
    	}
    	
    	if ($this->_request->isPost()) {
    		$id = (int) $this->_request->getPost('id');
    		if ($id && $user) {
    			$table->delete('id_group = ' . $id . ' AND id_user = ' . $user);
    			$this->_redirect('/admin/groups/edit/id/' . $id . '/msg/3#members');
    		} else {
    			$this->_redirect('/admin/groups/edit/id/' . $id);
    		}
    	} else {
    		$row = $table->fetchRow(
    					$table->select()->setIntegrityCheck(false)
    					      ->from($table)
    					      ->joinLeftUsing('iso_users', 'id_user')
    					      ->joinLeftUsing('iso_groups', 'id_group')
    						  ->where('iso_user_group.id_group = ?', $id)
    						  ->where('iso_user_group.id_user = ?', $user)
    		);
    		if ($row) {
    			$this->view->data = $row;
    		} else {
    			$this->_redirect('/admin/groups/edit/id/' . $id);
    		}
    	}
    }
    
	public function addMembersAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	
    	$table = new Groups();
    	$tableCont = new UserGroup();

    	if ($this->_request->isPost()) {
			
			$rows = $tableCont->fetchAll($tableCont->select()->where('id_group = ?', $id));
			$control = array();
			foreach ($rows as $i) {
				$control[] = $i->id_user;
			}
			
			
						
						
			$search = urldecode($this->_request->getParam('search'));
			if ($search) {
				
				$tableUsers = new Users();
				$select = $tableUsers->select();
				
				if (count($control))
					$select->where('id_user NOT IN (' . implode(',', $control) . ')');
				
				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%' 
									OR user_surname LIKE '%$search%' 
									OR login LIKE '%$search%')");
				}
				
				$this->view->data = $tableUsers->fetchAll($select);  
			}
    	}
    	
    	$this->view->basic = $table->fetchRow($table->select()->where('id_group = ?', $id));
    }
    
    public function multiAddMembersAction()
    {
    	if ($this->_request->isPost()) {
    		$id = (int) $this->_request->getPost('id');
    		$event = $this->_request->getPost('event');
    		
    		if (is_array($event) && count($event)) {
    			
    			$table = new UserGroup();
    			
    			$rows = $table->fetchAll($table->select()->where('id_group = ?', $id));
    			
    			$controll = array();
    			foreach ($rows as $i) {
    				$controll[] = $i->id_user;
    			}
    			
    			$data['id_group'] = $id;
    			$data['active'] = 1;
    			
    			foreach ($event as $j) {
    				if (!in_array($j, $controll)) {
    					$data['id_user'] = $j;
    					$table->insert($data);
    				}
    			}
				$this->_redirect('/admin/groups/edit/id/' . $id . '#members');
    		}
    	}
    	$this->_redirect('/admin/groups');
    }
    
    public function activateRightsCategoryAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	$rights = (int) $this->_getParam('rights', 0);
    	if ($id && $rights) $this->changeRightsCategoryState($rights, $id, 1);
    	$this->_redirect('/admin/groups/edit/id/' . $id . '#rights');
    }
    
    public function deactivateRightsCategoryAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	$rights = (int) $this->_getParam('rights', 0);
    	if ($id && $rights) $this->changeRightsCategoryState($rights, $id, 0);
    	$this->_redirect('/admin/groups/edit/id/' . $id . '#rights');
    }
    
    private function changeRightsCategoryState($rights, $id, $state)
    {
//    	$table = new Rights();
//    	$row = $table->fetchRow($table->select()->where('id_rights = ?', (int) $rights));
//    	if ($row) {
//    		
//    		$cats = new Categoryies();
//    		$descendants = $cats->getAllDescendants($row->id_category);
//    		
//    		$data['rights_active'] = $state;
//    		foreach ($descendants as $i) {
//    			$table->update($data, "id_category = $i AND id_group = $id");
//    		}
//    		
//    		$this->_redirect('/admin/groups/edit/id/' . $id . '/msg/5#rights');
//    	} else {
//    		$this->_redirect('/admin/groups/edit/id/' . $id . '#rights');
//    	}
    	
    	$table = new Rights();
    	$row = $table->fetchRow($table->select()->where('id_rights = ?', (int) $rights));
    	if ($row) {
    		
    		$row->rights_active = (int) $state;
    		$row->save();
    		
    		$this->_redirect('/admin/groups/edit/id/' . $id . '/msg/5#rights');
    	} else {
    		$this->_redirect('/admin/groups/edit/id/' . $id . '#rights');
    	}
    }
    
    public function deleteRightsCategoryAction()
    {
    	
    	$id   = (int) $this->_getParam('id', 0);
    	$rights = (int) $this->_getParam('rights', 0);
    	$thru = (int) $this->_getParam('thru', 0);
    	
    	$table = new Rights();
    	$row = $table->fetchRow($table->select()->where('id_rights = ?', $rights));
    	
    	$descendants = array();
    	if ($row) {
    		$categoryies = new Categoryies();
    		$descendants = $categoryies->getAllDescendants($row->id_category);
    	
    	
	    	if ($thru && $id && $rights) {
	    		
	    		foreach ($descendants as $i) {
	    			$table->delete('id_group = ' . (int)$row->id_group . ' AND id_category = ' . (int)$i );
	    		}
	    		
	    		$this->_redirect('/admin/groups/edit/id/' . $id . '#rights');
	    	}
	    	
	    	if ($this->_request->isPost()) {
	    		$id = (int) $this->_request->getPost('id');
	    		$pass = (int) $this->_request->getPost('pass');
	    		if ($id && $pass) {
	    			$table->delete('id_rights = ' . $id);
	    			$this->_redirect('/admin/groups/edit/id/' . $pass . '/msg/3#rights');
	    		} else {
	    			$this->_redirect('/admin/groups/edit/id/' . $pass);
	    		}
	    	} else {
	    		$row = $table->fetchRow(
	    			$table->select()->setIntegrityCheck(false)
	    				  ->from($table)
	    				  ->joinLeftUsing('iso_categoryies', 'id_category')
	    				  ->where('id_rights = ?', $rights)
	    			);
	    		if ($row) {
	    			$this->view->data = $row;
	    		} else {
	    			$this->_redirect('/admin/groups/edit/id/' . $id);
	    		}
	    	}
    	}
    	$this->_redirect('/admin/groups/edit/id/' . $id);
    }
    
    public function addRightsCategoryAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	
    	$table = new Groups();
    	$tableCont = new Rights();

    	if ($this->_request->isPost()) {
			
    		$form = $this->getRightsAddForm();
    		if ($form->isValid($_POST)) {
    			
				$values = $form->getValues();
				$categoryies = new Categoryies();
				
				
				
				$descendants = $categoryies->getAllDescendants($values['id_category']);
				
				
				foreach ($descendants as $i) {
					$data = array(
								'id_category' => $i,
								'id_group' => $values['id_group']
									);
									
					$tableCont->insert($data);
				}
				
    		}
    		$this->_redirect('/admin/groups/add-rights-category/id/' . $values['id_group']);
    	}
    	
    	
    	$rows = $tableCont->fetchAll($tableCont->select()->where('id_group = ?', $id));
    	$avoid = array();
    	foreach ($rows as $i) {
    		$avoid[] = $i->id_category;
    	}
    	
    	
    	//rights
    	$rights = new Rights();
    	$select = $rights->select()
    					 ->where('id_group = ?', $id);
    	$rows = $rights->fetchAll($select);
    	$rightsArray = array();
		foreach ($rows as $i) {
			$rightsArray[$i->id_category] = array('id_rights' =>$i->id_rights, 
												  'rights_active' =>$i->rights_active,
												  'rights_read' =>$i->read,
												  'rights_add' =>$i->add,
												  'rights_edit' =>$i->edit,
												  'rights_del' =>$i->del,
												  );
		}
														  
		$cats = new Categoryies();

		$this->view->cats = $cats->getMenu();
    	$this->view->rights = $rightsArray;
    	
    	$form = $this->getRightsAddForm($avoid);
    	$form->populate(array('id_group' => $id));
    	$this->view->form = $form;
    	$this->view->item = $table->fetchRow($table->select()->where('id_group = ?', $id));
    	
    	
    }
    
    private function getRightsAddForm($avoid = null)
    {
    	$form = new Zend_Form();
    	$form->clearDecorators();
    				
    	$table = new Categoryies();
    	$multi = $table->getParentsForSelect(true, $avoid);
    				
    	$form->addElement(new Zend_Form_Element_Select(array(
    					'name'	=> 'id_category',
    					'multioptions'	=> $multi
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Hidden(array(
    					'name'	=> 'id_group'
    				)));
    	
    	return $form;
	}
    
}
