<?php
class Project_DeleteController extends Library_Controller {
	public function __call($methodName, $args) {
		//priprava operace
		$tableProjects = new Application_Model_Projects();
		$response = new Library_Response();
		$objectInfo = $this->_parseActionName($methodName);
		
		//kontorla dat
		try {
			//nacten 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("PROJECT_MANAGER", $this->_user->getRoles())) {
				//uzivatel neni opravnen samazat projekt
				$response->setStatus("NOT_PERMITED_TO_DELETE", 403);
				throw new Zend_Exception("User id " . $this->_user->id . " is not permited to delete project id " . $objectInfo["id"]);
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "delete");
			return;
		}
		
		//smazani asociovanych dat v databazi
		
		//samazani asociaci na spolupracovniky
		$tableColabours = new Application_Model_ProjectsColabours();
		$tableColabours->delete("directory_id = ". $project->id);
		
		foreach ($colabous as $user) {
			$user->delete();
		}
		
		//smazani obrazu a asociovanych dat
		$labels = $project->findDependentRowset("Application_Model_ProjectsLabels", "project");
		$tableDocuments = new Application_Model_ProjectsLabelsDocuments();
		
		foreach ($labels as $label) {
			//smazani ZIP souboru
			$content = $label->findDependentRowset("Application_Model_ProjectsLabelsContents", "label")->current();
			
			if ($content) {
				$content->delete();
			}
			
			//samazani dokumentu
			$tableDocuments->delete("label_id = " . $label->id);
			
			//samazni obrazu
			$label->delete;
		}
		
		//samazani projektu
		$project->delete();
		
		//nastaveni odpovedi
		$response->setOk();
		$this->_sendToRender($response, $objectInfo["format"], "delete");
	}
}