<?php
class Group_DeleteController extends Library_Controller {
	public function __call($methodName, $args) {
		//priprava akce
		$objectInfo = $this->_parseActionName($methodName);
		$response = new Library_Response();
		
		//pokus o nacteni skupiny
		$tableGroups = new Application_Model_UsersGroups();
		$group = $tableGroups->find($objectInfo["id"])->current();
		
		if (!$group) {
			//skupina nebyla nalezena
			$response->setStatus("GROUP_NOT_FOUND", 404);
			$this->_sendToRender($response, $objectInfo["format"]);
			return;
		}
		
		//kontrola opravneni
		if ($this->_user->id != 1) {
			//uzivatel neni root, zkontorluji se role
			$tableRoles = new Application_Model_UsersRoles();
			
			$role = $this->_user->findManyToManyRowset($tableRoles, "Application_Model_UsersHasManyUsersRoles", "user", "role", $tableRoles->select(false)->where("role_name like ?", "GROUP_MANAGER"));

			if (!$role->count()) {
				//role nebyla nalezena, uzivatel nema opravneni
				$response->setStatus("NO_PERMISIONS_TO_DELETE_GROUP", 403);
				$this->_sendToRender($response, $objectInfo["format"]);
				return;
			}
		}
		
		//vyhodnoceni nove skupiny pro pridelene dokumenty a adresare
		$newGroup = isset($_REQUEST["replaceBy"]) ? $_REQUEST["replaceBy"] : 0;
		
		//nastaveni novych hodnot
		$data = array(
			"group_id" => $newGroup
		);
		
		$where = array(
			"group_id" => $group->id
		);
		
		$tableDocuments = new Application_Model_Documents();
		$tableDirectories = new Application_Model_DocumentsDirectories();
		
		$tableDocuments->update($data, $where);
		$tableDirectories->update($data, $where);
		
		//smazani uzivatelu
		$tableAssocs = new Application_Model_UsersHasManyUsersGroups;
		$tableAssocs->delete(array("user_group_id" => $group->id));
		
		//smazani skupiny
		$group->delete();
		
		//nastavnei odpovedi
		$response->setOk();
		$this->_sendToRender($response, $objectInfo["format"]);
	}
	
	protected function _sendToRender(Library_Response $response, $format) {
		//zapsani do view
		$this->view->response = $response;
		$response->sendHeader();
		
		if ($format != "html") {
			$this->_helper->layout()->disableLayout();
		}
		
		//vyhodnoceni formatu
		switch ($format) {
			case "html":
				$this->_helper->viewRenderer("delete-html");
				break;
			
			case "json":
			
			default:
				$this->_helper->viewRenderer("delete-json");
		}
	}
}