<?php
class Plan_PutController extends Library_Controller {
	public function __call($methodName, $args) {
		//priprava dat
		$response = new Library_Response();
		$tableTasks = new Application_Model_PlansTasks();
		$objectInfo = $this->_parseActionName($methodName);
		
		//kontrola dat
		try {
			//kontrola dat
			if (!isset($_REQUEST["task"])) {
				//data nebyla odeslana
				$response->setStatus("DATA_NOT_SENT", 400);
				throw new Zend_Exception("Data not sent to server");
			}
			
			$data = $_REQUEST["task"];
			
			if (!isset($data["status"], $data["comment"])) {
				//data nejsou kompletni
				$response->setStatus("DATA_NOT_COMPLETE", 400);
				throw new Zend_Exception("Sent data is not complete");
			}
			
			$statusList = array(
				"DONE"
				, "DELAY"
				, "INPROGRESS"
				, "NOTSTARTED"
				, "PUTOFF"
				, "NEVER"
			);
			
			$data["status"] = strtoupper($data["status"]);
			
			if (!in_array($data["status"], $statusList)) {
				//novy stav je neplatny
				$response->setStatus("INVALID_STATUS", 400);
				throw new Zend_Exception("Sent status '" . $data["status"] . " is invalid");
			}
			
			//kontorla existence ukolu
			$task = $tableTasks->find($objectInfo["id"])->current();
			
			if (!$task) {
				//ukol neexistuje
				$response->setStatus("TASK_NOT_FOUND", 404);
				throw new Zend_Exception("Task id " . $objectInfo["id"] . " not found");
			}
			
			//kontorla opravneni
			if ($task->user_id != $this->_user->id && $task->for_user_id != $this->_user->id && $this->_user->id != 1 && !in_array("PLAN_MANAGER", $this->_user->getRoles())) {
				//uzivatel neni opravnen menit
				$response->setStatus("NOT_PERMITED", 403);
				throw new Zend_Exception("User id " . $this->_user->id . " is not permited to modify task id " . $task->id);
			}
		} catch (Zend_Exception $e) {
			$this->_sendToRender($response, $objectInfo["format"], "put");
			return;
		}
		
		//update hodnot
		$task->current_status = $data["status"];
		$task->current_comment = $data["comment"];
		$taks->modified_at = new Zend_Db_Expr("NOW()");
		$task->save();
		
		//zapis historie
		$tableHistory = new Application_Model_PlansTasksHistory();
		$history = $tableHistory->createRow();
		
		$history->setFromArray(array(
			"task_id" => $task->id
			, "comment" => $data["comment"]
			, "status" => $data["status"]
		));
		
		$history->save();
		
		//zapsani odpovedi
		$this->view->task_id = $task->id;
		
		$response->setOk();
		$this->_sendToRender($response, $objectInfo["format"], "put");
	}
}