<?php
class Document_TrashController extends Library_Controller {
	/**
	 * stavova promenna informujici o presmerovani z jine akce
	 * @var bool
	 */
	private $_redirected = false;
	
	public function getHtmlAction() {
		$this->_redirected = true;
		
		$this->getAction();
	}
	
	public function getJsonAction() {
		$this->_redirected = true;
		
		$this->_helper->layout()->disableLayout();
		
		$this->getAction();
	}
	
	public function refreshHtmlAction() {
		$this->_redirected = true;
		
		$this->refreshAction();
	}
	
	public function refreshJsonAction() {
		$this->_redirected = true;
		
		$this->_helper->layout()->disableLayout();
		
		$this->refreshAction();
	}
	
	public function getAction() {
		if (!$this->_redirected) {
			$this->_helper->layout()->disableLayout();
		}
		
		//nacteni informaci
		$tableTrash = new Application_Model_DocumentsUnassigned();
		$response = new Library_Response();
		
		$documents = $tableTrash->fetchAll(array("user_id" => $this->_user->id), "document_name");
		
		//nastaveni odpovedi
		$response->setOk();
		$response["documents"] = $documents;
		$response->sendHeader();
		
		$this->view->response = $response;
	}
	
	public function refreshAction() {
		if (!$this->_redirected) {
			$this->_helper->layout()->disableLayout();
		}
		
		//vytvoreni tabulek
		$tableDocuments = new Application_Model_Documents();
		$tableAssocs = new Application_Model_DocumentsDirectoriesHasManyDocuments();
		$tableTrash = new Application_Model_DocumentsUnassigned();
		
		//nalezeni vsech dokumentu, ktere jsou asociovany v adredari
		$filter = $tableDocuments->select(false)->from($tableDocuments, array("uuid"))->where("user_id = ?", $this->_user->id)->where("is_latest = ?", 1);
		$select = $tableAssocs->select(false)->from($tableAssocs, array("document_uuid"))->where("document_uuid in ?", $filter);
		
		//nacteni asociovanych dat a jejich refactoring
		$associatedData = $select->query()->fetchAll();
		$inDirectory = array();
		
		foreach ($associatedData as $document) {
			$inDirectory[] = $document["document_uuid"];
		}
		
		//nacteni dat, ktera nejsou v zadnem adredari
		$data = $filter->where("uuid not in (?)", $inDirectory)
		->columns(array("uuid", "document_name"))
		->query()
		->fetchAll();
		
		//reset tabulky trash
		$tableTrash->delete(array("user_id" => $this->_user->id));
		
		//zapis do tabulky trash
		$insertArray = array(
			"uuid" => "",
			"user_id" => $this->_user->id,
			"document_name" => "" 
		);
		
		$count = 0;
		
		foreach ($data as $document) {
			//nastavnei dat
			$insertArray["uuid"] = $document["uuid"];
			$insertArray["document_name"] = $document["document_name"];
			
			//nalezeni jmena dokumentu
			$tableTrash->insert($insertArray);
			
			$count++;
		}
		
		//zapsani odpovedi
		$response = new Library_Response();
		$response->setOk();
		$response["count"] = $count;
		$response->sendHeader();
		
		$this->view->response = $response;
	}
}