<?

require_once ('class.stdModule.php');

class cric0100 extends stdModule {

	function cric0100() {
		$this->stdModule('cric0100');

		$this->_settings->templates->overview		= 'overview.tpl';
		$this->_settings->templates->detail			= 'detail.tpl';
		$this->_settings->templates->sentences		= 'sentences.tpl';
		$this->_settings->templates->comments		= 'comments.tpl';
		$this->_settings->templates->comment		= 'comment.tpl';

		$this->_cache = array();
		
		//-- check I3A object
		if (isset($GLOBALS['g_obj_ti3a0365']) && is_object($GLOBALS['g_obj_ti3a0365'])) {
			$this->_ti3a0365 =& $GLOBALS['g_obj_ti3a0365'];
		} elseif (isset($GLOBALS['g_obj_i3a']) && is_object($GLOBALS['g_obj_i3a'])) {
			$this->_ti3a0365 =& $GLOBALS['g_obj_i3a'];
		} else {
			$this->_ti3a0365 = null;	
		}
		
		$this->_initializeUserGroups();

	}
	
	function setTichObject(&$tich_object) {
		$this->_tich0105 =& $tich_object;
	}
	
	function _getUserGreeting($usr_id) {
		
		if (!is_numeric($usr_id)) return false;
		if ($this->_ti3a0365) {
			if (!isset($this->_cache['usr_greeting'][$usr_id])) {
				$this->_cache['usr_greeting'][$usr_id] = $this->_ti3a0365->getUserGreeting($usr_id, false);
			}
			return $this->_cache['usr_greeting'][$usr_id];
		}
	}

	function _initializeUserGroups() {
	
		if ($this->_ti3a0365 && isset($_SESSION['session_usr_id']) && is_numeric($_SESSION['session_usr_id'])) {
			
			$mbr_info = $this->_ti3a0365->getMemberships($_SESSION['session_usr_id'], $this->_variables->public->org_id, false, true);
			$this->_variables->usr_groups = array_keys((array)$mbr_info['GROUPS']);
					
		} else {
			$this->_variables->usr_groups = array();
		}
		
	}

	function deleteRichtlijn($rtl_id) {
		if (!is_numeric($rtl_id)) return false;
		
		$sql = "DELETE FROM tbl_cric_richtlijn WHERE rtl_id = ".$rtl_id;
		return $this->_db->Execute($sql);		
	}

	function switchRichtlijn($rtl_id, $state) {
		if (!is_numeric($rtl_id)) return false;
				
		$sql = "UPDATE tbl_cric_richtlijn SET rtl_state = ".($state ? 1 : 0)." WHERE rtl_id = ".$rtl_id;
		return $this->_db->Execute($sql);
	}
	
	function generateRichtlijnId() {
		$loop = true;
		while ($loop) {
			$id = rand(100, 9999999999);

			// Check if unique
			$rs = $this->_db->Query("SELECT rtl_id FROM tbl_cric_richtlijn WHERE rtl_id=".$id);
			$loop = (!$rs->EOF());
			$rs->Close();
		}

		return $id;						
	}

	function saveRichtlijn ($rtl_data, $rtl_new=0) {
	
		if (!isset($rtl_data['rtl_id']) || !is_numeric($rtl_data['rtl_id'])) {
			$rtl_data['rtl_id'] = $this->generateRichtlijnId();
		}
	
		$fields = array();
		$fields[] = "rtl_title 			= '".mysql_escape_string(stripslashes($rtl_data['rtl_title'])) . "'";
		$fields[] = "rtl_intro			= '".mysql_escape_string(stripslashes($rtl_data['rtl_intro'])) . "'";
		$fields[] = "rtl_authorization	= ".($rtl_data['rtl_authorization'] ? 1 : 0);
		$fields[] = "rtl_changedate		= NOW()";
		
		if ($rtl_new) {
			$fields[] =	"rtl_id 			= ".$rtl_data['rtl_id'];
			$fields[] = 'rtl_createdate = NOW()';

			$sql = "INSERT INTO tbl_cric_richtlijn SET ".implode(", ", $fields);

		} else {
			$sql = "UPDATE tbl_cric_richtlijn SET  ".implode(", ", $fields)." 
					WHERE rtl_id = ".$rtl_data['rtl_id'];
		}

		$this->_db->execute($sql);
		
		return $rtl_data['rtl_id'];
	}

