<?

define('CCRD01_KA_LIST_PER_PAGE',	25);
define('CCRD01_INC_LIST_PER_PAGE',	25);

define('CCRD01_ABO_OK'			, 200);
define('CCRD01_ABO_NOT_STARTED'	, 201);
define('CCRD01_ABO_EXPIRED'		, 202);
define('CCRD01_ABO_NO_SALDO'	, 203);
define('CCRD01_ABO_ABSENT'		, 204);

DEFINE('CCRD01_ORG_TYPE_MAIN',		'ORG');
DEFINE('CCRD01_ORG_TYPE_CLIENT',	'CLT');


require_once('class.stdModule.php');

class ccrd0100 extends stdModule {

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

		$this->_settings->templates->orderbox				= "orderbox.tpl";
		$this->_settings->templates->error					= "error.tpl";
		$this->_settings->templates->kredietrapport_email	= "kredietrapport_email.tpl";
		$this->_settings->templates->verbruiksoverzicht		= "verbruiksoverzicht.tpl";
		$this->_settings->templates->verbruiksoverzicht_csv	= "verbruiksoverzicht_csv.tpl";

		$this->_settings->templates->kredietaanvraag		= "kredietaanvraag.tpl";
		$this->_settings->templates->kredietaanvraag_xml	= "kredietaanvraag_xml.tpl";
		$this->_settings->templates->updateservice			= "updateservice.tpl";

		$this->_settings->templates->faillissement_int		= "faillissement_int.tpl";
		$this->_settings->templates->faillissement_old		= "faillissement_old.tpl";

		$this->_settings->templates->incasso_aanvraag		= "incasso_aanvraag.tpl";
		$this->_settings->templates->incasso_aanvraag_email	= "incasso_aanvraag_email.tpl";
		$this->_settings->templates->incasso_list			= "incasso_list.tpl";
		$this->_settings->templates->incasso_detail			= "incasso_detail.tpl";
		$this->_settings->templates->incasso_detail_financieel	= "incasso_detail_financieel.tpl";


		$this->_variables->public->krediet_priority			= array(1 => 'Superspoed', 2 => 'Spoed', 3 => 'Normaal');
		$this->_variables->public->languages				= array('NL' => 'Nederlands', 'EN' => 'Engels');

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

	// quick e-mail function
	function _send_email($code, $usr_id = null, $email_address = null, $variables = null, $attachment = null) {

		if (is_object($this->_tcc)) {

			$attachment = ($attachment) ? array($attachment) : null;

			$err = $this->_tcc->doCall("SEND_EMAIL", array(
					'code'		=> $code
				,	'org_id'	=> $this->_variables->public->org_id
				,	'usr_id'	=> $usr_id
				,	'lng_code'	=> $this->_variables->public->lng_code
				,	'address'	=> array('to' => $email_address)
				,	'variables'	=> $variables
				,	'attachments'=> $attachment
				,	'debug'		=> false
				), $return);

			return $return;

		} else {

			$this->_debug('_send_email::error: no tcc object available', 1);
			trigger_error('no tcc object available in _send_email', E_USER_WARNING);

		}

	}

	function showError($error_message='') {

		$this->_smrt->assign('error_message', $error_message);
		$this->_smrt->display($this->_settings->templates->error);

	}

	function _getNextSequence($seq_name) {
		$rs = $this->_db->Query("SELECT ".$seq_name.".NEXTVAL as nextval FROM dual");
		return $rs->Row('NEXTVAL');
	}


	function _getUser($usr_id, $atts=array()) {
		if (!is_numeric($usr_id)) return false;

		$GLOBALS['g_obj_ti3a0365']->getUsers(	$users
								,	array(array('USR_ID', '='.$usr_id), 'USR_INFIX','USR_ORG_ID','USR_INITIALS','USR_FAMILYNAME', 'USR_EMAIL')
								,	array('GATT_ORG_STREETNAME','GATT_ORG_STREETNUMBER','GATT_ORG_ZIPCODE','GATT_ORG_CITY','GATT_USR_ORGNAME','GATT_ORG_PHONE','GATT_ORG_KVK','GATT_USR_FUNCTION')
							);

		return current($users);

	}

	function _getUserGreeting($usr_id) {
		if (!is_numeric($usr_id)) return false;

		if (!isset($this->_cache['user_greeting'][$usr_id])) {
			$this->_cache['user_greeting'][$usr_id] = $GLOBALS['g_obj_ti3a0365']->getUserGreeting($usr_id, false);
		}

		return $this->_cache['user_greeting'][$usr_id];
	}


	function _getOrganization($org_id, $atts=array()) {
		if (!is_numeric($org_id)) return false;

		$atts = ($atts) ? $atts : array('GATT_ORG_STREETNAME','GATT_ORG_STREETNUMBER','GATT_ORG_ZIPCODE','GATT_ORG_CITY','GATT_ORG_NUMBER','GATT_ORG_PHONE','GATT_ORG_KVK','GATT_ORG_EMAIL', 'GATT_ORG_SHORTNAME','GATT_PROVISIE','GATT_PROVISIE_PERC', 'GATT_TPL_CODE');

		$GLOBALS['g_obj_ti3a0365']->getOrganizations(	$orgs
								,	array(array('ORG_ID', '='.$org_id), 'ORG_NAME')
								,	$atts
							);

		return current($orgs);

	}

	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 CCRD01_ORG_TYPE_MAIN:

				$q[] = array(I3A_FLD, 'ORG_DEF_CODE', "IN ('OWR','PRT')");
				$order = 'org_def_code, LOWER(org_name)';

				break;

			case CCRD01_ORG_TYPE_CLIENT:

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

				$rs_def_codes = $GLOBALS['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;

		}

		$GLOBALS['g_obj_ti3a0365']->searchOrganizations($orgs, $q, $order);

