<?php

/**
 * Description of class
 *
 * @author sasha
 */
class pagehandler_panel extends SimplePagehandler {
	
	public function process()
	{
		$this->user()->actAsSelf();
		switch ($this->getCmd()) {

			case 'dE':
				return $this->doDocumentEditor($_REQUEST['d']);
			break;

			case 'create':
				$this->createDocument();
			break;

			case 'download':
				$this->downloadAttachment();
			break;

			case 'clearCache':
				utls::clearCaches(get("cache"));
				header("Location: " . $_SERVER["HTTP_REFERER"]);
			break;

			default:
				$tpl = $this->createTemplate('wellcome.tpl.html');
				$this->display($tpl->fetch());
			break;
		}
		$this->user()->actAsCommonUser();
	}



	protected function getCmd()
	{
		$params = $this->simpleUrl->params["url"];
		if ((int)$params[0] > 0) {
			$_REQUEST['a'] = "dE";
			$_REQUEST['d'] = $params[0];
		}
		if (!empty ($_REQUEST['a'])) {
			return $_REQUEST['a'];
		} else if (!empty ($params[0])) {
			return $params[0];
		} else {
			return "";
		}
	}



	protected function createDocument()
	{
		$documentType = strtoupper($_REQUEST['dT']);
		if (empty($documentType) /* || @todo проверка на тип документа */)
			throw new Exception('wrong document type');

		$document_id = create_document($documentType);
		if ($document_id <= 0) {
			throw new Exception('create document fail');
		}

		switch ($documentType)
		{
			case 'RESTATE':
				// заполняем основные поля и переводим в статус
				$oper_type=1; // аренда
				$list_kind=1; // каталог
				$media_send = 2; // holidayapartments.ru
				$restate_type = 1041104;
				$restate_subtype = 1077815;
				$sql = sprintf("APPL_RENT_WEB.UPDATE_RESTATE_INFO('%d','%d','%d','%d', '%d', '%d')",
							$document_id, $oper_type, $list_kind,
							$media_send, $restate_type, $restate_subtype);
				ora_proc($sql);
			break;

			default:
			break;
		}

		header('Location: /panel/index.aspx?a=dE&d=' . $document_id);
	}
	
	//скачать медиа-документ
	protected function downloadAttachment() {
		$document_id = $this->simpleUrl->params["url"][1];
		if (empty($document_id) || (int)$document_id <= 0) {
			throw new NotFoundException("Nothing to load");
		}
		$sql = "select parent, dockind_id from documents_tree where document_id = $document_id";
		$control = ora_redim(ora_select($sql, "no-cache", '', ''));
		//Аттачи -- документы без типа, привязанные к карточке
		if ($control[0]["PARENT"] > 0 && empty($control[0]["DOCKIND_ID"])) {
			$sql = "SELECT COMPRESSOR.BLOB_DECOMPRESS(T.DOC_CONTENT) AS CONTENT, T.DOC_NAME AS FILENAME, T.DOC_CONTENT_TYPE AS CONTENT_TYPE FROM DOCUMENTS_TREE T WHERE T.DOCUMENT_ID = '$document_id'";
			global $conn;
			$stmt = OCIParse($conn, $sql);
			OCIExecute($stmt);
			if (OCIFetch($stmt)) {
				$file = OCIResult($stmt, 'CONTENT');
				$content = $file->load();
				$filename = OCIResult($stmt, 'FILENAME');
				header("Content-type: ");
				header("Content-Length: " . strlen($content));
				header("Content-Disposition: attachment; filename=\"$filename\"");
				print $content;
			} else {
				throw new Exception(oci_error($stmt));
			}
		} else {
			throw new NotFoundException("$document_id is not attachment");
		}
		
	}
	
	protected function doDocumentEditor($documentId)
	{
		if (empty($documentId)) {
			throw new Exception('Wrong document id');
		}

		$documentEditor = $this->init_documentEditor($documentId);
		if ($documentEditor->isSelfRequest()) {
			$documentEditor->processRequest();
		} else {
			$render = utls::get_renderer();
			$tpl = $render->createTemplate('_de.tpl');
			$tpl->assignByRef('dE', $documentEditor->fetchWidget());
			$tpl->assign("pagehandler", $this);
			$tpl->display();
		}

		//if ($_REQUEST['idE']) {
		//    $this->internal_documentEditor($documentId);
		//} else {
		//    $this->show_documentEditor($documentId);
		//}
	}


	protected function init_documentEditor($documentId)
	{
		require_once CARABI_DIR . "/classes/document_editor/CarabiEditor.php";
		if (defined("SUB_URL")) {
			$subUrl = SUB_URL;
		}
		$carabiEditor = new CarabiEditor();
		$carabiEditor->setConfig('haru_config1');
		$carabiEditor->setMainDocument((int)$documentId);
		$carabiEditor->setConfigValue('connectorUrl', $subUrl . '/panel/index.aspx');
		$carabiEditor->setConfigValue('connectorPrefix', "a=dE&d={$documentId}");

		return $carabiEditor;
	}



	public function getObjectsList()
	{
		ora_proc("APPL_RENT_WEB.SET_RENT_OWNER_LIST (1416573, 1041104, null, 1010161)");
		$sql = "select * from table(appl_rent_web.get_page_rent_list(1, 10000))";
		$res = ora_select($sql, md5($sql), '', '');
		$res = ora_redim($res);
		utls::extractSubPageInfo_bulk($res);
		return $res;
	}

	public function getRequestList()
	{
		//global $currentUser;
		//$currentUser->actAsSelf();
		$sql = "SELECT * FROM TABLE(APPL_RENT_WEB.GET_REQUEST_CLIENT_INFO())";
		$res = ora_redim(ora_select($sql, 'no-cache', '', ''));
		//print_a($res);
		return $res;
	}
	
}
?>
