<?php
class Project_PostController extends Library_Controller {
	public function __call($methodName, $args) {
		//nastaveni odpovedi
		$response = new Library_Response();
		$tableProjects = new Application_Model_Projects();
		$objectInfo = $this->_parseActionName($methodName);
		
		//kontorla dat
		try {
			//kontrola odeslanych dat
			if (!isset($_REQUEST["project"])) {
				//data nebyla odeslana na server
				$response->setStatus("DATA_NOT_SENT", 400);
				throw new Zend_Exception("Data not sent to server");
			}
			
			$data = $_REQUEST["project"];
			
			if (!isset($data["project_name"], $data["description"])) {
				//data nejsou kompletni
				$response->setStatus("DATA_NOT_COMPLETE", 400);
				throw new Zend_Exception("Data sent to server is not complete");
			}
			
			$project = $tableProjects->find($objectInfo["id"])->current();
			
			if ($project) {
				//projekt je uz zalozen
				$response->setStatus("PROJECT_EXISTS", 409);
				throw new Zend_Exception("Project id " . $project->id . " is exists");
			}
			
			//kontorla majitele adresare
			$tableDirectories = new Application_Model_DocumentsDirectories();
			$directory = $tableDirectories->find($objectInfo["id"])->current();
			
			if (!$directory) {
				//adresar neexistuje
				$response->setStatus("DIRECTORY_NOT_FOUND", 404);
				throw new Zend_Exception("Directory id " . $objectInfo["id"] . " not found");
			}
			
			if ($directory->user_id != $this->_user->id && $this->_user->id != 1 && !in_array("PROJECT_MANAGER", $this->_user->getRoles())) {
				//uzivatel neni opravnen vytvorit projekt
				$response->setStatus("NOT_PERMITED", 403);
				throw new Zend_Exception("User id " . $this->_user->id . " is not permited to create project id " . $directory->id);
			}
			
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "post");
			return;
		}
		
		//odebrani potencionalne nebezpecnych dat
		unset($data["user_id"], $data["directory_id"], $data["created_at"]);
		$data["directory_id"] = $objectInfo["id"];
		$data["user_id"] = $this->_user->id;
		
		//zalozeni projektu
		$project = $tableProjects->createRow();
		$project->setFromArray($data);
		$project->save();
		
		//zapsani odpovedi
		$response->setOk();
		$response["project"] = $project;
		
		$this->_sendToRender($response, $objectInfo["format"], "post");
	}
}