<?php
class Plan_ManagerController extends Library_Controller {
	public function __call($methodName, $args) {
		//priprava dat
		$objectInfo = $this->_parseActionName($methodName);
		
		if (!isset($_REQUEST["user"])) {
			//dotaz na vypis manazeru
			$this->_list($objectInfo);
			return;
		}
		
		//tvorba objketu
		$tableProjects = new Application_Model_Projects();
		$tableManagers = new Application_Model_PlansManagers();
		$response = new Library_Response();
		
		//kontrola dat
		try {
			//kontorla odeslanych dat
			if (!isset($_REQUEST["user"])) {
				$response->setStatus("DATA_NOT_SENT", 400);
				throw new Zend_Exception("Data not sent to server");
			}
			
			//kontorla existence projektu
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if (!$project) {
				//projekt neexistuje
				$response->setStatus("PROJECT_NOT_FOUND", 404);
				throw new Zend_Exception("Project id " . $objectInfo["id"] . " not found");
			}
			
			//kontrola opravneni
			if ($project->user_id != $this->_user->id && $this->_user->id != 1 && !in_array("PLAN_MANAGER", $this->_user->getRoles())) {
				//uzivatel neni opravnen
				$response->setStatus("NOT_PERMITED", 403);
				throw new Zend_Exception("User id " . $this->_user->id . " is not permited to change plan managers of project id " . $project->directory_id);
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "put");
			return;
		}
		
		//vymazani starych zaznamu
		$tableManagers->delete("project_id = " . $project->directory_id);
		
		//nacteni skutecnych uzivatelu
		$users = $this->_tableUsers->find($_REQUEST["user"]);
		
		//zapis uzivatelu
		$insert = array(
			"project_id" => $project->directory_id
			, "user_id" => 0
		);
		
		foreach ($users as $user) {
			$insert["user_id"] = $user->id;
			$tableManagers->insert($insert);
		}
		
		//zapis odpovedi
		$response->setOk();
		$this->view->project_id = $project->directory_id;
		
		$this->_sendToRender($response, $objectInfo["format"], "put");
	}
	
	protected function _list($objectInfo) {
		//priprava dat
		$tableManagers = new Application_Model_PlansManagers();
		$response = new Library_Response();
		
		//ziskani vypisu dat
		$managers = $tableManagers->fetchAll("project_id = " . $tableManagers->getAdapter()->quote($objectInfo["id"]));
		
		//zapis do odpovedi
		$response->setOk();
		$response["user"] = $managers;
		
		$this->view->project_id = $objectInfo["id"];
		$this->_sendToRender($response, $objectInfo["format"], "list");
	}
}