		return $orgs;

	}


	/****************************************************************************/
	/* KREDIETRAPPORT AANVRAGEN													*/
	/****************************************************************************/

	function setKredietAanvraag($values) {

		if (!is_numeric($_SESSION['session_usr_id'])) {
			return;
		}

		$values = array_map('stripslashes', $values);

		$new_ckre_id = $this->_getNextSequence('CCRD_KREDIET_SEQ');

		$ka_values = array();
		$ka_values['CKRE_ID']				= $new_ckre_id;
		$ka_values['CKRE_USR_ID']			= $_SESSION['session_usr_id'];
		$ka_values['CKRE_ORG_ID']			= (is_numeric($_SESSION['session_org_id']) ? $_SESSION['session_org_id'] : $this->getSetting('default_org_id'));
		$ka_values['CKRE_CSTA_ID']			= ($values['CKRE_US_FREQ']) ? 10 : 1;
		$ka_values['CKRE_REQUEST_DATE']		= 'SYSDATE';
		$ka_values['CKRE_CLOSE_DATE']		= 'NULL';
		$ka_values['CKRE_NAME']				= "'".$this->_db->db_escape_string($values['CKRE_NAME'])."'";
		$ka_values['CKRE_ADDRESS_STREET']	= "'".$this->_db->db_escape_string($values['CKRE_ADDRESS_STREET'])."'";
		$ka_values['CKRE_ADDRESS_NUMBER']	= "'".substr($this->_db->db_escape_string($values['CKRE_ADDRESS_NUMBER']),0,15)."'";
		$ka_values['CKRE_ADDRESS_ZIP']		= "'".substr($this->_db->db_escape_string($values['CKRE_ADDRESS_ZIP']),0,15)."'";
		$ka_values['CKRE_ADDRESS_CITY']		= "'".$this->_db->db_escape_string($values['CKRE_ADDRESS_CITY'])."'";
		$ka_values['CKRE_ADDRESS_PHONE']	= "'".$this->_db->db_escape_string($values['CKRE_ADDRESS_PHONE'])."'";
		$ka_values['CKRE_ADDRESS_COUNTRY']	= "'".($values['CKRE_ADDRESS_COUNTRY'] ? $this->_db->db_escape_string($values['CKRE_ADDRESS_COUNTRY']) : 'NL')."'";
		$ka_values['CKRE_BTW_NUMBER']		= "'".$this->_db->db_escape_string($values['CKRE_BTW_NUMBER'])."'";
		$ka_values['CKRE_CPRO_ID']			= (is_numeric($values['CKRE_CPRO_ID']) ? (int)$values['CKRE_CPRO_ID'] : 'NULL');
		$ka_values['CKRE_AMOUNT']			= ($values['CKRE_AMOUNT'] ? (float)str_replace(',','.',$values['CKRE_AMOUNT']) : 'NULL');
		$ka_values['CKRE_CURRENCY']			= "'".($values['CKRE_CURRENCY'] ? $values['CKRE_CURRENCY'] : 'EUR')."'";
		$ka_values['CKRE_REASON']			= "'".$this->_db->db_escape_string($values['CKRE_REASON'])."'";
		$ka_values['CKRE_REFERENCE_NAME']	= "'".$this->_db->db_escape_string($values['CKRE_REFERENCE_NAME'])."'";

		$ka_values['CKRE_US_BASE_ID']		= ($values['CKRE_US_FREQ']) ? $new_ckre_id : 'NULL';
		$ka_values['CKRE_US_FREQ']			= (is_numeric($values['CKRE_US_FREQ']) ? (int)$values['CKRE_US_FREQ'] : 'NULL');
		$ka_values['CKRE_BED_ID']			= (is_numeric($values['CKRE_BED_ID']) ? (int)$values['CKRE_BED_ID'] : 'NULL');
		$ka_values['CKRE_PARTNER_ORG_ID']	= (is_numeric($this->_variables->public->org_id) ? $this->_variables->public->org_id : 'NULL');
		$ka_values['CKRE_REP_ID']			= (is_numeric($values['CKRE_REP_ID']) ? (int)$values['CKRE_REP_ID'] : 'NULL');
		$ka_values['CKRE_PRIORITEIT']		= (is_numeric($values['CKRE_PRIORITEIT']) ? (int)$values['CKRE_PRIORITEIT'] : 'NULL');
		$ka_values['CKRE_LANGUAGE']			= "'".(array_key_exists($values['CKRE_LANGUAGE'], $this->_variables->public->languages) ? $values['CKRE_LANGUAGE'] : 'NL') . "'";

		$sql = "INSERT INTO CCRD_KREDIET (".implode(", ",array_keys($ka_values)).") VALUES (".implode(", ",array_values($ka_values)).")";

		if ($this->_db->execute($sql)) {

			$this->saveAanvraagToXML($new_ckre_id);

			if (is_numeric($values['CKRE_US_FREQ']) && $values['CKRE_US_FREQ'] > 0) {

				//--- if record is an update-service, create a child record

				//-- make changes
				$ka_values['CKRE_ID']			= $this->_getNextSequence('CCRD_KREDIET_SEQ');
				$ka_values['CKRE_CSTA_ID']		= '1';
				$ka_values['CKRE_US_BASE_ID']	= $new_ckre_id;

				$strSQL = "INSERT INTO ccrd_krediet (".implode(',',array_keys($ka_values)). ")
							VALUES (".implode(',',array_values($ka_values)). ")";

				$this->_db->execute($strSQL);

			}

			if ($_SESSION['session_org_id']) {
				$org_info = $this->_getOrganization($_SESSION['session_org_id'], array('GATT_CSA_STATUS'));
			}

			return $new_ckre_id;

		} else {
			return false;
		}

	}

	function sendKredietAanvraagMail($ckre_id, $send_to_client=false) {

		$ckre = $this->getKredietAanvraag($ckre_id);
		$applicant = $this->_getUser($ckre['CKRE_USR_ID']);

		if (is_numeric($applicant['USR_ORG_ID'])) {
			$org = $this->_getOrganization($applicant['USR_ORG_ID']);
			$applicant = array_merge($applicant, $org);
		}

		if (is_numeric($ckre['CKRE_US_BASE_ID'])) {
			if ($ckre['CKRE_US_BASE_ID'] == $ckre_id) {
				//--- base record, get the first 'child' id
				$rs_child = $this->_db->Query("SELECT CKRE_ID FROM ccrd_krediet WHERE CKRE_ID != ".$ckre_id." AND CKRE_US_BASE_ID = ".$ckre_id);
				$ckre['us_child_id'] = $rs_child->Row('CKRE_ID');
				$ckre['us_state'] = 'Basisrapport met updates';
			} else {
				$ckre['us_state'] = 'Automatische vervolgaanvraag';
			}
			$ckre['us_freq'] = $ckre['CKRE_US_FREQ'];
		}

		//--- create attachment
		$this->_smrt->assign('report_title', $GLOBALS['g_obj_crbh0100']->getReportTitle($ckre['CKRE_REP_ID'], $this->_variables->public->org_id, true));
		$this->_smrt->assign('kr', $ckre);
		$this->_smrt->assign('applicant', $applicant);
		$kr_info = $this->_smrt->fetch($this->_settings->templates->kredietrapport_email);

		$attachment = array(	'data'		=> $kr_info
							,	'filename'	=> 'kredietaanvraag_'.$ckre_id.'.txt'
							,	'mimetype'	=> 'text/plain'
							,	'inline'	=> 0);

		if ($send_to_client) {

			$this->_send_email('CKRE_CLT', $ckre['CKRE_USR_ID'], null, null, $attachment);

		}

		$this->_send_email('CKRE_PAR', null, null, null, $attachment);


	}

	function deleteKredietAanvraag($ckre_id) {
		if (!is_numeric($ckre_id)) return false;

		$sql = "DELETE FROM ccrd_krediet WHERE ckre_id = ".$ckre_id;
		$this->_db->execute($sql);

	}

	function removeDupKredietAanvraag($values) {

		if (!isset($values['CKRE_USR_ID'])) $values['CKRE_USR_ID'] = $_SESSION['session_usr_id'];
		if (!isset($values['CKRE_ORG_ID'])) $values['CKRE_ORG_ID'] = (is_numeric($_SESSION['session_org_id']) ? $_SESSION['session_org_id'] : $this->getSetting('default_org_id'));

		$sql = "SELECT ckre_id
				FROM ccrd_krediet
				WHERE ckre_usr_id = ".$values['CKRE_USR_ID']."
				AND	ckre_org_id = ".$values['CKRE_ORG_ID']."
				AND ckre_request_date > SYSDATE-1
				AND ckre_cpro_id = ".$this->getSetting('creditscore_product_id')."
				AND ckre_csta_id = 1
				AND LOWER(ckre_name) LIKE '%".strtolower($this->_db->db_escape_string(stripslashes($values['CKRE_NAME'])))."%'";

		$rs = $this->_db->query($sql);
		$dups = $rs->RowCount;
		while ($r = $rs->row()) {
			$this->deleteKredietAanvraag($r['CKRE_ID']);
			$this->deleteAanvraagToXML($r['CKRE_ID']);
			$rs->moveNext();
		}
		$rs->Close();

		return $dups;
	}

	function getKredietAanvraag($ckre_id) {
		if (!is_numeric($ckre_id)) return false;

		$sql = "SELECT
					ccrd_krediet.*
				,	TO_CHAR(ckre_request_date, 'DD-MM-YYYY') AS CKRE_REQUEST_DATE_FMT
				,	TO_CHAR(ckre_request_date, 'HH24:MI:SS') AS CKRE_REQUEST_TIME_FMT
				,	ccrd_product.*
				,	ccrd_countries.*
				,	ccrd_aanvraag_status.*
				FROM ccrd_krediet
				LEFT JOIN ccrd_product ON cpro_id = ckre_cpro_id
				LEFT JOIN ccrd_countries ON ccou_code = ckre_address_country
				LEFT JOIN ccrd_aanvraag_status ON csta_id = ckre_csta_id
				WHERE ckre_id = ".$ckre_id;
		$rs = $this->_db->query($sql);
		$ka = $rs->Row();
		$rs->Close();

		return $ka;

	}



	function getTemplatesByProduct($cpro_id) {
		if (!is_numeric($cpro_id)) return false;
		$sql = "SELECT *
				FROM ccrd_product_templates
				WHERE ctpl_cpro_id = ".$cpro_id;

		$result = array();
		$rs = $this->_db->query($sql);
		while ($r = $rs->row()) {
			$result[] = $r;
			$rs->moveNext();
		}
		$rs->Close();

		return $result;

	}

	function getProductByCode($cpro_code) {
		$rs = $this->_db->Query("SELECT * FROM ccrd_product WHERE cpro_code = '".mysql_escape_string($cpro_code)."'");
		return $rs->Row();
	}

	function _getCountryList($extended=false) {
		$rs = $this->_db->Query("SELECT ccou_code, ccou_name ".($extended ? ', ccou_cclu_id':'')." FROM ccrd_countries ORDER BY ccou_name");
		return $extended ? rs2arr($rs) : rs2arr($rs, 'CCOU_CODE');
	}

	function _getProductList($org_id=null) {

		if ($org_id && is_numeric($org_id)) {

			$wheres = array();
			if ($_SESSION['session_org_id']) {

				//--- check if organization has an own product-selection
				$rs = $this->_db->Query("SELECT cpro_id FROM ccrd_product INNER JOIN ccrd_product_org_connections ON cpoc_cpro_id = cpro_id AND cpoc_org_id = ".$_SESSION['session_org_id']." AND cpoc_org_is_client = 1");
				if ($rs->RowCount > 0) {
					$valid_pro_ids = array();
					while (!$rs->EOF()) {
						$valid_pro_ids[] = $rs->Row('CPRO_ID');
						$rs->MoveNext();
					}
					$wheres[] = ' cpro_id IN ('.implode(',',$valid_pro_ids).') ';
				}
			}

			$sql = "SELECT cpro_id, cpro_name
					FROM ccrd_product
					INNER JOIN ccrd_product_org_connections oc_org ON oc_org.cpoc_cpro_id = cpro_id AND oc_org.cpoc_org_id = ".$org_id."
					". ($wheres ? 'WHERE '.implode(' AND ', $wheres) : '') ."
					ORDER BY cpro_name";
		} else {
			$sql = "SELECT cpro_id, cpro_name FROM ccrd_product ORDER BY cpro_name";
		}

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

	}

	function _getIncassoProductList() {

		if (is_numeric($this->_variables->public->org_id)) {
			$rs = $this->_db->Query("SELECT cipr_id, cipr_name
									FROM ccrd_incasso_productcode
									WHERE cipr_org_id = ". $this->_variables->public->org_id ."
									AND cipr_visible_front = 'Y'
									ORDER BY cipr_code");
			return rs2arr($rs, 'CIPR_ID');
		}
	}

	function getIncasso($cinc_id) {
		if (!is_numeric($cinc_id)) return false;

		$sql = "SELECT ccrd_incasso.*, csta_label, ccou_name, cipr_code, cipr_name, cist_name, ciaf_name
				,	TO_CHAR(cinc_request_date, 'DD-MM-YYYY') AS cinc_request_date
				,	TO_CHAR(cinc_close_date,'DD-MM-YYYY') as cinc_close_date
				,	TO_CHAR(cinc_date_closure,'DD-MM-YYYY') as cinc_date_closure
				,	TO_CHAR(cinc_product_change_date,'DD-MM-YYYY') as cinc_product_change_date

				FROM ccrd_incasso
				INNER JOIN ccrd_countries ON ccou_code = cinc_address_country
				INNER JOIN ccrd_incasso_productcode ON cipr_id = cinc_cipr_id
				LEFT JOIN ccrd_incasso_statuscode ON cist_id = cinc_cist_id
				LEFT JOIN ccrd_aanvraag_status ON csta_id = cinc_csta_id
				LEFT JOIN ccrd_incasso_afsluitcode ON ciaf_id = cinc_ciaf_id
				WHERE cinc_id = ".$cinc_id;

		$incasso = current(rs2arr($this->_db->Query($sql)));

		$incasso['TOTAAL_INCASSEREN'] = $incasso['CINC_SUM_AMOUNT']+$incasso['CINC_INTEREST_AMOUNT']+$incasso['CINC_INCASSOCOSTS_AMT_CLIENT'];
		$incasso['SLOTTERMIJN'] = $incasso['TOTAAL_INCASSEREN'] - $incasso['CINC_PAID_AMOUNT'];

		return $incasso;
	}

	function getIncassoInvoices($cinc_id) {
		if (!is_numeric($cinc_id)) return false;

		$sql = "SELECT cinv_invoicenumber, cinv_amount, cinv_currency
				,	TO_CHAR(cinv_invoicedate,'DD-MM-YYYY') as cinv_invoicedate
				,	TO_CHAR(cinv_closedate,'DD-MM-YYYY') as cinv_closedate
                FROM ccrd_incasso_invoice
                WHERE cinv_cinc_id = ".$cinc_id;

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

	function getIncassoMessages($cinc_id) {
		if (!is_numeric($cinc_id)) return false;

		$sql = "SELECT TO_CHAR(cmsg_date,'DD-MM-YYYY') as cmsg_date, cmsg_date as cmsg_date_orig
				,	cmsg_sender_id, cmsg_sender_name
				,	cmsg_recipients
				,	cmsg_subject, cmsg_body
				,	cmsg_send
                FROM ccrd_messages
				WHERE cmsg_cinc_id = ".$cinc_id." AND cmsg_showfront = 'Y'
				ORDER BY cmsg_date_orig DESC ";
		$rs = $this->_db->Query($sql);
		$messages = array();
		while (!$rs->EOF()) {
			$messages[] = $rs->Row();
			$rs->MoveNext();
		}
		$rs->Close();
		return $messages;
	}
	
	function getIncassoPayments($cinc_id, $payment_type) {
		if (!is_numeric($cinc_id)) return false;

		switch ($payment_type) {
		
			case CCRD_PAYMENT_FROM_CD_TO_CLIENT:
				$sql = "SELECT cpay_id, cpay_amount, ccdi_uri, citp_name, ccdi_provisie_amount, ccdi_number, ccdi_id
						,	cpay_date
						,	count(cdbm_id) as dbm_count
						FROM ccrd_payment
						LEFT JOIN ccrd_cd_invoice ON ccdi_id = cpay_ccdi_id
						LEFT JOIN ccrd_incasso_type_of_payment ON citp_id = cpay_citp_id
						LEFT JOIN ccrd_disbursement ON cdbm_cinc_id = ".$cinc_id." AND cpay_ccdi_id = cdbm_ccdi_id
						WHERE cpay_cinc_id = ".$cinc_id."
						AND ccdi_id IS NOT NULL
						AND cpay_is_direct != 1
						GROUP BY cpay_id, cpay_amount, ccdi_uri, citp_name, ccdi_provisie_amount, ccdi_number, ccdi_id, cpay_date
						ORDER BY ccdi_id, cpay_date";
				break;

			case CCRD_PAYMENT_NOT_PAYED: #wel betaald aan cd, niet UITbetaald aan de klant

				$sql = "SELECT cpay_id, cpay_amount, citp_code, citp_name, cpay_is_direct
						FROM ccrd_payment
						LEFT JOIN ccrd_incasso_type_of_payment ON citp_id = cpay_citp_id
						WHERE cpay_cinc_id = ".$cinc_id." AND cpay_ccdi_id IS NULL
						ORDER BY CPAY_DATE";

				break;

			case CCRD_PAYMENT_FROM_DEBTOR_TO_CLIENT:
				
				$sql = "SELECT cpay_id, cpay_amount, ccdi_number, ccdi_uri, ccdi_id, ccdi_provisie_amount
						FROM ccrd_payment
						LEFT JOIN ccrd_incasso_type_of_payment ON citp_id = cpay_citp_id AND citp_code = '8020'
						LEFT JOIN ccrd_cd_invoice ON ccdi_id = cpay_ccdi_id
						WHERE cpay_cinc_id = ".$cinc_id." AND cpay_is_direct = 1 AND ccdi_id IS NOT NULL
						ORDER BY CPAY_DATE";

				break;
		}


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

	function _getCurrencyList() {
		$rs = $this->_db->Query("SELECT ccur_code, ccur_name
								FROM ccrd_currency
								ORDER BY ccur_code");
		return rs2arr($rs, 'CCUR_CODE');
	}

	function _getKredietAanvragen($org_id, $filters=array(), $offset=null, $limit=null) {
		if (!is_numeric($org_id)) return false;

		$where = '';
		if (count($filters) > 0) {
			$where = ' AND ' . implode(' AND ', $filters);
		}

		$sql = "SELECT
					ckre_id
				,	ckre_usr_id
				,	ckre_address_city
				,	ckre_address_street
				,	ckre_address_number
				,	ckre_address_zip
				,	ckre_address_phone
				,	ckre_btw_number
				,	csta_label
				,	TO_CHAR(ckre_request_date,'DD-MM-YYYY') AS ckre_date
				,	TO_CHAR(ckre_close_date,'DD-MM-YYYY') AS ckre_close_date
				,	ckre_name
				,	cpro_name
				,	ckre_reference_name
				,	ccou_name
				,	ckre_rep_id
				FROM ccrd_krediet
				INNER JOIN ccrd_aanvraag_status ON csta_id = ckre_csta_id
				LEFT JOIN ccrd_product ON cpro_id = ckre_cpro_id
				INNER JOIN ccrd_countries ON ccou_code = ckre_address_country
				WHERE ckre_org_id = ".$org_id."
				AND	  ((ckre_id != ckre_us_base_id) OR (ckre_us_base_id IS NULL))
				". $where."
				ORDER BY ckre_request_date DESC";

		$result = array();
		$rs = $this->_db->Query($sql, $offset, $limit);
		while ($r = $rs->Row()) {

			if (is_numeric($r['CKRE_USR_ID'])) {
				$r['USR_GREETING'] = $this->_getUserGreeting($r['CKRE_USR_ID']);
			}
			$result[] = $r;
			$rs->MoveNext();
		}
		$rs->Close();

		return $result;
	}

	function _getKredietAanvragenCount($org_id, $filters=array()) {
		if (!is_numeric($org_id)) return false;

		$where = '';
		if (count($filters) > 0) {
			$where = ' AND ' . implode(' AND ', $filters);
		}

		$sql = "SELECT COUNT(ckre_id) AS aantal
				FROM CCRD_KREDIET
				INNER JOIN ccrd_aanvraag_status ON csta_id = ckre_csta_id
				INNER JOIN ccrd_countries ON ccou_code = ckre_address_country
				WHERE ckre_org_id = ".$org_id."
				AND ((ckre_id != ckre_us_base_id) OR (ckre_us_base_id IS NULL))
				". $where;

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

		return $rs->Row('AANTAL');

	}

	function _getKredietAanvragenUpdateService($org_id, $filters=array(), $offset=0) {

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

		$where = '';
		if (count($filters) > 0) {
			$where = ' AND ' . implode(' AND ', $filters);
		}


		$sql = "SELECT
					k1.ckre_id
				,	k1.ckre_usr_id
				,	k1.ckre_address_city
				,	csta_label
				,	TO_CHAR(k1.ckre_request_date,'DD-MM-YYYY') AS ckre_date
				,	TO_CHAR(k1.ckre_close_date,'DD-MM-YYYY') AS ckre_close_date
				,	k1.ckre_name
				,	cpro_name
				,	k1.ckre_reference_name
				,	k1.ckre_us_freq
				,	TO_CHAR(MAX(k2.ckre_close_date), 'DD-MM-YYYY') as last_update
				FROM ccrd_krediet k1
				INNER JOIN ccrd_aanvraag_status ON csta_id = k1.ckre_csta_id
				LEFT JOIN ccrd_product ON cpro_id = k1.ckre_cpro_id
				LEFT JOIN ccrd_krediet k2 ON k2.ckre_us_base_id = k1.ckre_id AND k2.ckre_id != k1.ckre_id AND k2.ckre_csta_id = 11
				WHERE
					k1.ckre_org_id = ".$org_id."
				AND k1.ckre_us_base_id = k1.ckre_id
				AND k1.ckre_csta_id = 10
				". $where."
				GROUP BY k1.ckre_id, k1.ckre_usr_id, k1.ckre_address_city, csta_label, k1.ckre_request_date, k1.ckre_close_date, k1.ckre_name, cpro_name, k1.ckre_reference_name, k1.ckre_us_freq
				ORDER BY k1.ckre_request_date DESC";

		$return = array();

		$rs = $this->_db->Query($sql, $offset, CCRD01_KA_LIST_PER_PAGE);
		while ($r = $rs->Row()) {

			if ($r['LAST_UPDATE']) {
				list($d,$m,$y) = explode('-', $r['LAST_UPDATE']);
				$r['NEXT_UPDATE'] = date('d-m-Y', mktime(0,0,0,($m+(12/$r['CKRE_US_FREQ'])),$d,$y));
			} else {
				$r['LAST_UPDATE'] = 'n.v.t.';
				$r['NEXT_UPDATE'] = 'z.s.m.';
			}

			$return[] = $r;

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

	}

	function _getKredietAanvragenUpdateServiceCount($org_id, $filters=array()) {
		if (!is_numeric($org_id)) return false;

		$where = '';
		if (count($filters) > 0) {
			$where = ' AND ' . implode(' AND ', $filters);
		}

		$sql = "SELECT COUNT(ckre_id) AS aantal
				FROM ccrd_krediet k1
				WHERE
					k1.ckre_org_id = ".$org_id."
				AND k1.ckre_us_base_id = k1.ckre_id
				AND k1.ckre_csta_id = 10
				". $where."";

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

		return $rs->Row('AANTAL');

	}


	function deleteUpdateService($ckre_id) {
		if (!is_numeric($ckre_id) && is_numeric($_SESSION['session_org_id'])) return false;

		$sql = "UPDATE ccrd_krediet SET
					CKRE_CSTA_ID = 11
				,	CKRE_CLOSE_DATE = SYSDATE
				WHERE	ckre_id = ".$ckre_id ."
				AND		ckre_org_id = ".$_SESSION['session_org_id'];
		$this->_db->execute($sql);
	}


	/**********************************************************************************/
	/*	FAILLISSEMENTEN - INTERNATIONAAL	*/
	/**********************************************************************************/

	function _getFaillissementenInternationaal($filters, $extended_info = false) {

		$where = '';
		if (count($filters) > 0) {
			$where = ' AND ' . implode(' AND ', $filters);
		}

		$sql = "SELECT
					ccrd_fail_int.*
				,	ccou_name
				FROM ccrd_fail_int
				INNER JOIN ccrd_countries ON ccou_code = cfin_ccou_code
				WHERE 1=1
				".$where."
				ORDER BY cfin_week desc, cfin_year desc, cfin_naam_bedrijf";

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


		if ($extended_info) {
			$return = array();

			while ($r = $rs->Row()) {
				$rs_ext = $this->_db->Query("SELECT cfip_info FROM ccrd_fail_int_plus WHERE cfip_cfin_id = ".$r['CFIN_ID']." ORDER BY cfip_id");
				$r['extended'] = rs2arr($rs_ext);

				$return[] = $r;
				$rs->moveNext();
			}
			$rs->Close();

			return $return;

		} else {
			return rs2arr($rs);
		}
	}

	/**********************************************************************************/
	/*	FAILLISSEMENTEN - OUD	*/
	/**********************************************************************************/

	function _getFaillissementenOud($filters, $extended_info = false) {

		$where = '';
		if (count($filters) > 0) {
			$where = ' AND ' . implode(' AND ', $filters);
		}

		$sql = "SELECT *
				FROM ccrd_faillisement
				WHERE 1=1
				".$where."
				ORDER BY cfai_week desc, cfai_year desc, cfai_naam_bedrijf";

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


		if ($extended_info) {
			$return = array();

			while ($r = $rs->Row()) {
				$rs_ext = $this->_db->Query("SELECT cfaa_info FROM ccrd_faillisement_plus WHERE cfaa_cfai_id = ".$r['CFAI_ID']." ORDER BY cfaa_id");
				$r['extended'] = rs2arr($rs_ext);

				$return[] = $r;
				$rs->moveNext();
			}
			$rs->Close();

			return $return;

		} else {
			return rs2arr($rs);
		}
	}


	/*************************************************************
	*  print functions
	**************************************************************/

	function print_kr_orderbox() {

		//--- assign countries
		$this->_smrt->assign('countries', $this->_getCountryList());
		$this->_smrt->assign('country_connections', $GLOBALS['g_obj_crbh0100']->getCountryConnections());
		
		$this->_smrt->assign('krediet_priority', $this->_variables->public->krediet_priority);
		$this->_smrt->assign('languages', $this->_variables->public->languages);
		
		//$rep_reports = $GLOBALS['g_obj_crbh0100']->getReportsByOrg(1, $this->_variables->public->org_id, RBH_REPORT_TYPE_OFFLINE);

		//--- assign products
		$this->_smrt->assign('products', $this->_getProductList($this->_variables->public->org_id));
		//$this->_smrt->assign('rep_reports', $rep_reports);

		$reports = $GLOBALS['g_obj_crbh0100']->getReportsByOrg($this->_variables->public->org_id, $_SESSION['session_org_id'], RBH_REPORT_TYPE_OFFLINE);
		$this->_smrt->assign('reports', $reports);


		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->orderbox);

	}

	function csv_verbruiksoverzicht($search_data) {

		$filters = array();
		if (isset($search_data['search_name']) && strlen(trim($search_data['search_name']))) {
			$filters[] = "LOWER(ckre_name) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_name'])))."%'";
		}
		if (isset($search_data['search_city']) && strlen(trim($search_data['search_city']))) {
			$filters[] = "LOWER(ckre_address_city) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_city'])))."%'";
		}
		if (isset($search_data['search_date_from']) && preg_match('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', $search_data['search_date_from'])) {
			$filters[] = "ckre_request_date >= TO_DATE('".$search_data['search_date_from']."', 'DD-MM-YYYY')";
		}
		if (isset($search_data['search_date_till']) && preg_match('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', $search_data['search_date_till'])) {
			$filters[] = "ckre_request_date <= TO_DATE('".$search_data['search_date_till']."', 'DD-MM-YYYY')";
		}

		$ka = $this->_getKredietAanvragen($_SESSION['session_org_id'], $filters);

		foreach ($ka as $index => $k) {
			$ka[$index]['report_title'] = $GLOBALS['g_obj_crbh0100']->getReportTitle($k['CKRE_REP_ID'], $this->_variables->public->org_id, true);
		}

		//--- assign kredietaanvragen
		$this->_smrt->assign('ka', $ka);

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$csv_data = $this->_smrt->fetch($this->_settings->templates->verbruiksoverzicht_csv);

		Header("Content-type: text/csv");
		Header("Pragma: public");
		Header("Expires:0");
		Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		Header("Content-Disposition: attachment; filename=verbruiksoverzicht_".date("Ymd").".csv");
		Header("Connection: close");

		echo $csv_data;
		exit();
	}

	function print_verbruiksoverzicht($search_data) {


		$filters = array();
		if (isset($search_data['search_name']) && strlen(trim($search_data['search_name']))) {
			$filters[] = "LOWER(ckre_name) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_name'])))."%'";
		}
		if (isset($search_data['search_city']) && strlen(trim($search_data['search_city']))) {
			$filters[] = "LOWER(ckre_address_city) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_city'])))."%'";
		}
		if (isset($search_data['search_date_from']) && preg_match('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', $search_data['search_date_from'])) {
			$filters[] = "ckre_request_date >= TO_DATE('".$search_data['search_date_from']."', 'DD-MM-YYYY')";
		}
		if (isset($search_data['search_date_till']) && preg_match('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', $search_data['search_date_till'])) {
			$filters[] = "ckre_request_date <= TO_DATE('".$search_data['search_date_till']."', 'DD-MM-YYYY')";
		}

		$browse_current_page = isset($search_data['browse_current_page']) && is_numeric($search_data['browse_current_page']) && $search_data['browse_current_page'] > 0 ? $search_data['browse_current_page'] : 1;

		$total_aanvragen = $this->_getKredietAanvragenCount($_SESSION['session_org_id'], $filters);
		$browse_info = array (	'total_items'	=> $total_aanvragen
							,	'total_pages'	=> ceil($total_aanvragen/CCRD01_KA_LIST_PER_PAGE)
							,	'current_page'	=> $browse_current_page);


		$this->_smrt->assign('browse_info', $browse_info);

		$ka = $this->_getKredietAanvragen($_SESSION['session_org_id'], $filters, ($browse_current_page-1)*CCRD01_KA_LIST_PER_PAGE, CCRD01_KA_LIST_PER_PAGE);

		//--- assign kredietaanvragen
		$this->_smrt->assign('ka', $ka);

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->verbruiksoverzicht);

	}

	function printKredietAanvraag($ckre_id) {
		if (!is_numeric($ckre_id)) return false;

		//--- assign kredietaanvraag
		$this->_smrt->assign('ka', $this->getKredietAanvraag($ckre_id));


		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->kredietaanvraag);

	}

	function saveAanvraagToXML($ckre_id) {
		$xml = $this->generateKredietAanvraagXml($ckre_id);

		if (!$xml) return false;

		$path = $this->_settings->paths->xml .'kredietaanvraag/';
		$filename = $path . $ckre_id . '.xml';
		
		file_put_contents($filename, $xml);
	}

	function deleteAanvraagToXML($ckre_id) {

		$path = $this->_settings->paths->xml .'kredietaanvraag/';
		$filename = $path . $ckre_id . '.xml';
		
		if (file_exists($filename)) {
			unlink($filename);
		}
	}

	function checkCkreIdHash($ckre_id, $hash) {

		return $hash == $this->generateCkreIdHash($ckre_id);
	}

	function generateCkreIdHash($ckre_id) {
		return substr(strrev(md5($ckre_id)), 5, 8);
	}


	function generateKredietAanvraagXml($ckre_id) {
		if (!is_numeric($ckre_id)) return false;

		//--- assign kredietaanvraag
		$ka = $this->getKredietAanvraag($ckre_id);
		if (!$ka) return false;

		$ka['COUNTRY_CLUSTER_CODE'] = $this->getCountryClusterCode($ka['CKRE_ADDRESS_COUNTRY']);

		$this->_smrt->assign('ka', $ka);

		if (isset($ka['CKRE_REP_ID']) && is_numeric($ka['CKRE_REP_ID'])) {
			global $g_obj_crbh0100;
			$GLOBALS['g_obj_html']->createObject('crbh0100', 'crbh0100');
			$report = $GLOBALS['g_obj_crbh0100']->getReport($ka['CKRE_REP_ID']);
			$this->_smrt->assign('report', $report);
		}
		if (isset($ka['CKRE_ORG_ID']) && is_numeric($ka['CKRE_ORG_ID'])) {
			$this->_smrt->assign('organization', $this->_getOrganization($ka['CKRE_ORG_ID']));
			$abo = $this->getOrgAboInfo($ka['CKRE_ORG_ID']);
			$this->_smrt->assign('org_has_abo', ($abo['ABO_STATE'] == CCRD01_ABO_OK));
			
		}
		if (isset($ka['CKRE_PARTNER_ORG_ID']) && is_numeric($ka['CKRE_PARTNER_ORG_ID'])) {
			$this->_smrt->assign('partner', $this->_getOrganization($ka['CKRE_PARTNER_ORG_ID']));
		}

		if (isset($ka['CKRE_USR_ID']) && is_numeric($ka['CKRE_USR_ID'])) {
			$this->_smrt->assign('user', $this->_getUser($ka['CKRE_USR_ID']));
		}

		// Display
		return $this->_smrt->fetch($this->_settings->templates->kredietaanvraag_xml);

	}

	function printUpdateService($search_data) {

		$filters = array();

		if (isset($search_data['search_name']) && strlen(trim($search_data['search_name']))) {
			$filters[] = "LOWER(ckre_name) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_name'])))."%'";
		}
		if (isset($search_data['search_city']) && strlen(trim($search_data['search_city']))) {
			$filters[] = "LOWER(ckre_address_city) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_city'])))."%'";
		}
		if (isset($search_data['search_date_from']) && preg_match('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', $search_data['search_date_from'])) {
			$filters[] = "ckre_request_date >= TO_DATE('".$search_data['search_date_from']."', 'DD-MM-YYYY')";
		}
		if (isset($search_data['search_date_till']) && preg_match('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', $search_data['search_date_till'])) {
			$filters[] = "ckre_request_date <= TO_DATE('".$search_data['search_date_till']."', 'DD-MM-YYYY')";
		}
		if (isset($search_data['search_ref']) && strlen(trim($search_data['search_ref']))) {
			$filters[] = "LOWER(ckre_reference_name) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_ref'])))."%'";
		}

		$browse_current_page = isset($search_data['browse_current_page']) && is_numeric($search_data['browse_current_page']) && $search_data['browse_current_page'] > 0 ? $search_data['browse_current_page'] : 1;

		$total_aanvragen = $this->_getKredietAanvragenUpdateServiceCount($_SESSION['session_org_id'], $filters);
		$browse_info = array (	'total_items'	=> $total_aanvragen
							,	'total_pages'	=> ceil($total_aanvragen/CCRD01_KA_LIST_PER_PAGE)
							,	'current_page'	=> $browse_current_page);

		$this->_smrt->assign('browse_info', $browse_info);

		$ka = $this->_getKredietAanvragenUpdateService($_SESSION['session_org_id'], $filters, ($browse_current_page-1)*CCRD01_KA_LIST_PER_PAGE);

		//--- assign kredietaanvragen
		$this->_smrt->assign('ka', $ka);

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->updateservice);

	}


	/**********************************************************************************/
	/*	FAILLISSEMENTEN - INTERNATIONAAL	*/
	/**********************************************************************************/

	function printFaillissementIndexInternationaal($search_data) {

		$filters = array();

		if (isset($search_data['search_jaar']) && is_numeric($search_data['search_jaar'])) {
			$filters[] = "cfin_year = '".$this->_db->db_escape_string(strtolower(trim($search_data['search_jaar'])))."'";
		}
		if (isset($search_data['search_week']) && is_numeric($search_data['search_week'])) {
			$filters[] = "cfin_week = '".$this->_db->db_escape_string(strtolower(trim($search_data['search_week'])))."'";
		}

		if (isset($search_data['search_trefwoord']) && strlen(trim($search_data['search_trefwoord']))) {
			$filters[] = "LOWER(cfin_trefwoord) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_trefwoord'])))."%'";
		}
		if (isset($search_data['search_naam']) && strlen(trim($search_data['search_naam']))) {
			$filters[] = "LOWER(cfin_naam_bedrijf) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_naam'])))."%'";
		}
		if (isset($search_data['search_plaats']) && strlen(trim($search_data['search_plaats']))) {
			$filters[] = "LOWER(cfin_plaats_bedrijf) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_plaats'])))."%'";
		}

		if ($filters) {
			$fail_list = $this->_getFaillissementenInternationaal($filters);

			//--- assign faillissementen
			$this->_smrt->assign('fail_list', $fail_list);
		}

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->faillissement_int);
	}

	function printFaillissementInternationaal ($fail_ids) {
		if (is_numeric($fail_ids)) $fail_ids[] = $fail_ids;

		if (count($fail_ids) > 0) {

			$filters = array('cfin_id IN ('.implode(',', $fail_ids).')');

			$fail_list = $this->_getFaillissementenInternationaal($filters, true);

			//--- assign faillissementen
			$this->_smrt->assign('fail_list', $fail_list);
		}

		$this->_smrt->assign('view_mode', 'detail');


		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->faillissement_int);

	}

	/**********************************************************************************/
	/*	FAILLISSEMENTEN - OUD	*/
	/**********************************************************************************/


	function printFaillissementIndexOud($search_data) {

		$filters = array();

		if (isset($search_data['search_jaar']) && is_numeric($search_data['search_jaar'])) {
			$filters[] = "cfai_year = '".$this->_db->db_escape_string(strtolower(trim($search_data['search_jaar'])))."'";
		}
		if (isset($search_data['search_week']) && is_numeric($search_data['search_week'])) {
			$filters[] = "cfai_week = '".$this->_db->db_escape_string(strtolower(trim($search_data['search_week'])))."'";
		}
		if (isset($search_data['search_trefwoord']) && strlen(trim($search_data['search_trefwoord']))) {
			$filters[] = "LOWER(cfai_trefwoord) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_trefwoord'])))."%'";
		}
		if (isset($search_data['search_naam']) && strlen(trim($search_data['search_naam']))) {
			$filters[] = "LOWER(cfai_naam_bedrijf) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_naam'])))."%'";
		}
		if (isset($search_data['search_plaats']) && strlen(trim($search_data['search_plaats']))) {
			$filters[] = "LOWER(cfai_plaats_bedrijf) LIKE '%".$this->_db->db_escape_string(strtolower(trim($search_data['search_plaats'])))."%'";
		}

		if ($filters) {
			$fail_list = $this->_getFaillissementenOud($filters);

			//--- assign faillissementen
			$this->_smrt->assign('fail_list', $fail_list);
		}

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->faillissement_old);
	}

	function printFaillissementOud ($fail_ids) {
		if (is_numeric($fail_ids)) $fail_ids[] = $fail_ids;

		if (count($fail_ids) > 0) {

			$filters = array('cfai_id IN ('.implode(',', $fail_ids).')');

			$fail_list = $this->_getFaillissementenOud($filters, true);

			//--- assign faillissementen
			$this->_smrt->assign('fail_list', $fail_list);
		}

		$this->_smrt->assign('view_mode', 'detail');

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->faillissement_old);

	}

	function getOrgAboInfo($org_id) {
		$org_info = $this->_getOrganization($org_id, array('GATT_CSA_STATUS','GATT_CSA_START','GATT_CSA_END','GATT_CSA_AMOUNT','GATT_CSA_AMT_REQ'));

		if ($org_info['GATT_CSA_STATUS'] == 'Y') {

			$today = mktime(0,0,0,date('m'), date('d'), date('Y'));

			$org_info['ABO_STATE'] = CCRD01_ABO_OK;

			if ($org_info['GATT_CSA_START']) {
				list($d,$m,$y) = explode('-', $org_info['GATT_CSA_START']);
				$org_info['GATT_CSA_START_TS'] = mktime(0,0,0,$m,$d,$y);

				if ($org_info['GATT_CSA_START_TS'] > $today) {
					$org_info['ABO_STATE'] = CCRD01_ABO_NOT_STARTED;
				}
			}

			if ($org_info['GATT_CSA_END']) {
				list($d,$m,$y) = explode('-', $org_info['GATT_CSA_END']);
				$org_info['GATT_CSA_END_TS'] = mktime(0,0,0,$m,$d,$y);

				if ($org_info['GATT_CSA_END_TS'] < $today) {
					$org_info['ABO_STATE'] = CCRD01_ABO_EXPIRED;
				}
			}

			if ($org_info['GATT_CSA_AMT_REQ'] >= $org_info['GATT_CSA_AMOUNT']) {
				$org_info['ABO_STATE'] = CCRD01_ABO_NO_SALDO;
			}

		} else {
			$org_info['ABO_STATE'] = CCRD01_ABO_ABSENT;
		}

		return $org_info;
	}

	function getOrgMonitoring($org_id) {
		$org_info = $this->_getOrganization($org_id, array('GATT_MONITORING','GATT_MONITORING_LENGTH','GATT_MONITORING_FIELDS'));

		preg_match_all('/\[([A-Z0-9]*)\]/i', $org_info['GATT_MONITORING_FIELDS'], $matches);

		$monitoring = array(
					'org_id'		=> $org_id
				,	'monitoring'	=> explode('+',$org_info['GATT_MONITORING'])
				,	'length'		=> $org_info['GATT_MONITORING_LENGTH']
				,	'fields'		=> $matches[1]
				);

		return $monitoring;

	}

	function getCountryClusterCode($countryCode) {
		$sql = "SELECT cclu_code FROM ccrd_countries
				INNER JOIN ccrd_country_cluster ON cclu_id = ccou_cclu_id
				WHERE ccou_code = '".$this->_db->db_escape_string($countryCode)."'";

		$rs = $this->query($sql);
		return $rs->Row('CCLU_CODE');
	}

	function doKredietUpdateService() {

		$sql = "SELECT
					ckre_id
				,	TO_CHAR(ckre_request_date, 'DD-MM-YYYY') AS ckre_request_date
				,	ckre_us_freq
				FROM 	ccrd_krediet
				WHERE	ckre_us_base_id = ckre_id AND ckre_csta_id = 10";

		$rs = $this->query($sql);

		$created_reports = array();
		while ($r = $rs->Row()) {

			$sql = "SELECT
						TO_CHAR(MAX(ckre_request_date), 'DD-MM-YYYY') last_request
					,	TO_CHAR(ADD_MONTHS(MAX(ckre_request_date), (12/ckre_us_freq)), 'DD-MM-YYYY') next_request
					FROM
						ccrd_krediet
					WHERE
						ckre_id != ".$r['CKRE_ID']."
					AND ckre_us_base_id = ".$r['CKRE_ID']."
					GROUP BY ckre_us_freq
					HAVING ADD_MONTHS(MAX(ckre_request_date), (12/ckre_us_freq)) <= SYSDATE";

			$rs_sub = $this->query($sql);
			if ($rs_sub->RowCount > 0) {
				echo "Dossier: ".$r['CKRE_ID']."....\n";

				$this->createKredietUpdateAanvraag($r['CKRE_ID'], $rs_sub->Row('NEXT_REQUEST'));
			
			}

			$rs->moveNext();
		}	
	}

		function createKredietUpdateAanvraag($base_ckre_id, $date_next_request) {
			if (!is_numeric($base_ckre_id)) return;

			$krediet_base = $this->getKredietAanvraag($base_ckre_id);
			if ($krediet_base && is_numeric($krediet_base['CKRE_ID'])) {
				
				$new_ckre_id = $this->_getNextSequence('CCRD_KREDIET_SEQ');

				$sql = "
					INSERT INTO ccrd_krediet (CKRE_ID, CKRE_USR_ID, CKRE_ORG_ID, CKRE_CSTA_ID, CKRE_REQUEST_DATE,		   CKRE_NAME, CKRE_ADDRESS_STREET, CKRE_ADDRESS_NUMBER, CKRE_ADDRESS_ZIP, CKRE_ADDRESS_CITY, CKRE_ADDRESS_COUNTRY, CKRE_ADDRESS_PHONE, CKRE_BTW_NUMBER, CKRE_CPRO_ID, CKRE_AMOUNT, CKRE_ACC_AMOUNT, CKRE_CURRENCY, CKRE_REASON,										  CKRE_REFERENCE_NAME, CKRE_US_FREQ, CKRE_US_BASE_ID,		 CKRE_BED_ID, CKRE_PARTNER_ORG_ID, CKRE_REP_ID, CKRE_PRIORITEIT, CKRE_LANGUAGE)
					SELECT ".$new_ckre_id.", CKRE_USR_ID, CKRE_ORG_ID, 1, TO_DATE('".$date_next_request."', 'DD-MM-YYYY'), CKRE_NAME, CKRE_ADDRESS_STREET, CKRE_ADDRESS_NUMBER, CKRE_ADDRESS_ZIP, CKRE_ADDRESS_CITY, CKRE_ADDRESS_COUNTRY, CKRE_ADDRESS_PHONE, CKRE_BTW_NUMBER, CKRE_CPRO_ID, CKRE_AMOUNT, CKRE_ACC_AMOUNT, CKRE_CURRENCY, '".$this->_db->db_escape_string($krediet_base['CKRE_REASON'])."', CKRE_REFERENCE_NAME, CKRE_US_FREQ, " . $base_ckre_id . ",CKRE_BED_ID, CKRE_PARTNER_ORG_ID, CKRE_REP_ID, CKRE_PRIORITEIT, CKRE_LANGUAGE
						FROM ccrd_krediet
						WHERE CKRE_ID = ". $base_ckre_id;

				if ($this->_db->execute($sql)) {

					$this->saveAanvraagToXML($new_ckre_id);					

					$old_org_id = $this->_variables->public->org_id;
					$this->_variables->public->org_id = $krediet_base['CKRE_PARTNER_ORG_ID'] ? $krediet_base['CKRE_PARTNER_ORG_ID'] : 1;
					$this->sendKredietAanvraagMail($new_ckre_id);
					$this->_variables->public->org_id = $old_org_id;
				}
			}
		}

	/**********************************************************************************/
	/*	INCASSO	*/
	/**********************************************************************************/

	function _getOfficeCosts($cipr_id, $org_id) {
		if (!is_numeric($cipr_id) || !is_numeric($org_id)) return false;
		$rs = $this->_db->Query("SELECT cipr_att_code FROM ccrd_incasso_productcode WHERE cipr_id = ". $cipr_id);
		if (!$rs->EOF() && strlen(trim($rs->Row('CIPR_ATT_CODE'))) > 0) {
			$att_code = trim($rs->Row('CIPR_ATT_CODE'));

			$GLOBALS['g_obj_ti3a0365']->getOrganizations($tmp_orgs, array(array('ORG_ID', '='.$org_id)), array($att_code));
			return $tmp_orgs[0][$att_code];
		}
	}

	function _calcIncassoCosts($amount, $type, $country='NL') {

		switch ($type) {
			
			case 'PERCENTAGE':

				//--- get 1 or 2 rows, if the specific country is no availabe, fallback to the default (cici_ccou_code=NULL)
				$sql = "SELECT cici_percentage 
						FROM ccrd_incassocosts_buitenland
						WHERE cici_org_id = ".$this->_variables->public->org_id."
						AND (cici_ccou_code = '".$this->_db->db_escape_string($country)."' OR cici_ccou_code IS NULL)
						ORDER BY cici_ccou_code";
				$rs = $this->_db->Query($sql);
				
				$costs = ($amount * $rs->Row('CICI_PERCENTAGE')) / 100;

				break;

			case 'STAFFEL':

				$sql = "SELECT CCIC_INCBTW FROM ccrd_incassocosts
						WHERE ccic_org_id = ".$this->_variables->public->org_id." 
						AND (ccic_lower < ".(float)$amount." OR ccic_lower IS NULL)
						AND (".(float)$amount." <= ccic_upper OR ccic_upper IS NULL)
						AND cicc_currency = 'EUR'";
				$rs = $this->_db->Query($sql);
				$costs = $rs->Row('CCIC_INCBTW');

				break;
		}

		return $costs;
	}

	function getIncassoTypeOfCostByCode($code) {
		$rs = $this->_db->Query("SELECT * FROM ccrd_incasso_type_of_costs WHERE citc_code = '".$this->_db->db_escape_string($code)."' AND citc_org_id = ".$this->_variables->public->org_id);
		$toc = $rs->Row();
		$rs->Close();
		return $toc;
	}

	function setIncassoCost($cinc_id, $amount, $btw_perc, $citc_id) {
		if (!is_numeric($cinc_id)) return false;
		if (!is_numeric($amount)) return false;
		if (!is_numeric($btw_perc)) return false;
		if (!is_numeric($citc_id)) return false;

		$btw = $amount * ($btw_perc/100);
		$amount_total = $amount + $btw;

		$cico_values = array();
		$cico_values['CICO_ID']				= 'CCRD_INCASSO_COSTS_SEQ.NEXTVAL';
		$cico_values['CICO_CINC_ID']		= $cinc_id;
		$cico_values['CICO_AMOUNT']			= $amount;
		$cico_values['CICO_CURRENCY']		= "'EUR'";
		$cico_values['CICO_BTW_PERC']		= $btw_perc;
		$cico_values['CICO_AMOUNT_BTW']		= $btw;
		$cico_values['CICO_AMOUNT_TOTAL']	= $amount_total;
		$cico_values['CICO_DATE']			= 'SYSDATE';
		$cico_values['CICO_CITC_ID']		= $citc_id;
		$cico_values['CICO_CCDI_ID']		= 'NULL';

		$sql = "INSERT INTO ccrd_incasso_costs (".implode(", ",array_keys($cico_values)).") VALUES (".implode(", ",array_values($cico_values)).")";

		$this->_db->Execute($sql);
	}

	function getIncassoCosts($cinc_id) {
		if (!is_numeric($cinc_id)) return false;

		$sql = "SELECT *
				FROM ccrd_incasso_costs
				LEFT JOIN ccrd_incasso_type_of_costs ON citc_id = cico_citc_id
				LEFT JOIN ccrd_cd_invoice ON ccdi_id = cico_ccdi_id
				WHERE cico_cinc_id = ".$cinc_id."
				ORDER BY cico_date";
		return rs2arr($this->_db->Query($sql));
	}

	function saveIncasso($values) {

		$new_cinc_id = $this->_getNextSequence('CCRD_INCASSO_SEQ');

		/*		

		$rCost = $db->fetchRow($strSQL, '', false, true);
		$incassoCosts = $rCost["CCIC_INCBTW"];
		$incassoCostsClient = $incassoCosts;

		if (is_numeric($vars["fv1OrgId"])) {

			$org_info = $g_obj_i3a->getOrgInfo($null, $vars["fv1OrgId"], array('GATT_PROVISIE','GATT_PROVISIE_PERC'));
			$org_info['GATT_PROVISIE_PERC'] = str_replace(',','.', $org_info['GATT_PROVISIE_PERC']);

			if ($org_info['GATT_PROVISIE'] == 'PERCENTAGE' && is_numeric($org_info['GATT_PROVISIE_PERC'])) {
				$incassoCostsClient = $SumOfInvoices * ($org_info['GATT_PROVISIE_PERC']/100);
			}

		}

		$totalIncasso = $SumOfInvoices + $incassoCosts + $vars["fv2Rente_A"];
		*/
		$invoices_sum = 0;
		$invoices_count = 0;
		for ($i = 0; $i < 10; $i++) {
			if (strlen(trim($values["fvINr"][$i])) > 0) {
				$invoices_sum += str_replace(',','.',$values['fvIAm'][$i]);
				$invoices_count++;
			}
		}

		$incasso_costs = $this->_calcIncassoCosts($invoices_sum, 'STAFFEL', $values['fvCountry']);
		$incasso_costs_client = $incasso_costs;
		
		if (is_numeric($_SESSION['session_org_id'])) {

			$org = $this->_getOrganization($_SESSION['session_org_id']);
			$org['GATT_PROVISIE_PERC'] = str_replace(',','.', $org['GATT_PROVISIE_PERC']);

			if ($org['GATT_PROVISIE'] == 'PERCENTAGE' && is_numeric($org['GATT_PROVISIE_PERC'])) {
				$incasso_costs_client = $invoices_sum * ($org['GATT_PROVISIE_PERC']/100);
			}
		}
		$total_amount = $invoices_sum + $incasso_costs;

		$inc_values = array();
		$inc_values['CINC_ID']					= $new_cinc_id;
		$inc_values['CINC_CSTA_ID']				= '1';
		$inc_values['CINC_USR_ID']				= $_SESSION['session_usr_id'];
		$inc_values['CINC_ORG_ID']				= $_SESSION['session_org_id'] ? $_SESSION['session_org_id'] : 'NULL';
		$inc_values['CINC_PARTNER_ORG_ID']		= $this->_variables->public->org_id ? $this->_variables->public->org_id : 'NULL';

		$inc_values['CINC_REQUEST_DATE']		= 'SYSDATE';
		$inc_values['CINC_CLOSE_DATE']			= 'NULL';
		$inc_values['CINC_NAME']				= "'".$this->_db->db_escape_string($values['fvName'])."'";
		$inc_values['CINC_ADDRESS_STREET']		= "'".$this->_db->db_escape_string($values['fvStreet'])."'";
		$inc_values['CINC_ADDRESS_NUMBER']		= "'".substr($this->_db->db_escape_string($values['fvNumber']),0,15)."'";
		$inc_values['CINC_ADDRESS_ZIP']			= "'".$this->_db->db_escape_string($values['fvZip'])."'";
		$inc_values['CINC_ADDRESS_CITY']		= "'".$this->_db->db_escape_string($values['fvCity'])."'";
		$inc_values['CINC_ADDRESS_COUNTRY']		= "'".$this->_db->db_escape_string($values['fvCountry'])."'";
		$inc_values['CINC_ADDRESS_PHONE']		= "'".$this->_db->db_escape_string($values['fvPhone'])."'";
		$inc_values['CINC_REFERENCE_NAME']		= "'".$this->_db->db_escape_string($values['fvContact'])."'";
		$inc_values['CINC_REFERENCE_CODE']		= "'".$this->_db->db_escape_string($values['fvReference'])."'";
		$inc_values['CINC_BED_ID']				= (is_numeric($values['fvBedId']) ? (int)$values['fvBedId'] : 'NULL');
		$inc_values['CINC_CIPR_ID']				= (is_numeric($values['fvProduct']) ? (int)$values['fvProduct'] : 'NULL');
		$inc_values['CINC_PRODUCT_CHANGE_DATE']	= 'SYSDATE';
		$office_costs = $this->_getOfficeCosts($values['fvProduct'], $_SESSION['session_org_id']);
		$inc_values['CINC_OFFICECOSTS']			= $office_costs ? $office_costs : 0;

		$inc_values["CINC_NUMBEROFINVOICES"]		= $invoices_count ? $invoices_count : 'NULL';
		$inc_values["CINC_SUM_AMOUNT"]				= $invoices_sum ? $invoices_sum : 'NULL';
		$inc_values["CINC_INCASSOCOSTS_AMOUNT"]		= $incasso_costs ? $incasso_costs : 'NULL';
		$inc_values["CINC_INCASSOCOSTS_AMT_CLIENT"]	= $incasso_costs_client ? $incasso_costs_client : 'NULL';
		$inc_values["CINC_TOTAL_AMOUNT"]			= $total_amount ? $total_amount : 'NULL';
		$inc_values["CINC_TOTAL_OPEN_AMOUNT"]		= $total_amount ? $total_amount : '0';

		$sql = "INSERT INTO CCRD_INCASSO (".implode(", ",array_keys($inc_values)).") VALUES (".implode(", ",array_values($inc_values)).")";

		$this->_db->Execute($sql);


		if (is_numeric($inc_values["CINC_CIPR_ID"])) {

			//-- 9090
			if ($inc_values["CINC_OFFICECOSTS"]) {
	
				//-- add office-costs as entry in costs-table
				if ($this->_tcc->getSettings('CCRD0100', 'INC_ADDCOSTS')) {
					
					$type_of_cost = $GLOBALS['g_obj_ccrd0100']->getIncassoTypeOfCostByCode('9090');
					if ($type_of_cost && $type_of_cost['CITC_ID']) {
						$this->setIncassoCost($new_cinc_id, $inc_values["CINC_OFFICECOSTS"], 19, $type_of_cost['CITC_ID']);
					}
				}
			}
		}

		for ($i = 0; $i < 10; $i++) {
			if (strlen(trim($values["fvINr"][$i])) > 0) {

				$inv_values = array();
				$inv_values['CINV_ID']				= 'CCRD_INCASSO_INVOICE_SEQ.nextval';
				$inv_values['CINV_CINC_ID']			= $new_cinc_id;
				$inv_values['CINV_INVOICENUMBER']	= "'".$this->_db->db_escape_string($values['fvINr'][$i])."'";
				$inv_values['CINV_INVOICEDATE']		= "TO_DATE('".$values['fvIDt'][$i]."','DD-MM-YYYY')";
				$inv_values['CINV_CLOSEDATE']		= "TO_DATE('".$values['fvIEDt'][$i]."','DD-MM-YYYY')";

				$amount = str_replace(',','.',$values['fvIAm'][$i]);
				$inv_values['CINV_AMOUNT']			= (is_numeric($amount) ? $amount : 'NULL');
				$inv_values['CINV_CURRENCY']		=  "'".$this->_db->db_escape_string($values['fvICu'][$i])."'";;

				$sql = "INSERT INTO CCRD_INCASSO_INVOICE (".implode(", ",array_keys($inv_values)).") VALUES (".implode(", ",array_values($inv_values)).")";

				$this->_db->Execute($sql);
			}
		}

		//-- update user-att GATT_EMAIL_ONTVANGEN
		$user_values = array('usr_id' => $_SESSION['session_usr_id'], 'GATT_EMAIL_ONTVANGEN' => ($values["fvReceiveMail"] ? 'Y' : 'N'));
		$GLOBALS['g_obj_ti3a0365']->saveUser($user_values, false, false);

		return $new_cinc_id;

	}

	function sendIncassoAanvraagMail($cinc_id, $send_to_client=false, $send_to_partner=true) {
		if (!is_numeric($cinc_id)) return false;

		$cinc = $this->getIncasso($cinc_id);
		$applicant = $this->_getUser($cinc['CINC_USR_ID']);

		if (is_numeric($applicant['USR_ORG_ID'])) {
			$org = $this->_getOrganization($applicant['USR_ORG_ID']);
			$applicant = array_merge($applicant, $org);
		}


		//--- create attachment
		$this->_smrt->assign('incasso', $cinc);
		$this->_smrt->assign('applicant', $applicant);
		$incasso_info = $this->_smrt->fetch($this->_settings->templates->incasso_aanvraag_email);

		$attachment = array(	'data'		=> $incasso_info
							,	'filename'	=> 'incassoaanvraag_'.$cinc_id.'.csv'
							,	'mimetype'	=> 'text/csv'
							,	'inline'	=> 0);

		if ($send_to_client) $this->_send_email('CINC_CLT', $cinc['CINC_USR_ID'], null, null, $attachment);
		if ($send_to_partner) $this->_send_email('CINC_PAR', null, null, null, $attachment);
	}

	function printIncassoAanvraag($form_data) {

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

		//--- assign products
		$this->_smrt->assign('products', $this->_getIncassoProductList());
		$this->_smrt->assign('currencies', $this->_getCurrencyList());

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->incasso_aanvraag);

	}

	function _getIncassoList($org_id, $filters=array(), $offset=0, $result_count=false) {
		if (!is_numeric($org_id)) return false;

		$where_list = array();
		if (isset($filters['DATE_FROM'])) {
			$where_list[] = "cinc_request_date > TO_DATE('".$this->_db->db_escape_string($filters['DATE_FROM'])."','DD-MM-YYYY')";
		}
		if (isset($filters['DATE_TO'])) {
			$where_list[] = "cinc_request_date < TO_DATE('".$this->_db->db_escape_string($filters['DATE_TO'])."','DD-MM-YYYY')";
		}
		if (isset($filters['CINC_NAME'])) {
			$where_list[] = "UPPER(cinc_name) LIKE '%".strtoupper($this->_db->db_escape_string($filters['CINC_NAME']))."%'";
		}
		if (isset($filters['CINC_ADDRESS_CITY'])) {
			$where_list[] = "UPPER(cinc_address_city) LIKE '%".strtoupper($this->_db->db_escape_string($filters['CINC_ADDRESS_CITY']))."%'";
		}
		if (isset($filters['CINC_REFERENCE_CODE'])) {
			$where_list[] = "UPPER(cinc_reference_code) LIKE '%".strtoupper($this->_db->db_escape_string($filters['CINC_REFERENCE_CODE']))."%'";
		}

		if ($result_count) {

			$sql = "SELECT count(cinc_id) as AANTAL FROM ccrd_incasso
				INNER JOIN ccrd_aanvraag_status ON csta_id = cinc_csta_id
				WHERE cinc_org_id = ".$org_id ."
				".($where_list ? ' AND ' : '') .implode(' AND ', $where_list);
			$rs = $this->_db->Query($sql);
			return $rs->Row('AANTAL');

		} else {

			$sql = "SELECT
					cinc_usr_id
				,	cinc_id
				,	nvl(cist_code,0) as cist_code
				,	nvl(cist_sortorder,0) as cist_sortorder
				,	cist_name
				,	cinc_reference_code
				,	to_char(cinc_request_date,'DD-MM-YYYY') as CINC_DATE
				,	to_char(cinc_close_date,'DD-MM-YYYY') as CINC_CLOSEDATE
				,	cinc_name
				,	cinc_address_city
				FROM ccrd_incasso
				INNER JOIN ccrd_aanvraag_status ON csta_id = cinc_csta_id
				LEFT JOIN ccrd_incasso_statuscode ON cist_id = cinc_cist_id
				WHERE cinc_org_id = ".$org_id ."
				".($where_list ? ' AND ' : '') .implode(' AND ', $where_list)."
				ORDER BY cist_sortorder ASC, cist_code ASC, cinc_request_date DESC";

			$rs = $this->_db->Query($sql, $offset, CCRD01_INC_LIST_PER_PAGE);
			$list = array();
			while ($r = $rs->Row()) {
				$r['USR_GREETING'] = $this->_getUserGreeting($r['CINC_USR_ID']);
				$list[] = $r;
				$rs->MoveNext();
			}


			return $list;
		}
	}

	function printIncassoList($form_data) {
		$filters = array();
		if (isset($form_data['search_date_from']) && strlen($form_data['search_date_from']) == 10) {
			$filters['DATE_FROM'] = trim($form_data['search_date_from']);
		}
		if (isset($form_data['search_date_till']) && strlen($form_data['search_date_till']) == 10) {
			$filters['DATE_TO'] = trim($form_data['search_date_till']);
		}
		if (isset($form_data['search_name']) && strlen(trim($form_data['search_name'])) > 0) {
			$filters['CINC_NAME'] = trim($form_data['search_name']);
		}
		if (isset($form_data['search_city']) && strlen(trim($form_data['search_city'])) > 0) {
			$filters['CINC_ADDRESS_CITY'] = trim($form_data['search_city']);
		}
		if (isset($form_data['search_reference']) && strlen(trim($form_data['search_reference'])) > 0) {
			$filters['CINC_REFERENCE_CODE'] = trim($form_data['search_reference']);
		}

		$current_page = isset($form_data['browse_current_page']) && is_numeric($form_data['browse_current_page']) && $form_data['browse_current_page'] > 0 ? $form_data['browse_current_page'] : 1;
		$offset = ($current_page-1)*CCRD01_KA_LIST_PER_PAGE;

		$incasso_list = $this->_getIncassoList($_SESSION['session_org_id'], $filters, $offset);
		$incasso_total_count = $this->_getIncassoList($_SESSION['session_org_id'], $filters, 0, true);

		$this->_smrt->assign('incasso_list', $incasso_list);
		$this->_smrt->assign('incasso_total_pages', ceil($incasso_total_count/CCRD01_KA_LIST_PER_PAGE));
		$this->_smrt->assign('incasso_total_count', $incasso_total_count);
		$this->_smrt->assign('incasso_current_page', $current_page);

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($this->_settings->templates->incasso_list);

	}

	function printIncasso($cinc_id, $type=null) {

		$incasso = $this->getIncasso($cinc_id);
		if ($incasso['CINC_ORG_ID'] == $_SESSION['session_org_id']) {
			$this->_smrt->assign('incasso', $incasso);
			$this->_smrt->assign('incasso_invoices', $this->getIncassoInvoices($cinc_id));
			$this->_smrt->assign('incasso_messages', $this->getIncassoMessages($cinc_id));

			
			switch ($type) {
				case 'financieel': 
					$this->_smrt->assign('incasso_payments_from_cd', $this->getIncassoPayments($cinc_id, CCRD_PAYMENT_FROM_CD_TO_CLIENT));
					$this->_smrt->assign('incasso_payments_from_debtor', $this->getIncassoPayments($cinc_id, CCRD_PAYMENT_FROM_DEBTOR_TO_CLIENT));
					$this->_smrt->assign('incasso_payments_not_payed', $this->getIncassoPayments($cinc_id, CCRD_PAYMENT_NOT_PAYED));
					$this->_smrt->assign('incasso_costs', $this->getIncassoCosts($cinc_id));

					$this->_smrt->assign('counted_invoices', array());
					
					$tpl = $this->_settings->templates->incasso_detail_financieel; 
					break;
				default: 
					$tpl = $this->_settings->templates->incasso_detail; 
					break;
			}

		}

		// Assign globals
		$this->assignTemplateGlobals();

		// Display
		$this->_smrt->display($tpl);

	}

}

?>