<?

require_once('class.stdModule.php');

DEFINE('RBH_ERR_CODE_EXISTS',		401);

DEFINE('RBH_LIST_REPORT_PAGESIZE',	20);

DEFINE('RBH_REPORT_TYPE_OFFLINE',	'OFFLINE');
DEFINE('RBH_REPORT_TYPE_ONLINE',	'ONLINE');

DEFINE('RBH_ORG_TYPE_MAIN',		'ORG');
DEFINE('RBH_ORG_TYPE_CLIENT',	'CLT');

DEFINE('RBH_DATA_TYPE_BLOCK',	'BLOCK');
DEFINE('RBH_DATA_TYPE_ROW',		'ROW');


class crbh0100 extends stdModule {

	function crbh0100() {

		$this->stdModule('crbh0100');

		$this->_settings->assignTemplateFunction	= '$this->_assignGlobals();';


		$this->_variables->public->listreport->pagesize	= RBH_LIST_REPORT_PAGESIZE;
		
		$this->_settings->templates->list_report		= 'list_report.tpl';
		$this->_settings->templates->edit_report		= 'edit_report.tpl';
		$this->_settings->templates->beschikbaarheid	= 'beschikbaarheid.tpl';
		$this->_settings->templates->content_editor		= 'content_editor.tpl';
		
		$this->_settings->templates->content_editor_tree	= 'content_editor_tree.tpl';
		$this->_settings->templates->content_editor_block	= 'content_editor_block.tpl';
		$this->_settings->templates->report					= 'report.tpl';
		$this->_settings->templates->content_editor_row		= 'content_editor_row.tpl';
		$this->_settings->templates->error				= '';

		$this->_g_obj_ti3a0365						= &$GLOBALS['g_obj_ti3a0365'];

		$this->_post_filters						= array();
	}

	function _assignGlobals() {
		$this->_variables->template->global['image_url']			= $this->_settings->graph_url;

	}


	function fetchTemplate($filename) {
		$this->assignTemplateGlobals();
		return $this->_smrt->fetch($filename);
	}


