<?php
class Sended_PostController extends Library_Controller {
	public function __call($methodName, $args) {
		//vytvoreni odpovedi a instance tabulky
		$response = new Library_Response();
		$tableSended = new Application_Model_MessagesSended();
		
		//nacteni objektu
		$objectInfo = $this->_parseActionName($methodName);
		
		if (empty($objectInfo["format"])) {
			$objectInfo["format"] = strtolower($objectInfo["id"]);
		}

		//kontrola uzivatele
		if ($this->_user->id == 2) {
			//uzivatel je guest, ketery nemuze posilat zpravy
			$response->setStatus("GUEST_CANT_SEND_MESSAGES", 403);
			$this->_sendToRender($response, $objectInfo["format"]);
		}
		
		//vytvoreni radku
		$row = $tableSended->createRow();
		
		//kontrola odeslanych dat
		if (isset($_REQUEST["sended"])) {
			//vychozi data byla odeslana
			$data = $_REQUEST["sended"];
			
			//smazani potencionalne nebezpecnych dat
			unset($data["sended_at"], $data["created_at"], $data["user_id"], $data["id"]);
			
			//nastaveni dat
			$row->setFromArray($data);
		}
		
		//nastaveni majitele zpravy
		$row->user_id = $this->_user->id;
		
		//konotrla jestli se ma zprava odeslat
		if (isset($_REQUEST["send"])) {
			//zprava byla oznacena k odeslani
			$this->_send($row);
		}
		
		//ulozeni zpravy
		$row->save();
		
		//zapsani dat
		$response->setOk();
		$response["sended"] = $row;
		
		$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("post-html");
				break;
			
			case "json":
			
			default:
				$this->_helper->viewRenderer("post-json");
		}
	}
	
	protected function _send($messageRow) {
		//naparsovani cilu
		$targetList = explode(" ", $messageRow->targets);
		
		//nacteni id uzivatelu
		$users = $this->_tableUsers->fetchAll($this->_tableUsers->select(false)->where("username in (?)", $targetList));
		
		//vytvoreni pole prototypu zpravy
		$data = array(
			"user_id" => 0,
			"from_user_id" => $this->_user->id,
			"subject" => $messageRow->subject,
			"content" => $messageRow->content 
		);
		
		//ukladani dat
		$tableRecieved = new Application_Model_MessagesRecieved();
		
		foreach ($users as $user) {
			$data["user_id"] = $user->id;
			
			$tableRecieved->insert($data);
		}
		
		$messageRow->sended_at = new Zend_Db_Expr("NOW()");
	}
}
?>