	function getRichtlijn ($rtl_id) {
		if (!is_numeric($rtl_id)) return false;

		$rs = $this->_db->Query("
			SELECT tbl_cric_richtlijn.*,
				count(att_id) as attachements
			FROM tbl_cric_richtlijn 
			LEFT JOIN tbl_cric_attachement ON att_rtl_id = rtl_id AND att_uri IS NOT NULL
			WHERE rtl_id = ".$rtl_id ." 
			GROUP BY rtl_id");

		$richtlijn = $rs->Row();
		$rs->Close();
		
		return $richtlijn;
	}
	
	function setSentences ($rtl_id, $content) {
		if (!is_numeric($rtl_id)) return false;
		
		//-- Delete all sentences and comments
		$this->_db->execute("DELETE FROM tbl_cric_sentence WHERE snt_rtl_id = ".$rtl_id);
		
		$content = str_replace(". ", ". #|#", $content);
		$content = str_replace("\n", "\n#|#", $content);
		$regels = explode("#|#", $content);
		
		$count = 0;
		
		foreach ($regels as $regel) {
			$sql = "INSERT INTO tbl_cric_sentence SET 
					snt_rtl_id = $rtl_id, 
					snt_number = ".++$count.",
					snt_text = '".mysql_escape_string(stripslashes($regel))."'";
			
			$this->_db->execute($sql);
		}
		
		return $count;
	}
	
	function getSentences ($rtl_id, $show_comments) {
		if (!is_numeric($rtl_id)) return false;
		
		$contents = array();
		
		$rs = $this->_db->Query("SELECT tbl_cric_sentence.* 
								". (is_numeric($_SESSION['session_usr_id']) ? ", tbl_cric_comment.cmt_id" : "") ."
								FROM tbl_cric_sentence 
								". (is_numeric($_SESSION['session_usr_id']) ? "LEFT JOIN tbl_cric_comment ON cmt_snt_id = snt_id AND cmt_usr_id = ".$_SESSION['session_usr_id'] : "") ."
								WHERE snt_rtl_id=".$rtl_id);
		
		while ($r = $rs->Row()) {

			$contents[$r['snt_id']]['snt_id'] = $r['snt_id'];
			$contents[$r['snt_id']]['text'] = $r['snt_text'];
			$contents[$r['snt_id']]['number'] = $r['snt_number'];
			$contents[$r['snt_id']]['cmt_id'] = $r['cmt_id'];

			if ($show_comments) {
				$contents[$r['snt_id']]['comments'] = array();
				$contents[$r['snt_id']]['comments'] = $this->getComments($r['snt_id']);
			}

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

		return $contents;
	}

	function getComments ($snt_id) {
		if (!is_numeric($snt_id)) return false;
		
		$comments = array();
		$rs = $this->_db->Query("
					SELECT *
					, cmt_createdate as cmt_createdate_original
					, DATE_FORMAT(cmt_createdate, '%d-%m-%Y %H:%i:%s') as cmt_createdate
					, DATE_FORMAT(cmt_changedate, '%d-%m-%Y %H:%i:%s') as cmt_changedate 
					FROM tbl_cric_comment 
					WHERE cmt_snt_id=".$snt_id." 
					ORDER BY cmt_createdate_original");
		
		while ($r = $rs->Row()) {
			$comments[$r['cmt_id']] = $r;
			$comments[$r['cmt_id']]['usr_greeting'] = $this->_getUserGreeting($r['cmt_usr_id']);
			
			$rs->moveNext();
		}
		
		return $comments;
	}
	
	function getComment($cmt_id, $snt_id=null, $usr_id=null) {
		
		if (is_numeric($cmt_id) || (is_numeric($snt_id) && is_numeric($usr_id))) {
			
			$sql = "
				SELECT * 
				FROM tbl_cric_comment 
				INNER JOIN tbl_cric_sentence ON snt_id = cmt_snt_id
				WHERE 
					".(is_numeric($cmt_id) ? "cmt_id = ".$cmt_id : "")."
					".(is_numeric($snt_id) && is_numeric($usr_id) ? ("cmt_snt_id = ".$snt_id." AND cmt_usr_id = ".$usr_id) : "");

			$rs = $this->_db->query($sql);
			if (!$rs->EOF()) {
				$comment = $rs->Row();
				$comment['usr_greeting'] = $this->_getUserGreeting($comment['cmt_usr_id']);
				$rs->Close();
				return $comment;
			}

		}
		
		return false;
		
	}
	
	function getBijlagen ($rtl_id) {
		if (!is_numeric($rtl_id)) return false;
		
		$rs = $this->_db->Query("
			SELECT *
			FROM tbl_cric_attachement
			WHERE att_rtl_id = ".$rtl_id);
		while ($r = $rs->Row()) {
			$attachment[$r['att_id']] = $r;
			$attachment[$r['att_id']]['meta'] = $this->_tcc->getResourceMetaByURI($r['att_uri']);
			$rs->moveNext();
		}
		$rs->Close();
		
		return $attachment;
	}
	
	function saveNewComment($snt_id, $comment) {

		if ( !is_numeric($snt_id) || !is_numeric($_SESSION['session_usr_id'])) return false;
	
		$usr_id = $_SESSION['session_usr_id'];
		
		if ($comment_data = $this->getComment(null, $snt_id, $usr_id)) {

			//--- comment already exists, don't create a new one
			$this->saveComment($cmt_id, $comment);
			$cmt_id = $comment_data['cmt_id'];
		
		} else {
			
			//-- insert new comment
			$sql = "INSERT INTO tbl_cric_comment SET 
					cmt_usr_id = $usr_id,
					cmt_snt_id = $snt_id,
					cmt_text = '".mysql_escape_string(stripslashes($comment))."',
					cmt_createdate = NOW(),
					cmt_changedate = NOW()";
			
			$this->_db->execute($sql);
			$cmt_id = $this->_db->lastInsertID();
		}
		
		return $cmt_id;
	}
	
	function saveComment($cmt_id, $comment) {

		if ( !is_numeric($cmt_id) || !is_numeric($_SESSION['session_usr_id'])) return false;
	
		$usr_id = $_SESSION['session_usr_id'];
		
		//-- update comment
		$sql = "UPDATE tbl_cric_comment SET 
				cmt_text = '".mysql_escape_string(stripslashes($comment))."',
				cmt_changedate = NOW()
				WHERE cmt_id = ".$cmt_id ." AND cmt_usr_id = ".$_SESSION['session_usr_id'];
		
		//-- en uitvoeren
		$this->_db->execute($sql);
		
		return $cmt_id;
		
	}
	
	//------------------------------------------------------------------------
	//--- FO functies
	//------------------------------------------------------------------------
	
	function printRichtlijn($rtl_id) {
		if (!is_numeric($rtl_id)) return false;	
		if (!$this->_isAuthorized($rtl_id)) return false;
		
		$richtlijn = $this->getRichtlijn($rtl_id);

		$this->_smrt->assign('richtlijn', $richtlijn);
		if($richtlijn['rtl_state'] != 1) return false;
		$this->_smrt->assign('attachments', $this->getBijlagen($rtl_id));
		
		// Show
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->detail);
	}

	function _isAuthorized($rtl_id) {
	
		$auth = $this->_tich0105->getAuthorizations('CRIC0100', $this->_variables->public->org_id, 'GRP', 'tbl_cric_richtlijn', $rtl_id);
		$auth_groups = array_keys((array)$auth['GRP']);
		
		if (count($auth_groups) == 0 || count(array_intersect($auth_groups, $this->_variables->usr_groups)) > 0) {
			return true;
		} else {
			return false;
		}
	}

	function printRichtlijnOverview() {
	
		//-- get alle richtlijnen hier en assign het naar de template
		$richtlijnen = array();
		
		$rs = $this->_db->Query("SELECT * FROM tbl_cric_richtlijn WHERE rtl_state = 1 ORDER BY rtl_title ASC");
		while ($r = $rs->Row()) {
			
			if ($this->_isAuthorized($r['rtl_id'])) {

				$richtlijnen[] = $r;

			}
			$rs->moveNext();
		}
		$rs->Close();
		
		$this->_smrt->assign('richtlijnen', $richtlijnen);

		// Show
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->overview);		
	}

	function printRichtlijnCommentaar($rtl_id) {
		if (!is_numeric($rtl_id)) return false;
		if (!$this->_isAuthorized($rtl_id)) return false;
		
		$richtlijn = $this->getRichtlijn($rtl_id);
		if($richtlijn['rtl_state'] != 1) return false;
		
		$sentences = $this->getSentences($rtl_id, 1);
		
		$this->_smrt->assign('richtlijn', $richtlijn);
		$this->_smrt->assign('sentences', $sentences);
		
		// Show
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->comments);
	}
	
	function printRichtlijnInhoud($rtl_id) {
		if (!is_numeric($rtl_id)) return false;	
		if (!$this->_isAuthorized($rtl_id)) return false;
		
		$richtlijn = $this->getRichtlijn($rtl_id);
		if($richtlijn['rtl_state'] != 1) return false;
		
		$sentences = $this->getSentences($rtl_id, 0);
		
		$this->_smrt->assign('richtlijn', $richtlijn);
		$this->_smrt->assign('sentences', $sentences);
		
		// Show
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->sentences);
	}
	
	function printComment($cmt_id) {
		if (!is_numeric($cmt_id)) return false;	
		
		$comment = $this->getComment($cmt_id);
		
		$this->_smrt->assign('comment', $comment);

		// Show
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->comment);
		
	}

}

?>