	function getOrgs($org_type, $org_id=null) {
		
		$q = array(
				array(I3A_FLD, 'ORG_ID'), 
				array(I3A_FLD, 'ORG_NAME'),
				array(I3A_FLD, 'GATT_ORG_NUMBER'),
		);

		switch ($org_type) {
			
			case RBH_ORG_TYPE_MAIN:
				
				$q[] = array(I3A_FLD, 'ORG_DEF_CODE', "IN ('OWR','PRT')");
				$order = 'org_def_code, LOWER(org_name)';

				break;

			case RBH_ORG_TYPE_CLIENT:

				if (!is_numeric($org_id)) return false;

				$rs_def_codes = $this->_g_obj_ti3a0365->Query("
						SELECT DISTINCT(aut_com_code) FROM tbl_i3a_authorisations
						INNER JOIN tbl_i3a_org_licenses ON lic_org_id=".$org_id." AND aut_ctr_code = lic_ctr_code
						WHERE aut_mod_code = 'TI3A0365' AND LENGTH(aut_com_code) = 3");
				$def_codes = rs2arr($rs_def_codes);

				if (count($def_codes)) {
					$q[] = array(I3A_FLD, 'ORG_DEF_CODE', "IN ('".implode("', '", $def_codes)."')");
				} else {
					return false;
				}
				$order = 'LOWER(gatt_org_number), LOWER(org_name)';

				break;

		}

		$this->_g_obj_ti3a0365->searchOrganizations($orgs, $q, $order);

		return $orgs;
	
	}

	function getCountries() {
		$rs = $this->_db->Query("SELECT ctr_code, ctr_name FROM rep_country ORDER BY ctr_name");
		return rs2arr($rs, 'ctr_code');
	}

	function saveCountryConnections($rep_id, $ctr_codes) {
		if (!is_numeric($rep_id)) return false;
		$this->_db->Execute("DELETE FROM rep_country_connection WHERE ccn_rep_id = ".$rep_id);
		foreach ($ctr_codes as $ctr_code) {
			$this->_db->Execute("INSERT INTO rep_country_connection (ccn_ctr_code, ccn_rep_id) VALUES ('".mysql_escape_string($ctr_code)."',".$rep_id.")");
		}
	}

	function getCountryConnections($rep_id=null) {
		
		if (is_numeric($rep_id)) {

			$rs = $this->_db->Query("SELECT ctr_code, ctr_name FROM rep_country 
									INNER JOIN rep_country_connection ON ccn_rep_id = ".$rep_id." AND ccn_ctr_code = ctr_code 
									ORDER BY ctr_name");
			return rs2arr($rs, 'ctr_code');
		
		} else {

			$rs = $this->_db->Query("SELECT rep_id, ccn_ctr_code 
									FROM rep_report
									LEFT JOIN rep_country_connection ON ccn_rep_id = rep_id
									ORDER BY rep_id, ccn_ctr_code");
			$return = array();
			while ($r = $rs->Row()) {
				if (!$return[$r['rep_id']]) $return[$r['rep_id']] = array();
				if ($r['ccn_ctr_code']) $return[$r['rep_id']][] = $r['ccn_ctr_code'];
				$rs->MoveNext();
			}
			$rs->Close();
			return $return;

		}
	}

	function printListReport($page=1, $search_data=null) {
	
		$search_items = array();
		if (is_array($search_data)) {
			
			if (isset($search_data['rep_state'])) {
				if (in_array($search_data['rep_state'], array('0', '1'))) $search_items['rep_state'] = $search_data['rep_state'];
			}

			if (isset($search_data['rep_type'])) {
				if (in_array($search_data['rep_type'], array(RBH_REPORT_TYPE_OFFLINE, RBH_REPORT_TYPE_ONLINE))) $search_items['rep_type'] = $search_data['rep_type'];
			}

			if (isset($search_data['rep_org_id']) && is_numeric($search_data['rep_org_id']) && $search_data['rep_org_id'] > 0) {
				$search_items['rep_org_id'] = $search_data['rep_org_id'];
			}

			if (isset($search_data['rep_title']) && strlen(trim($search_data['rep_title']))) {
				$search_items['rep_title'] = trim($search_data['rep_title']);
			}

			$_SESSION['session_crbh']['list_report_search'] = $search_items;

		}

		$_r = &$_SESSION['session_crbh']['list_report_search'];

		$reports = $this->getReports($_r['rep_state'], $_r['rep_type'], $_r['rep_org_id'], $_r['rep_title']);
		$this->_smrt->assign('reports', $reports);
		$this->_smrt->assign('orgs', $this->getOrgs(RBH_ORG_TYPE_MAIN));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->list_report);
	}

	function getReports($rep_state=null, $rep_type=null, $rep_org_id=null, $rep_title=null, $page=1) {

		if (!$page || $page < 1) $page = 1;

		$wheres = array();

		if (!is_null($rep_state)) $wheres[] = 'rep_state = ' . ($rep_state ? "'1'" : "'0'");
		if (!is_null($rep_type)) $wheres[] = 'rep_type = ' . ($rep_type == RBH_REPORT_TYPE_OFFLINE ? "'OFFLINE'" : "'ONLINE'");
		if (!is_null($rep_title)) {
			$wheres[] = "rep_code LIKE '%" . mysql_escape_string($rep_title). "%'";
			$wheres[] = "rep_title LIKE '%" . mysql_escape_string($rep_title). "%'";
		}
		
		$sql = "SELECT SQL_CALC_FOUND_ROWS
					rep_id
				,	rep_code
				,	rep_title
				,	rep_state
				,	rep_type
				,	COUNT(DISTINCT bbh_org.bbh_id) as count_org
				,	COUNT(DISTINCT bbh_clt.bbh_id) as count_clt
				FROM rep_report
				LEFT JOIN rep_bbh AS bbh_clt ON bbh_clt.bbh_rep_id = rep_id AND bbh_clt.bbh_type = 'CLT'";
		
		if (!is_null($rep_org_id) && is_numeric($rep_org_id)) {
			$sql .= " INNER JOIN rep_bbh AS bbh_org ON bbh_org.bbh_rep_id = rep_id AND bbh_org.bbh_type = 'ORG' AND bbh_org.bbh_value = ". $rep_org_id;
		} else {
			$sql .= " LEFT JOIN rep_bbh AS bbh_org ON bbh_org.bbh_rep_id = rep_id AND bbh_org.bbh_type = 'ORG' ";
		}

		if ($wheres) $sql .= ' WHERE '. implode(' AND ', $wheres);

		$sql .= " GROUP BY rep_id ORDER BY rep_title";

		$offset = ($page-1) * $this->_variables->public->listreport->pagesize;
		$limit = $this->_variables->public->listreport->pagesize;
		$rs = $this->_db->Query($sql, $offset, $limit);

		// get rowcount
		$rst_cnt = $this->_db->Query("select FOUND_ROWS() as rowcount");
		$row_count = $rst_cnt->Row('rowcount');
		$rst_cnt->Close();

		return rs2arr($rs);
	}

	function getReportTitle($rep_id, $org_id, $include_code=false) {
		if (!is_numeric($rep_id) || !is_numeric($org_id)) return false;

		$unique_cache_id = ($include_code ? '1':'0') . '|' .$rep_id;
		if (!isset($this->_cache['report_title'][$unique_cache_id])) {
		
			$rs = $this->_db->Query("
							SELECT IFNULL(rpt_title, rep_title) as rep_title, rep_code 
							FROM rep_report 
							LEFT JOIN rep_reporttitle ON rpt_rep_id = rep_id AND rpt_org_id = ".$org_id."
							WHERE rep_id = ".$rep_id);
			$this->_cache['report_title'][$unique_cache_id] = ($include_code ? $rs->Row('rep_code') . ' ' : '') . $rs->Row('rep_title');
			$rs->Close();

		}

		return $this->_cache['report_title'][$unique_cache_id];
	}

	function getReportsByOrg($org_id, $clt_id=null, $rep_type=null) {
		
		$fields = array();
		$joins = array();
		$wheres = array();
		$havings = array();

		if (is_numeric($clt_id)) {
			$fields[] = "count(DISTINCT bbh_clt_all.bbh_id) connections_clt";
			$fields[] = "IF(bbh_clt.bbh_id, 1, 0) clt_connected";
			$joins[] = "LEFT JOIN rep_bbh bbh_clt_all ON bbh_clt_all.bbh_rep_id = rep_id AND bbh_clt_all.bbh_type = 'CLT'";
			$joins[] = "LEFT JOIN rep_bbh bbh_clt ON bbh_clt.bbh_rep_id = rep_id AND bbh_clt.bbh_type = 'CLT' AND bbh_clt.bbh_value = ".$clt_id;
			$havings[] = "(connections_clt = 0 OR clt_connected = 1)";
		}

		if ($rep_type) {
			$wheres[] = "rep_type = '".$rep_type."'";
		}
		
		$sql = "SELECT 
					rep_id
				,	rep_code
				,	IFNULL(rpt_title, rep_title) as rep_title
				,	count(DISTINCT bbh_org_all.bbh_id) as connections_org
				,	IF(bbh_org.bbh_id, 1, 0) as org_connected
				".($fields ? ', '. implode(' , ', $fields) : '') ."
				FROM rep_report
				LEFT JOIN rep_reporttitle ON rpt_rep_id = rep_id AND rpt_org_id = ".$org_id."
				LEFT JOIN rep_bbh bbh_org_all ON bbh_org_all.bbh_rep_id = rep_id AND bbh_org_all.bbh_type = 'ORG'
				LEFT JOIN rep_bbh bbh_org ON bbh_org.bbh_rep_id = rep_id AND bbh_org.bbh_type = 'ORG' AND bbh_org.bbh_value = ".$org_id."
				".implode(' ', $joins)."
				WHERE rep_state = '1'
				".($wheres ? ' AND '. implode(' AND ', $wheres) : '') ."
				GROUP BY rep_id
				HAVING (connections_org = 0 OR org_connected = 1) ".($havings ? ' AND '. implode(' AND ', $havings) : '') ."
				ORDER BY rep_code, rep_title";

		$rs = $this->_db->Query($sql);
		return rs2arr($rs, 'rep_id');
	}

	function getReport($rep_id) {
		if (!is_numeric($rep_id)) return false;

		if (!isset($this->_cache['report'][$rep_id])) {

			$sql = "SELECT 
						rep_id
					,	rep_code
					,	rep_title
					,	rep_state
					,	rep_type
					,	COUNT(bbh_org.bbh_id) as count_org
					,	COUNT(bbh_clt.bbh_id) as count_clt
					FROM rep_report
					LEFT JOIN rep_bbh AS bbh_org ON bbh_org.bbh_rep_id = rep_id AND bbh_org.bbh_type = 'ORG'
					LEFT JOIN rep_bbh AS bbh_clt ON bbh_clt.bbh_rep_id = rep_id AND bbh_clt.bbh_type = 'CLT'
					WHERE rep_id = ".$rep_id."
					GROUP BY rep_id";
			$rs = $this->_db->Query($sql);

			$this->_cache['report'][$rep_id] = rs2arr($rs, false, true);
		}

		return $this->_cache['report'][$rep_id];

	}

	function saveReport($data) {
	
		if (strlen(trim($data['rep_code'])) > 0) {
			$code_rep_id = $this->getReportIDByCode($data['rep_code']);
			if (is_numeric($code_rep_id) && (!is_numeric($data['rep_id']) || $code_rep_id != $data['rep_id'])) {
				$this->triggerError(RBH_ERR_CODE_EXISTS);
				return false;
			}
		}

		$rep_data = array();
		if (is_numeric($data['rep_id'])) $rep_data['rep_id']		= $data['rep_id'];
		$rep_data['rep_code']	= strlen($data['rep_code']) ? "'". strtoupper(trim($data['rep_code'])) ."'" : 'NULL';
		$rep_data['rep_title']	= "'". mysql_escape_string(trim($data['rep_title'])) ."'";

		$rep_data['rep_state']	= "'". ($data['rep_state'] ? 1 : 0) ."'";
		$rep_data['rep_type']	= "'". ($data['rep_type'] == RBH_REPORT_TYPE_OFFLINE ? 'OFFLINE' : 'ONLINE') ."'";

		$sql = generate_query('rep_report', $rep_data, 'rep_id');
		$this->_db->Execute($sql);

		$rep_id = $data['rep_id'] ? $data['rep_id'] : $this->_db->lastInsertID();

		if ($rep_id) {
			$this->saveCountryConnections($rep_id, $data['ctr_code']);
			$this->_saveReportTitles($rep_id, $data['rpt_title']);
		}

		return true;

	}

	function _saveReportTitles($rep_id, $titles) {
		if (!is_numeric($rep_id)) return false;

		$this->_db->Query("DELETE FROM rep_reporttitle WHERE rpt_rep_id = ".$rep_id);
		foreach ($titles as $org_id => $title) {
			$this->_db->Query("INSERT INTO rep_reporttitle SET
									rpt_id			= NULL
								,	rpt_rep_id		= ".$rep_id."
								,	rpt_org_id		= ".$org_id."
								,	rpt_title		= '".mysql_escape_string(trim($title))."'");
			
		}

	}

	function _getReportTitles($rep_id) {
		if (!is_numeric($rep_id)) return false;
		$rs = $this->_db->Query("SELECT * FROM rep_reporttitle WHERE rpt_rep_id = ".$rep_id);
		return rs2arr($rs, 'rpt_org_id');
	}


	function getReportIDByCode($rep_code) {
		
		$rs = $this->Query("SELECT rep_id FROM rep_report WHERE rep_code = '".mysql_escape_string($rep_code)."'");
		return rs2arr($rs, false, true);

	}

	function printEditReport($rep_id=null) {

		if (is_numeric($rep_id)) {
			$report = $this->getReport($rep_id);
			$report['titles'] = $this->_getReportTitles($rep_id);
			$report['ctr_connections'] = array_keys($this->getCountryConnections($rep_id));
			$this->_smrt->assign('report', $report);

		}

		$this->_smrt->assign('orgs', $this->getOrgs(RBH_ORG_TYPE_MAIN));

		$this->_smrt->assign('countries', $this->getCountries());

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->edit_report);

	}

	function copyReport($rep_id) {
		if (!is_numeric($rep_id)) return false;

		$this->_db->Execute("INSERT INTO rep_report (rep_id, rep_code, rep_title, rep_type, rep_state, rep_createdate, rep_changedate) 
							SELECT NULL, NULL, CONCAT(rep_title, ' (kopie)'), rep_type, '0', NOW(), NOW()
							FROM rep_report WHERE rep_id = ". $rep_id);

		$new_rep_id = $this->_db->lastInsertID();

		if ($new_rep_id) {
			
			//-- country connections
			$this->_db->Execute("INSERT INTO rep_country_connection 
							   SELECT ccn_ctr_code, ".$new_rep_id." FROM rep_country_connection WHERE ccn_rep_id = ". $rep_id);

			//-- beschikbaarheid
			$this->_db->Execute("INSERT INTO rep_bbh (bbh_id, bbh_rep_id, bbh_type, bbh_value)
							   SELECT NULL, ".$new_rep_id.", bbh_type, bbh_value FROM rep_bbh WHERE bbh_rep_id = ". $rep_id);

			//-- contents
			$content_tree = $this->getReportStructure($rep_id);
			foreach ($content_tree as $block) {
				
				//--- blocks
				$this->_db->Execute("INSERT INTO rep_reportblock (blk_id, blk_rep_id, blk_code, blk_title, blk_style, blk_newpage, blk_order, blk_createdate, blk_changedate)
									SELECT NULL, ".$new_rep_id.", blk_code, blk_title, blk_style, blk_newpage, blk_order, blk_createdate, blk_changedate FROM rep_reportblock WHERE blk_id = ". $block['blk_id']);
				$new_blk_id = $this->_db->lastInsertID();

				//--- block-atts
				$this->_db->Execute("INSERT INTO rep_att_values (val_id, val_att_code, val_blk_id, val_row_id, val_value, val_changedate, val_createdate)
									SELECT NULL, val_att_code, ".$new_blk_id.", NULL, val_value, NOW(), NOW() FROM rep_att_values WHERE val_blk_id = ". $block['blk_id']);

				foreach ($block['rows'] as $row) {
	
					//--- rows
					$this->_db->Execute("INSERT INTO rep_reportrow (row_id, row_blk_id, row_title, row_order)
										SELECT NULL, ".$new_blk_id.", row_title, row_order FROM rep_reportrow WHERE row_id = ". $row['row_id']);
					$new_row_id = $this->_db->lastInsertID();

					//--- row-atts
					$this->_db->Execute("INSERT INTO rep_att_values (val_id, val_att_code, val_blk_id, val_row_id, val_value, val_changedate, val_createdate)
										SELECT NULL, val_att_code, NULL, ".$new_row_id.", val_value, NOW(), NOW() FROM rep_att_values WHERE val_row_id = ". $row['row_id']);

					//--- columns
					$this->_db->Execute("INSERT INTO rep_reportcol (col_id, col_row_id, col_pos, col_state, col_code, col_title, col_value, col_span, col_createdate)
										SELECT NULL, ".$new_row_id.", col_pos, col_state, col_code, col_title, col_value, col_span, NOW() FROM rep_reportcol WHERE col_row_id = ". $row['row_id']);
					
				}

			}

		}

	}

	function deleteReport($rep_id) {
		if (!is_numeric($rep_id)) return false;
		
		$this->_db->Execute("DELETE FROM rep_report WHERE rep_id = ". $rep_id);
	}

	/**************************************/
	/* BESCHIKBAARHEID                    */
	/**************************************/

	function printReportBeschikbaarheid($rep_id) {
		if (!is_numeric($rep_id)) return false;

		$this->_smrt->assign('report', $this->getReport($rep_id));

		$orgs_main = $this->getOrgs(RBH_ORG_TYPE_MAIN);
		$orgs_client = array();
		foreach ($orgs_main as $org) {
			$orgs_clients[$org['ORG_ID']] = $this->getOrgs(RBH_ORG_TYPE_CLIENT, $org['ORG_ID']);
		}
		$this->_smrt->assign('orgs_main', $orgs_main);
		$this->_smrt->assign('orgs_clients', $orgs_clients);

		$this->_smrt->assign('bbh_main', $this->getBeschikbaarheid($rep_id, RBH_ORG_TYPE_MAIN));
		$this->_smrt->assign('bbh_clients', $this->getBeschikbaarheid($rep_id, RBH_ORG_TYPE_CLIENT));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->beschikbaarheid);
	}

	function saveBeschikbaarheid($rep_id, $form_data) {
		if (!is_numeric($rep_id)) return false;

		//-- reset all current settings
		$this->deleteBeschikbaarheid($rep_id);

		if (isset($form_data['org_check']) && is_array($form_data['org_check'])) {
		
			foreach ($form_data['org_check'] as $org_id => $state) {
				if (is_numeric($org_id) && $state) {
					
					$this->setBeschikbaarheid($rep_id, RBH_ORG_TYPE_MAIN, $org_id);

					if (isset($form_data['client_selected'][$org_id]) && is_array($form_data['client_selected'][$org_id])) {
						foreach ($form_data['client_selected'][$org_id] as $client_org_id) {
							if (is_numeric($client_org_id)) $this->setBeschikbaarheid($rep_id, RBH_ORG_TYPE_CLIENT, $client_org_id);
						}
					}
					
				}
			}

		}
		
		return true;
	}

	function setBeschikbaarheid($rep_id, $type, $value) {
		if (!is_numeric($rep_id) || !$type || !$value) return false;
		$this->_db->Execute("REPLACE INTO rep_bbh (bbh_rep_id, bbh_type, bbh_value) VALUES (".$rep_id.", '".$type."', '".mysql_escape_string($value)."')");
	}

	function deleteBeschikbaarheid($rep_id) {
		if (!is_numeric($rep_id)) return false;
		$this->_db->Execute("DELETE FROM rep_bbh WHERE bbh_rep_id = ". $rep_id);
	}

	function getBeschikbaarheid($rep_id, $type=null) {
		if (!is_numeric($rep_id)) return false;

		$sql = "SELECT bbh_value FROM rep_bbh WHERE bbh_rep_id = ".$rep_id;
		if ($type && in_array($type, array(RBH_ORG_TYPE_MAIN, RBH_ORG_TYPE_CLIENT))) {
			$sql .= " AND bbh_type = '".$type."'";
		}

		$rs = $this->_db->Query($sql);
		return rs2arr($rs);
	}

	/**************************************/
	/* CONTENT EDITOR                     */
	/**************************************/

	function getReportStructure($rep_id, $cols=false) {
		if (!is_numeric($rep_id)) return false;

		$structure = array();

		$atts_block = $this->_getReportAttributes(RBH_DATA_TYPE_BLOCK, $rep_id);
		$atts_row = $this->_getReportAttributes(RBH_DATA_TYPE_ROW, $rep_id);

		$rs = $this->_db->Query("SELECT * FROM rep_reportblock WHERE blk_rep_id = ". $rep_id ." ORDER BY blk_order");
		while ($block = $rs->Row()) {
			
			//$block['attributes'] = $this->_getAttributes(RBH_DATA_TYPE_BLOCK, $block['blk_id']);
			$block['attributes'] = $atts_block[$block['blk_id']];
			
			$block['rows'] = array();
			$block['blk_title'] = $this->_parseValue($block['blk_title']);

			$rs_rows = $this->_db->Query("SELECT rep_reportrow.*, SUM(col_span) total_colspan 
										FROM rep_reportrow 
										LEFT JOIN rep_reportcol ON col_row_id = row_id AND col_state='1'
										WHERE row_blk_id = ". $block['blk_id']." 
										GROUP BY row_id
										ORDER BY row_order");

			while ($row = $rs_rows->Row()) {

				//$row['attributes'] = $this->_getAttributes(RBH_DATA_TYPE_ROW, $row['row_id']);
				$row['attributes'] = $atts_row[$row['row_id']];

				if ($cols) {
					$row['cols'] =  $this->getCols($row['row_id'], true);
					$row['cols_meta'] =  $this->_getColMeta($row['cols']);
				}
				$block['rows'][] = $row;

				$rs_rows->MoveNext();
			}
			$rs_rows->Close();

			$structure[] = $block;

			$rs->MoveNext();
		}
		$rs->Close();

		return $structure;

	}

	function printReportContentEditor($rep_id) {
		if (!is_numeric($rep_id)) return false;

		$this->_smrt->assign('report', $this->getReport($rep_id));
		$this->_smrt->assign('structure', $this->getReportStructure($rep_id));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->content_editor);
	}

	function printTree($rep_id) {
		if (!is_numeric($rep_id)) return false;

		$this->_smrt->assign('report', $this->getReport($rep_id));
		$this->_smrt->assign('structure', $this->getReportStructure($rep_id));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->content_editor_tree);
	
	}

	function printReport($rep_id) {

		echo $this->getReportOutput($rep_id);
	}

	function getReportOutput($rep_id) {
		if (!is_numeric($rep_id)) return false;

		$this->_smrt->assign('graph_url', $this->getSetting('graph_url'));
		$this->_smrt->assign('report', $this->getReport($rep_id));
		$this->_smrt->assign('structure', $this->getReportStructure($rep_id, true));

		$this->assignTemplateGlobals();
		$tpl_data = $this->_smrt->fetch($this->_settings->templates->report);

		$tpl_data = $this->applyPostFilters($tpl_data);
		return $tpl_data;
	}

	function applyPostFilters($data) {
		if ($this->_post_filters) {
			
			$meta_data = array('lng_code' => $this->getVariable('language_code'));

			foreach ($this->_post_filters as $pf) {
				$data = $pf['obj']->{$pf['method']}($data, $meta_data);
			}
		}
		
		return $data;
	}

	function saveTreeOrder($rep_id, $data) {
		if (!is_numeric($rep_id)) return false;
		
		if (isset($data['block_order']) && is_array($data['block_order'])) {
			foreach ($data['block_order'] as $blk_id => $blk_order) {
				$this->setBlock(array('blk_id'=>$blk_id, 'blk_order' => $blk_order));
			}
		} elseif (isset($data['row_order']) && is_array($data['row_order'])) {
			foreach ($data['row_order'] as $blk_id => $rows) {
				foreach ($rows as $row_id => $row_order) {
					$this->setRow(array('row_id'=>$row_id, 'row_order' => $row_order));
				}
			}

		}
	}
	
	function deleteTreeItem($sort, $id) {
		
		if (!is_numeric($id)) return false;
		
		switch (strtoupper($sort)) {
		
			case RBH_DATA_TYPE_BLOCK:
				$rs = $this->_db->Execute("DELETE FROM rep_reportblock WHERE blk_id = ". $id);
			break;
			
			case RBH_DATA_TYPE_ROW:
				$tmp_row = $this->getRow($id);
				if ($tmp_row) {

					$rs = $this->_db->Execute("DELETE FROM rep_reportrow WHERE row_id = ". $id);
					$this->_resetOrder(RBH_DATA_TYPE_ROW, $tmp_row['row_blk_id']);
				}

			break;
		}
		
	}

	function _resetOrder($type, $id) {
		if (!is_numeric($id)) return false;

		switch (strtoupper($type)) {
		
			case RBH_DATA_TYPE_BLOCK:
				
				
				break;
			
			case RBH_DATA_TYPE_ROW:

				$rs = $this->_db->Query("SELECT * FROM rep_reportrow WHERE row_blk_id = ". $id." ORDER BY row_order");
				$current_order = 1;
				while ($r = $rs->Row()) {
					
					$this->setRow(array('row_id'=>$r['row_id'], 'row_order'=>$current_order));
					$current_order++;
					$rs->MoveNext();
				}
				$rs->Close();
				
				break;
		}

		
	}

	function getBlock($blk_id) {
		if (!is_numeric($blk_id)) return false;
		$rs = $this->_db->Query("SELECT * FROM rep_reportblock WHERE blk_id = ". $blk_id);
		$block = rs2arr($rs, false, true);
		$block['attributes'] = $this->_getAttributes(RBH_DATA_TYPE_BLOCK, $blk_id);

		return $block;
	}
	
	function _getAttributes($type, $id=null) {
		
		switch ($type) {
			
			case RBH_DATA_TYPE_BLOCK:

				if (is_numeric($id)) {
					$sql = "SELECT att_code, val_value
							FROM rep_attributes 
							LEFT JOIN rep_att_values ON val_att_code = att_code AND val_blk_id = ". $id."
							WHERE att_for = 'BLK'
							ORDER BY att_label";
				} else {
					$sql = "SELECT * FROM rep_attributes WHERE att_for = 'BLK' ORDER BY att_label";
							
				}

				break;

			case RBH_DATA_TYPE_ROW:
				if (is_numeric($id)) {
					$sql = "SELECT att_code, val_value
							FROM rep_attributes 
							LEFT JOIN rep_att_values ON val_att_code = att_code AND val_row_id = ". $id."
							WHERE att_for = 'ROW'
							ORDER BY att_label";
				} else {
					$sql = "SELECT * FROM rep_attributes WHERE att_for = 'ROW' ORDER BY att_label";
							
				}

				break;

		}

		if ($sql) {
			$rs = $this->_db->Query($sql);
			if (is_numeric($id)) {
				return rs2arr($rs, 'att_code');
			} else {
				return rs2arr($rs);
			}
		}
		
	}

	function _getReportAttributes($type, $rep_id) {
		if (!is_numeric($rep_id)) return false;

		switch ($type) {
			
			case RBH_DATA_TYPE_BLOCK:

				$sql = "SELECT blk_id as id, val_att_code, val_value
						FROM rep_reportblock
						INNER JOIN rep_att_values ON val_blk_id = blk_id
						WHERE blk_rep_id =". $rep_id ." AND LENGTH(val_value) > 0";

				break;

			case RBH_DATA_TYPE_ROW:

				$sql = "SELECT row_id as id, val_att_code, val_value
						FROM rep_reportrow 
						INNER JOIN rep_reportblock ON blk_id = row_blk_id
						INNER JOIN rep_att_values ON val_row_id = row_id
						WHERE blk_rep_id =". $rep_id ." AND LENGTH(val_value) > 0";

				break;
		}	

		if ($sql) {
			$atts = array();
			$rs = $this->_db->Query($sql);
			while ($r = $rs->Row()) {
				
				if (!isset($atts[$r['id']])) $atts[$r['id']] = array();
				$atts[$r['id']][$r['val_att_code']] = $r['val_value'];

				$rs->moveNext();
			}
			$rs->Close();

			return $atts;
			
		}
		
	}

	function _setAttributeValue($att_code, $type, $id, $value) {
		if ($att_code && $type && is_numeric($id)) {

			
			switch ($type) {
				case RBH_DATA_TYPE_BLOCK:
					$blk_id = $id;
					$row_id = 'NULL';
					break;

				case RBH_DATA_TYPE_ROW:
					$blk_id = 'NULL';
					$row_id = $id;
					break;
			}

			
			$this->_db->Execute("REPLACE INTO rep_att_values (val_id, val_att_code, val_blk_id, val_row_id, val_value, val_changedate, val_createdate)
							VALUES (null, '".mysql_escape_string($att_code)."', ".$blk_id.", ".$row_id.", '".mysql_escape_string($value)."', NOW(), NOW())");

		}

	}

	function _getMaxOrder($type, $id) {
		if (!is_numeric($id)) return false;

		switch ($type) {
			case RBH_DATA_TYPE_BLOCK:	$sql = "SELECT MAX(blk_order) AS max_order FROM rep_reportblock WHERE blk_rep_id = ".$id;	break;
			case RBH_DATA_TYPE_ROW:		$sql = "SELECT MAX(row_order) AS max_order FROM rep_reportrow WHERE row_blk_id = ".$id;		break;
		}

		if ($sql) {
			$rs = $this->_db->Query($sql);
			return $rs->Row('max_order');
		}
	}

	function setBlock($data) {

		if (!is_numeric($data['blk_id']) && !is_numeric($data['blk_rep_id'])) return false;

		$blk_data = array();
		if (is_numeric($data['blk_id'])) {
			$blk_data['blk_id']			= $data['blk_id'];
			$blk_data['blk_changedate']	= 'NOW()';
		} else {
			$blk_data['blk_rep_id']		= $data['blk_rep_id'];
			$blk_data['blk_createdate']	= 'NOW()';
			if (!isset($data['blk_order'])) {
				$blk_data['blk_order'] = $this->_getMaxOrder(RBH_DATA_TYPE_BLOCK, $data['blk_rep_id']) + 1;
			}
		}

		if (isset($data['blk_code']))		$blk_data['blk_code']		= "'". strtoupper(trim($data['blk_code'])) ."'";
		if (isset($data['blk_style']))		$blk_data['blk_title']		= "'". mysql_escape_string(trim($data['blk_title'])) ."'";
		if (isset($data['blk_style']))		$blk_data['blk_style']		= "'". mysql_escape_string(trim($data['blk_style'])) ."'";
		if (isset($data['blk_newpage']))	$blk_data['blk_newpage']	= "'". ($data['blk_newpage'] ? 1 : 0) ."'";
		if (isset($data['blk_order']))		$blk_data['blk_order']		= "'". intval($data['blk_order']) ."'";

		$sql = generate_query('rep_reportblock', $blk_data, 'blk_id');

		$this->_db->Execute($sql);
		if ($blk_data['blk_id']) {
			return $blk_data['blk_id'];
		} else {
			return $this->_db->lastInsertID();
		}

	}
	
	function saveBlock($blk_id, $form_data) {
		if (is_numeric($blk_id)) {
			$form_data['blk_id'] = $blk_id;
		}

		$save_blk_id = $this->setBlock($form_data);

		if ($save_blk_id) {
			
			foreach ($form_data['blk_att'] as $att_code => $value) {
				$this->_setAttributeValue($att_code, RBH_DATA_TYPE_BLOCK, $save_blk_id, $value);
			}
		}

		return $save_blk_id;

	}

	function printBlockEdit($rep_id, $blk_id=null) {
		if (!is_numeric($rep_id)) return false;
		$this->_smrt->assign('report', $this->getReport($rep_id));

		if (isset($blk_id) && is_numeric($blk_id)) {
			$this->_smrt->assign('block', $this->getBlock($blk_id));
		}

		$this->_smrt->assign('attributes', $this->_getAttributes(RBH_DATA_TYPE_BLOCK));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->content_editor_block);
	}
	
	function getCols($row_id, $parse_values=false, $return_inactive=false) {
		if (!is_numeric($row_id)) return false;
		$rs = $this->_db->Query("SELECT * FROM rep_reportcol WHERE col_row_id = ".$row_id." ".(!$return_inactive ? 'AND col_state = 1' : '') ." ORDER BY col_pos");
		
		$return = array();
		while ($r = $rs->Row()) {
			
			if ($parse_values) {
				$output_html = ($r['col_code'] == 'STRUCTUUR');
				$r['col_value_parsed'] = $this->_parseValue($r['col_value'], $output_html);
				$r['col_title_parsed'] = $this->_parseValue($r['col_title']);
			}

			$return[$r['col_pos']] = $r;	
			$rs->MoveNext();
		}
		$rs->Close();
		
		return $return;
	}

	function _getColMeta(&$col_data) {
		$meta = array();
		$meta['has_title']			= strlen(trim(array_value_implode($col_data, 'col_title'))) > 0;
		$meta['has_title_parsed']	= strlen(trim(array_value_implode($col_data, 'col_title_parsed'))) > 0;
		$meta['has_value']			= strlen(trim(array_value_implode($col_data, 'col_value'))) > 0;
		$meta['has_value_parsed']	= strlen(trim(array_value_implode($col_data, 'col_value_parsed'))) > 0;

		return $meta;
	}

	//
	// Blok rows
	//

	function setRow($data) {
	
		if (!is_numeric($data['row_id']) && !is_numeric($data['row_blk_id'])) return false;

		$row_data = array();
		if (is_numeric($data['row_id'])) {
			$row_data['row_id']			= $data['row_id'];
		} else {
			$row_data['row_blk_id']		= $data['row_blk_id'];
			if (!isset($data['row_order'])) {
				$row_data['row_order'] = $this->_getMaxOrder(RBH_DATA_TYPE_ROW, $data['row_blk_id']) + 1;
			}
		}

		if (isset($data['row_title'])) $row_data['row_title'] = "'". trim(mysql_escape_string($data['row_title'])) ."'";
		if (isset($data['row_order'])) $row_data['row_order'] = "'". intval($data['row_order']) ."'";

		$sql = generate_query('rep_reportrow', $row_data, 'row_id');

		$this->_db->Execute($sql);
		if ($row_data['row_id']) {
			return $row_data['row_id'];
		} else {
			return $this->_db->lastInsertID();
		}

	}

	function getRow($row_id) {
		if (!is_numeric($row_id)) return false;
		$rs = $this->_db->Query("SELECT * FROM rep_reportrow WHERE row_id = ". $row_id);

		$row = rs2arr($rs, false, true);
		$row['attributes'] = $this->_getAttributes(RBH_DATA_TYPE_ROW, $row_id);

		return $row;
	}

	function saveCol($form_data) {

		if (!is_numeric($form_data['blk_id'])) return false;

		$row_id = $this->setRow(array('row_id'=>$form_data['row_id'], 'row_blk_id'=>$form_data['blk_id'], 'row_title'=>$form_data['row_title']));
		
		if ($row_id) {
			foreach ($form_data['row_att'] as $att_code => $value) {
				$this->_setAttributeValue($att_code, RBH_DATA_TYPE_ROW, $row_id, $value);
			}
		}


		for ($i = 1; $i <= 4; $i++) {

			$data = array();
			if (is_numeric($form_data['col_id'][$i])) {
				$data['col_id']			= $form_data['col_id'][$i];
			} else {
				$data['col_createdate']	= 'NOW()';
			}
			
			$data['col_row_id']		= "'". intval($row_id) ."'";
			$data['col_pos']		= $i;
			$data['col_state']		= "'". intval($form_data['col_state'][$i]) ."'";
			$data['col_title']		= "'". mysql_escape_string(trim(stripslashes($form_data['col_title'][$i]))) ."'";
			$data['col_code']		= "'". mysql_escape_string(trim(stripslashes(strtoupper($form_data['col_code'][$i])))) ."'";
			$data['col_value']		= "'". mysql_escape_string(trim(stripslashes($form_data['col_value'][$i]))) ."'";
			$data['col_span']		= "'". intval($form_data['col_span'][$i]) ."'";
			
			$sql = generate_query('rep_reportcol', $data, 'col_id');
			$this->_db->Execute($sql);
			
			/*} else {
				if ($form_data['col_id'][$i]) {
					$this->deleteCol($form_data['col_id'][$i]);
				}
			}*/
		}

		return $row_id;
	
	}

	function deleteCol($col_id) {
		if (!is_numeric($col_id)) return false;
		$this->_db->Execute("DELETE FROM rep_reportcol WHERE col_id = ".$col_id);	
	}


	function printRowEdit($row_id, $blk_id) {

		if (is_numeric($blk_id)) {
			$block = $this->getBlock($blk_id);
			$this->_smrt->assign('block', $block);
			$this->_smrt->assign('report', $this->getReport($block['blk_rep_id']));
		}

		if (is_numeric($row_id)) {

			$this->_smrt->assign('row', $this->getRow($row_id));
			$this->_smrt->assign('columns', $this->getCols($row_id, false, true));
			//$this->_smrt->assign('row_id', $row_id);
		}	

		$this->_smrt->assign('attributes', $this->_getAttributes(RBH_DATA_TYPE_ROW));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->content_editor_row);

	}

	function setTemplateParserObject(&$obj) {
		$this->_template_parser =& $obj;
		$this->_template_parser->obj_crbh0100 =& $this;
	}


	function _parseValue($value, $output_html=false) {

		$new_value = $value;
		$this->_parse_field_output_html = $output_html;
		
		if ($this->_template_parser) {
			
			$new_value = preg_replace_callback('/\[(([a-z]{2,4}):([a-z0-9_]+)(|([^>]*))?)\]/i', array($this, '_parseField'), $value);
			$this->_template_parser->parseField($matches[1]);
		}

		return $new_value;
	}

	function _parseField($matches) {

		//--- quickfix to handle greedy matching
		if (substr($matches[1],-2) == ']]') {
			$ret = $this->_template_parser->parseField(substr($matches[1], 0, -2), $this->_parse_field_output_html) .']]';
		} else {
			$ret = $this->_template_parser->parseField($matches[1], $this->_parse_field_output_html);
		}

		return $ret;
	}

	function replaceGraphUrl($tpl_data, $meta_data) {
		return str_replace('[GRAPH_URL]', $this->_settings->graph_url, $tpl_data);
	}

	function replaceAmpersand($tpl_data) {
		return str_replace(' & ', ' &amp; ', $tpl_data);
	}

	function addPostFilter(&$object, $method) {
		$this->_post_filters[] = array('obj' => &$object, 'method' => $method);
	}


}

?>