<?

require_once('class.stdModule.php');
require_once($globalSettings->tcat0409->paths->ddi);

define('CDIA_ORDER_ROW_TYPE_STOCK', 'stock');
define('CDIA_ORDER_ROW_TYPE_BULK', 'bulk');

define('CDIA_ORDERS_PER_PAGE', 10);
define('CDIA_PACKAGE_PREFIX', 'PKT');

define('CDIA_MAIL_INTERVAL_FACTOR', 3600*24); #dag
define('CDIA_MAIL_RESEND_INTERVAL', 7*3600*24); #week
//define('CDIA_MAIL_INTERVAL_FACTOR', 60); #uur

define('CDIA_STAT_TYPE_WEEK', 'WEEK'); 
define('CDIA_STAT_TYPE_MONTH', 'MONTH'); 

class cdia0100 extends troyceDynamicCatalogue {

	function cdia0100() {

		$this->troyceDynamicCatalogue();
		$this->stdModule('cdia0100');


		// Default Settings
		$this->_settings->templates->catalogue		= "catalogue.tpl";
		$this->_settings->templates->product		= "product.tpl";
		$this->_settings->templates->product_xml	= "product_xml.tpl";
		$this->_settings->templates->products		= "products.tpl";
		$this->_settings->templates->searchresult	= "searchresult.tpl";
		$this->_settings->templates->favorites		= "favorites.tpl";

		$this->_settings->templates->packages		= "packages.tpl";

		$this->_settings->templates->stock			= "stock.tpl";
		$this->_settings->templates->stock_advice	= "stock_advice.tpl";
		$this->_settings->templates->stock_bookoff	= "stock_bookoff.tpl";

		$this->_settings->templates->cart			= "cart.tpl";

		$this->_settings->templates->order_complete	= "order_complete.tpl";

		$this->_settings->templates->orders			= "orders.tpl";
		$this->_settings->templates->order			= "order.tpl";

		$this->_settings->templates->invoice_usr	= "invoice_usr.tpl";
		$this->_settings->templates->invoice_org	= "invoice_org.tpl";
		$this->_settings->templates->invoice_csv	= "invoice_csv.tpl";

		$this->_settings->templates->error			= "error.tpl";


		$this->_settings->email->invoice_org		= "CINVORG";
		$this->_settings->email->invoice_usr		= "CINVUSR";
		$this->_settings->email->invoice_check		= "CINVCHCK";
		$this->_settings->email->invoice_reminder	= "CINVRMDR";

		$this->_settings->email->error				= "CINVERR";
		
		$this->_settings->assignTemplateFunction	= '$this->_assignGlobals();';
		$this->_settings->showCurrencySymbol		= true;

		if (is_numeric($_SESSION['session_group']['GRP_ID'])) {
			$this->_variables->public->grp_id		= $_SESSION['session_group']['GRP_ID'];
		} else {
			$this->_variables->public->grp_id		= null;
		}


	}

	/************************************************************************
	* Basic functions 
	*************************************************************************/

	function getOrg($id=null, $code=null) {
		global $g_obj_ti3a0365;

		if (is_numeric($id)) {
			$fields = array(array('ORG_ID' , '='.$id), 'ORG_NAME');
			$atts = array('GATT_ORG_EMAIL', 'GATT_ORG_FAX');
		} elseif ($code) {
			$fields = array('ORG_ID', 'ORG_NAME');
			$atts = array(array('GATT_CODE', "='".$code."'"),'GATT_ORG_EMAIL', 'GATT_ORG_FAX');
		}

		$g_obj_ti3a0365->getOrganizations($orgs, $fields, $atts);
		return current($orgs);

	}

	function getUsr($id) {
		global $g_obj_ti3a0365;

		$fields = array(array('USR_ID' , '='.$id), 'USR_INITIALS', 'USR_INFIX', 'USR_FAMILYNAME');
		$atts = false;

		$g_obj_ti3a0365->getUsers($usrs, $fields, $atts);
		return current($usrs);

	}

	// E-mail quick 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 , true);

			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);

	}

	/************************************************************************
	* Catalogue functions 
	*************************************************************************/

	function printSearch($query) {

		$this->printSearchResult($query);
	}


			
	function printProductXML($prd_id=null, $code=null) {

		$product = array();
		$prd_id = $this->getProductID($code);

		if (is_numeric($prd_id)) {
			$this->_getProducts($rst, $prd_id);

			if (!$rst->EOF()) {
				$product = $rst->Row();
				$this->_formatRow($product);
			}
		}

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

		header("Content-Type: text/xml");
		$this->_smrt->display($this->_settings->templates->product_xml);
	}


	function printPackages() {

		$this->_getCatagories($rs_cats, 'PKT');

		while ($r = $rs_cats->row()) {
			
			$this->_getCatProducts($rs_products, null, $r['id']);
			$r['products'] = rs2arr($rs_products);
			
			$this->_smrt->append('packages', $r);
			
			$rs_cats->moveNext();
		}
		$rs_cats->Close();

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

	/************************************************************************
	* Cart functions 
	*************************************************************************/

	function saveCart($cart_data) {

		global $g_obj_tcat0409;

		if (!is_array($cart_data)) {
			$cart_data = unserialize(stripslashes($cart_data));
		}

		if (is_array($cart_data)) {

			foreach ($cart_data['cart'] as $prd_id => $amount) {
			
				$g_obj_tcat0409->setProduct($prd_id, $amount);

			}

			foreach ($cart_data['stock'] as $prd_id => $amount) {
				
				$this->setStockCartItem($prd_id, $amount);

			}


		}

	}


	function printCart() {
		global $g_obj_tcat0409;

		//--- bulk-bestellingen
		$cart = $g_obj_tcat0409->_getCartItems();
		if (count($cart)) {
			$this->_getProducts($rs_prods, implode(',',array_keys($cart)));

			while ($r = $rs_prods->row()) {
				$this->_formatRow(&$r);
				$r['amount'] = $cart[$r['id']];
				$this->_smrt->append('cart', $r);

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


		//--- stock-advice
		$advice = $this->_getStockAdvice();
		
		//--- initialize session-cart for stock items
		foreach ($advice['advice_hard'] as $p) {
			if (!isset($_SESSION['stock_cart'][$p['id']])) {
				$this->setStockCartItem($p['id'], $p['advice_order']);
			}
		}
		foreach ($advice['advice_soft'] as $p) {
			if (!isset($_SESSION['stock_cart'][$p['id']])) {
				$this->setStockCartItem($p['id'], $p['advice_order']);
			}
		}

		$this->_smrt->assign('stock_cart', $_SESSION['stock_cart']);

		$this->_smrt->assign('advice_hard', $advice['advice_hard']);
		$this->_smrt->assign('advice_soft', $advice['advice_soft']);

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


	/************************************************************************
	* Stock functions 
	*************************************************************************/

	function saveStock($stock_data) {
	
		if (!is_array($stock_data)) {
			$stock_data = unserialize(stripslashes($stock_data));
		}

		if (is_array($stock_data)) {

			foreach ($stock_data as $stock) {

				if (is_numeric($stock['prd_id']) && is_numeric($this->_variables->public->grp_id)) {

					$sql = "REPLACE INTO dia_stock_row SET
								sto_prd_id		= ".$stock['prd_id']."
							,	sto_grp_id		= ".$this->_variables->public->grp_id."
							,	sto_max			= ".(is_numeric($stock['max']) ? $stock['max'] : 0)."
							,	sto_min_hard	= ".(is_numeric($stock['min_hard']) ? $stock['min_hard'] : 0)."
							,	sto_min_soft	= ".(is_numeric($stock['min_soft']) ? $stock['min_soft'] : 0)."
							,	sto_current		= ".(is_numeric($stock['current']) ? $stock['current'] : 0);

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

				}
			}
		}

	}
	
	function printStock() {

		if (is_numeric($this->_variables->public->grp_id)) {

			$stock = array();
			$this->_getProducts($rs_prods);
			while ($r = $rs_prods->row()) {

				$this->_formatRow(&$r);
				$stock[$r['attributes']['SUPPLIER']['value']][] = $r;
//				$this->_smrt->append('stock', $r);

				$rs_prods->moveNext();
			}
			$rs_prods->Close();
			
			$this->_smrt->assign('stock', $stock);

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

	}

	function _getStockAdvice() {

		$advice = array('advice_hard' => array(), 'advice_soft' => array());
		
		if (is_numeric($this->_variables->public->grp_id)) {

			$sql = "SELECT sto_prd_id 
					FROM dia_stock_row 
					WHERE sto_grp_id = ".$this->_variables->public->grp_id ."
					AND (sto_current < sto_min_hard OR sto_current < sto_min_soft)";

			$prd_ids = rs2arr($this->_db->query($sql));
			$this->_getProducts($rs_prods, implode(',',$prd_ids));

			while ($r = $rs_prods->row()) {

				$this->_formatRow(&$r);

				if ($r['attributes']['ORDER_AMOUNT']['value'] > 1) {

					$r['advice_order'] = ceil(($r['sto_max']/$r['attributes']['ORDER_AMOUNT']['value']) - ($r['sto_current']/$r['attributes']['ORDER_AMOUNT']['value']));
					$r['advice_show'] = $r['advice_order'] * $r['attributes']['ORDER_AMOUNT']['value'];

				} else {

					$r['advice_order'] = $r['sto_max'] - $r['sto_current'];

				}

				$r['sto_state'] = 'OK';
				if (($r['sto_current'] + ($r['sto_backorder']*$r['attributes']['ORDER_AMOUNT']['value'])) < $r['sto_min_hard']) {
					$r['sto_state'] = 'HARD';
					$advice['advice_hard'][] = $r;

				} elseif (($r['sto_current'] + ($r['sto_backorder']*$r['attributes']['ORDER_AMOUNT']['value'])) < $r['sto_min_soft']) {
					$r['sto_state'] = 'SOFT';

					$advice['advice_soft'][] = $r;

				}

				$rs_prods->moveNext();
			}

			$rs_prods->Close();

		}

		return $advice;

	}

	function printStockAdvice() {

		$advice = $this->_getStockAdvice();

		$this->_smrt->assign('advice_hard', $advice['advice_hard']);
		$this->_smrt->assign('advice_soft', $advice['advice_soft']);

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

	}



	function setStockCartItem($prd_id, $amount) {
		$_SESSION['stock_cart'][$prd_id] = $amount;
	}
	
	function resetStockCart() {
		$_SESSION['stock_cart'] = array();
	}


	function bookoffProduct($prd_id, $amount) {
	
		if (is_numeric($prd_id) && is_numeric($amount) && $amount > 0) {
			
			$this->doStockBookoff(array($prd_id => $amount), false);

		}

	}

	function initStockBookoff($products) {

		$_SESSION['sbo_list'] = array();
		$_SESSION['sbo_list_package'] = array();

		foreach ($products as $prd_code => $amount) {
			
			$prd_id = $this->getProductID($prd_code);
			if (is_numeric($prd_id)) {
			
				$_SESSION['sbo_list'][$prd_id] = $amount;
			
			} else {
				
				$category = $this->getCategoryByCode($prd_code);
	
				if (isset($category['id']) && is_numeric($category['id'])) {
					$_SESSION['sbo_list_package'][$category['id']] = $category;
					$_SESSION['sbo_list_package'][$category['id']]['amount'] = $amount;
				}
			}
		}
	}
			
	function printStockBookoff() {

		if ($_SESSION['sbo_list']) {
			$this->_getProducts($rs_prods, implode(',',array_keys($_SESSION['sbo_list'])));

			while ($r = $rs_prods->row()) {
				$this->_formatRow(&$r);
				$r['amount'] = $_SESSION['sbo_list'][$r['id']];

				$this->_smrt->append('products', $r);

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

		if ($_SESSION['sbo_list_package']) {

			
			$this->_smrt->assign('packages', $_SESSION['sbo_list_package']);

		}

		$this->_smrt->display($this->_settings->templates->stock_bookoff);

	}

	function doStockBookoff($bookoff_data, $reset=true) {
	
		foreach ($bookoff_data as $prd_id => $amount) {
			if (is_numeric($prd_id)) {
				
				$sql = "UPDATE dia_stock_row SET
							sto_current		= IF(sto_current - ".$amount." < 0, 0, sto_current - ".$amount.")
						WHERE
							sto_prd_id		= ".$prd_id."
						AND	sto_grp_id		= ".$this->_variables->public->grp_id;

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

				$sql = "INSERT INTO dia_bookoffs SET
							bko_prd_id		= ".$prd_id."
						,	bko_org_id		= ".$_SESSION['session_org']['ORG_ID']."
						,	bko_grp_id		= ".$this->_variables->public->grp_id."
						,	bko_usr_id		= ".$this->_variables->public->usr_id."
						,	bko_amount		= ".$amount."
						,	bko_date		= NOW()";
				$this->_db->execute($sql);

			} elseif (strpos($prd_id, CDIA_PACKAGE_PREFIX) === 0) {

				//--- bookoff packages
				$category = $this->getCategoryByCode($prd_id);

				$this->_getCatProducts($rs_products, null, $category['id']);
				$products = rs2arr($rs_products);
				if (count($products)) {
					foreach ($products as $prd) {

						$sql = "UPDATE dia_stock_row SET
									sto_current		= IF(sto_current - ".$amount." < 0, 0, sto_current - ".$amount.")
								WHERE
									sto_prd_id		= ".$prd['id']."
								AND	sto_grp_id		= ".$this->_variables->public->grp_id;

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

						$sql = "INSERT INTO dia_bookoffs SET
									bko_prd_id		= ".$prd['id']."
								,	bko_org_id		= ".$_SESSION['session_org']['ORG_ID']."
								,	bko_grp_id		= ".$this->_variables->public->grp_id."
								,	bko_usr_id		= ".$this->_variables->public->usr_id."
								,	bko_amount		= ".$amount."
								,	bko_date		= NOW()";
						$this->_db->execute($sql);

					}
				}
			}
		}
		

		if ($reset) {
			//--- reset
			$_SESSION['sbo_list'] = array();
			$_SESSION['sbo_list_package'] = array();
		}

		
	}

	/************************************************************************
	* Order functions 
	*************************************************************************/

	function setOrder() {
		global $g_obj_tcat0409;

		$orders = array();

		//--- bulk-bestellingen
		$cart = $g_obj_tcat0409->_getCartItems();
		if (count($cart)) {
			foreach ($cart as $prd_id => $amount) {

				$supplier = $this->_getProductAttribute($prd_id, 'SUPPLIER');
				$orders[$supplier['value']][] = array(
													'prd_id'	=> $prd_id
												,	'amount'	=> $amount
												,	'type'		=> CDIA_ORDER_ROW_TYPE_BULK
												);
			}
		}

		//--- initialize session-cart for stock items
		if (is_array($_SESSION['stock_cart']) && count($_SESSION['stock_cart']) > 0) {
			foreach ($_SESSION['stock_cart'] as $prd_id => $amount) {
				
				if ($amount > 0) {

					$supplier = $this->_getProductAttribute($prd_id, 'SUPPLIER');
					$orders[$supplier['value']][] = array(
														'prd_id'	=> $prd_id
													,	'amount'	=> $amount
													,	'type'		=> CDIA_ORDER_ROW_TYPE_STOCK
													);
				}
			}
		}

		
		//--- creating orders
		foreach ($orders as $supplier_code => $order) {
			$supplier = $this->getOrg(null, $supplier_code);
			

			$prd_ids = array_unique(array_values_multi($order, 'prd_id'));
			$products = $this->getProducts($prd_ids);

			if (is_numeric($supplier['ORG_ID'])) {

				$order_products = array();
				$ord_id = $this->_createOrder($supplier['ORG_ID'], $supplier_code);

				foreach ($order as $index => $row) {
					
					$this->_addOrderRow($ord_id, $row['prd_id'], $row['amount'], $row['type']);

					if (!$order_products[$row['prd_id']]) {
						$order_products[$row['prd_id']] = $products[$row['prd_id']];
						$order_products[$row['prd_id']]['amount'] = 0;
					}

					$order_products[$row['prd_id']]['amount'] += $row['amount'];

				}
			
				//--- send order mail to user
				$invoice = $this->_createInvoice($order_products, $supplier, $this->_settings->templates->invoice_usr);
				$this->_send_email(
								$this->_settings->email->invoice_usr
							,	$this->_variables->public->usr_id
							,	null
							,	array(	'ORDER'				=> $invoice
									,	'ORDER_NUMBER'		=> $ord_id
									,	'CLIENT_ORG_NAME'	=> $_SESSION['session_org']['ORG_NAME']
									,	'CLIENT_AFDELING'	=> $_SESSION['session_group']['GRP_DESCRIPTION']
								)
							);

				//--- send order mail to supplier
			
				$invoice_csv = $this->_createInvoice($order_products, $supplier, $this->_settings->templates->invoice_csv);
				$attachment = array('data'		=> $invoice_csv
								,	'filename'	=> 'order_'.$ord_id.'.csv'
								,	'mimetype'	=> 'text/csv'
								,	'inline'	=> false);

				$invoice = $this->_createInvoice($order_products, $supplier, $this->_settings->templates->invoice_org);
				$this->_send_email(
								$this->_settings->email->invoice_org
							,	null
							,	$supplier['GATT_ORG_EMAIL']
							,	array(	'ORDER'				=> $invoice
									,	'ORDER_NUMBER'		=>$ord_id
									,	'CLIENT_ORG_NAME'	=> $_SESSION['session_org']['ORG_NAME']
									,	'CLIENT_AFDELING'	=> $_SESSION['session_group']['GRP_DESCRIPTION']
								)
							, $attachment
						);
			
			} else {
			
				$this->_send_email(	$this->_settings->email->error
								,	null
								,	null
								,	array('ERROR' => "Supplier not found. code: ".$supplier_code."\n\n".print_r($order,1))
								);


			}

		}

		//--- clear cart
		$g_obj_tcat0409->clear();
		$this->resetStockCart();

	}

	function _createInvoice(&$products, $supplier, $tpl) {

		$this->_smrt->assign('products', $products);
		$this->_smrt->assign('supplier', $supplier);
		
		$invoice = $this->_smrt->fetch($tpl);

		return $invoice;
	
	}

	function _createOrder($supplier_org_id, $supplier_code) {

		if (is_numeric($this->_variables->public->grp_id) && is_numeric($this->_variables->public->usr_id) && is_numeric($supplier_org_id)) {


			$ord_id = $this->_createOrderNumber();
			//--- make new order
			$sql = "INSERT INTO dia_order SET
						ord_id		= ".$ord_id."
					,	ord_date	= NOW()
					,	ord_org_id	= ".$_SESSION['session_org']['ORG_ID']."
					,	ord_grp_id	= ".$this->_variables->public->grp_id."
					,	ord_usr_id	= ".$this->_variables->public->usr_id."
					,	ord_supplier_org_id	= ".$supplier_org_id."
					,	ord_supplier_code	= '".mysql_escape_string($supplier_code)."'
					,	ord_status	= 'NEW'";
			$this->_db->execute($sql);

			return $ord_id;

		}
	}

		function _createOrderNumber() {

			$invalid = true;
			while ($invalid) {
				$new_number = rand(100000,999999);
				$rst = $this->_db->Query("SELECT ord_id FROM dia_order WHERE ord_id = ".$new_number);
				$invalid = (!$rst->EOF());
				$rst->Close();
			}

			return $new_number;
		}

	function _addOrderRow($ord_id, $prd_id, $amount, $type) {
		if (is_numeric($ord_id) && is_numeric($prd_id) && is_numeric($amount) && ($type == CDIA_ORDER_ROW_TYPE_BULK || $type == CDIA_ORDER_ROW_TYPE_STOCK)) {

			$sql = "INSERT INTO dia_order_row SET
						row_ord_id	= ".$ord_id."
					,	row_prd_id	= ".$prd_id."
					,	row_amount	= ".$amount."
					,	row_price	= 0
					,	row_type	= '".$type."'";
			
			$this->_db->execute($sql);

		}
	
	}

	function printOrderList($status=null, $page=1) {
		if (!is_numeric($this->_variables->public->grp_id)) return;
		
		if (!$page || $page < 1) $page = 1;

		$sql_status = '';
		if ($status == 'NEW') {
			$sql_status = " AND ord_status = 'NEW'";
		} elseif ($status == 'CLOSED') {
			$sql_status = " AND ord_status = 'CLOSED'";
		}


		$sql = "SELECT SQL_CALC_FOUND_ROWS
					*
				,	UNIX_TIMESTAMP(ord_date) as ord_date
				,	SUM(IFNULL(row_amount,0)) as amount_order
				,	SUM(IFNULL(row_amount_received,0)) as amount_received
				,	IF(SUM(IF(row_amount_received >= row_amount, 0, 1)) > 0, 0, 1) as order_complete
				,	COUNT(row_id) AS stock_rows
				FROM dia_order 
				LEFT JOIN dia_order_row ON row_ord_id = ord_id AND row_type = 'STOCK'
				WHERE ord_grp_id = ".$this->_variables->public->grp_id ."
				".$sql_status."
				GROUP BY ord_id
				ORDER BY ord_date DESC";

		$rs = $this->_db->query($sql, ($page-1)*CDIA_ORDERS_PER_PAGE, CDIA_ORDERS_PER_PAGE);

		while ($r = $rs->row()) {

			$r['supplier'] = $this->getOrg($r['ord_supplier_org_id']);
			$this->_smrt->append('orders', $r);

			$rs->moveNext();
		}
		$current_page_rows = $rs->RowCount;
		$rs->Close();

		$tmp = $this->_db->query('SELECT FOUND_ROWS()');
		$total_rows = $tmp->Row('FOUND_ROWS()');
		$tmp->Close();

		$paging = array(	'current_page'		=> $page
						,	'current_page_rows'	=> $current_page_rows
						,	'total_rows'		=> $total_rows
						,	'total_pages'		=> ceil($total_rows/CDIA_ORDERS_PER_PAGE)
						);
		$this->_smrt->assign('paging', $paging);



		$this->_smrt->display($this->_settings->templates->orders);

	}

	function _getOrder($ord_id, $grp_id) {

		if (!is_numeric($ord_id) || !is_numeric($grp_id)) return;

		//--- order-data
		$sql = "SELECT *
				,	UNIX_TIMESTAMP(ord_date) as ord_date
				,	SUM(IFNULL(row_amount_received,0)) as amount_received
				,	IF(SUM(IF(row_amount_received >= row_amount, 0, 1)) > 0, 0, 1) as order_complete
				FROM dia_order
				LEFT JOIN dia_order_row ON row_ord_id = ord_id AND row_type = 'stock'
				WHERE ord_grp_id = ".$grp_id."
				AND ord_id = ".$ord_id ."
				GROUP BY ord_id";
		$rs = $this->_db->Query($sql);
		$order = $rs->Row();
		$rs->Close();

		return $order;

	}

	function printOrder($ord_id) {
		if (!is_numeric($this->_variables->public->grp_id) || !is_numeric($ord_id)) return;

		$order = $this->_getOrder($ord_id, $this->_variables->public->grp_id);

		if ($order) {


			$this->_smrt->assign('order', $order);
			$this->_smrt->assign('supplier', $this->getOrg($order['ord_supplier_org_id']));
			$this->_smrt->assign('user', $this->getUsr($order['ord_usr_id']));

			//--- order-rows

			$sql = "SELECT * 
					FROM dia_order_row 
					WHERE row_ord_id = ".$ord_id."
					ORDER BY row_type ASC";
			$rows = rs2arr($this->_db->query($sql));

			$prd_ids = array_values_multi($rows, 'row_prd_id');
			$this->_getProducts($rs_products, implode(',',$prd_ids));
			while ($r = $rs_products->row()) {
				$this->_formatRow(&$r);
				$products[$r['id']] = $r;
				$rs_products->moveNext();
			}
			$rs_products->Close();


			$this->_smrt->assign('products', $products);
			$this->_smrt->assign('order_rows', $rows);


		}

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

	}

	function saveOrder($ord_id, $order_row_data) {
		if (!is_numeric($this->_variables->public->grp_id) || !is_numeric($ord_id)) return;

		if (!is_array($order_row_data)) {
			$order_row_data = unserialize(stripslashes($order_row_data));
		}

		if (is_array($order_row_data)) {

			foreach ($order_row_data as $prd_id => $amount_received) {
				if (!is_numeric($prd_id)) continue;

				//--- get current value
				$sql = "SELECT IFNULL(row_amount_received,0) as row_amount_received
						FROM dia_order_row
						INNER JOIN dia_order ON ord_id = ".$ord_id." AND ord_grp_id = ".$this->_variables->public->grp_id."
						WHERE row_ord_id = ord_id
						AND	row_prd_id = ".$prd_id."
						AND row_type = 'STOCK'";
				$rs = $this->_db->query($sql);
				$diff = $amount_received - $rs->Row('row_amount_received');
				$order_amount = $this->_getProductAttribute($prd_id, 'ORDER_AMOUNT');
				$diff *= $order_amount['value'];
			
				//--- update order-row
				$sql = "UPDATE dia_order_row 
						INNER JOIN dia_order ON ord_id = ".$ord_id." AND ord_grp_id = ".$this->_variables->public->grp_id."
						SET
							row_amount_received = ".(int)$amount_received."
						WHERE
							row_ord_id = ord_id
						AND	row_prd_id = ".$prd_id."
						AND row_type = 'STOCK'";

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

				//--- update stock-data
				if ($diff != 0) {
					$sql = "UPDATE dia_stock_row SET
								sto_current		= sto_current + ".$diff."
							WHERE
								sto_prd_id		= ".$prd_id."
							AND	sto_grp_id		= ".$this->_variables->public->grp_id;
					$this->_db->execute($sql);
				}
			}
		}
	
	}

	function closeOrder($ord_id) {
		if (!is_numeric($this->_variables->public->grp_id) || !is_numeric($ord_id)) return;

		$sql = "UPDATE dia_order 
				SET ord_status = 'CLOSED' 
				WHERE ord_id = ".$ord_id." AND ord_grp_id = ".$this->_variables->public->grp_id;

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

	}

	function sendSupplierMail($ord_id) {

		$order = $this->_getOrder($ord_id, $this->_variables->public->grp_id);

		if ($order) {

			$supplier = $this->getOrg($order['ord_supplier_org_id']);

			//--- send e-mail
			$this->_send_email(	$this->_settings->email->invoice_reminder
							,	null
							,	$supplier['GATT_ORG_EMAIL']
							,	array(	'ORDER_NUMBER'		=> $order['ord_id']
									,	'ORDER_DATE'		=> date('d-m-Y H:i', $order['ord_date'])
									,	'CLIENT_ORG_NAME'	=> $_SESSION['session_org']['ORG_NAME']
									,	'CLIENT_AFDELING'	=> $_SESSION['session_group']['GRP_DESCRIPTION']
								)
							);
			

		}
	
	}

	function sendOrderCheckMails() {
		global $g_obj_ti3a0365;
		
		//-- get all leveranciers
		$g_obj_ti3a0365->getOrganizations($tmp_orgs, array('ORG_ID', 'ORG_NAME', array('ORG_DEF_CODE', "='LEV'")), array('GATT_ORG_WAIT_DAYS'));
		$orgs = array();
		foreach ($tmp_orgs as $org) {
			$orgs[$org['ORG_ID']] = $org;
		}

		$sent = 0;

		$sql = "SELECT 
					dia_order.* 
				,	UNIX_TIMESTAMP(ord_date) as ord_date_timestamp
				,	UNIX_TIMESTAMP(ord_check_mail) as ord_check_mail_timestamp
				,	SUM(IFNULL(row_amount_received,0)) total_received
				FROM dia_order
				LEFT JOIN dia_order_row ON row_ord_id = ord_id
				WHERE ord_status = 'NEW'
				GROUP BY ord_id
				HAVING total_received = 0";
		
		$rs = $this->_db->query($sql);
		while ($r = $rs->row()) {

			$factor = ($orgs[$r['ord_supplier_org_id']]['GATT_ORG_WAIT_DAYS'] * CDIA_MAIL_INTERVAL_FACTOR);

			if ($factor > 0) {
				if (($r['ord_date_timestamp'] + $factor) < time()) {

					$day_now		= mktime(0,0,0,date('m'),date('d'),date('Y'));
					if (is_numeric($r['ord_check_mail_timestamp'])) {
						$day_last_sent	= mktime(0,0,0,date('m', $r['ord_check_mail_timestamp']),date('d', $r['ord_check_mail_timestamp']),date('Y', $r['ord_check_mail_timestamp']));
					}

					if (!is_numeric($r['ord_check_mail_timestamp']) || $day_now > ($day_last_sent+CDIA_MAIL_RESEND_INTERVAL)) {

						//--- send e-mail
						$this->_send_email(	$this->_settings->email->invoice_check
										,	$r['ord_usr_id']
										,	null
										,	array(	'ORDER_NUMBER'	=> $r['ord_id']
												,	'ORDER_DATE'	=> date('d-m-Y H:i', $r['ord_date_timestamp'])
												,	'SUPPLIER'		=> $orgs[$r['ord_supplier_org_id']]['ORG_NAME']
											)
										);


					
						$this->_db->Execute("UPDATE dia_order SET ord_check_mail = NOW() WHERE ord_id = ".$r['ord_id']);				
						$sent++;
					}

				}
			}

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

		echo $sent . "  berichten verzonden";
	}	

	/************************************************************************
	* Stats functions (used in BO)
	*************************************************************************/
	
	function getStatsBookoff($stat_type, $number, $year, $org_id=null, $grp_id=null, $usr_id=null) {

		if ($year > 0) {

			$sql = "SELECT 
						bko_prd_id
					".(!is_numeric($number) || $number < 1 ? ', '.$stat_type .'(bko_date) as stat_type' : '')."
					,	count(bko_id) as aantal_regels
					,	sum(bko_amount) as aantal_items
					FROM 
						dia_bookoffs 
					WHERE YEAR(bko_date) = ".$year. (is_numeric($number) && $number > 0 ? ' AND '.$stat_type ."(bko_date) = ".$number : "") ." 
					".(is_numeric($org_id) && $org_id>0 ? ' AND bko_org_id = '.$org_id : '')."
					".(is_numeric($grp_id) && $grp_id>0 ? ' AND bko_grp_id = '.$grp_id : '')."
					".(is_numeric($usr_id) && $usr_id>0 ? ' AND bko_usr_id = '.$usr_id : '')."

					GROUP BY bko_prd_id ". (!is_numeric($number) || $number < 1 ? ', stat_type ' : '');

			$rs = $this->_db->query($sql);
		
			$this->_getProducts($rs_prd);
			$products = rs2arr($rs_prd, 'id');

			$stats = array();
			foreach ($products as $prd) {
				$stats[$prd['id']]['name']	= $prd['name'];
				$stats[$prd['id']]['code']	= $prd['code'];
			}


			$rs = $this->_db->query($sql);
			while ($r = $rs->row()) {
				

				if (!is_numeric($number) || $number < 1) {

					 $stats[$r['bko_prd_id']]['aantal_regels'][$r['stat_type']] = $r['aantal_regels'];
					 $stats[$r['bko_prd_id']]['aantal_items'][$r['stat_type']] = $r['aantal_items'];

				} else {

					$stats[$r['bko_prd_id']]['aantal_regels'] = $r['aantal_regels'];
					$stats[$r['bko_prd_id']]['aantal_items'] = $r['aantal_items'];
			

				}


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


			
			return $stats;

		}

	}


	function getStatsBulk($stat_type, $number, $year, $org_id=null, $grp_id=null, $usr_id=null) {
		
		if ($year > 0) {

			$sql = "SELECT 
						row_prd_id
					".(!is_numeric($number) || $number < 1 ? ', '.$stat_type .'(ord_date) as stat_type' : '')."
					,	count(row_id) as aantal_regels
					,	sum(row_amount) as aantal_items
					FROM 
						dia_order_row 
					INNER JOIN dia_order ON ord_id = row_ord_id
					WHERE row_type = 'bulk' AND YEAR(ord_date) = ".$year. (is_numeric($number) && $number > 0 ? " AND " . $stat_type ."(ord_date) = ".$number : "") ."
					".(is_numeric($org_id) && $org_id>0 ? ' AND ord_org_id = '.$org_id : '')."
					".(is_numeric($grp_id) && $grp_id>0 ? ' AND ord_grp_id = '.$grp_id : '')."
					".(is_numeric($usr_id) && $usr_id>0 ? ' AND ord_usr_id = '.$usr_id : '')."
					GROUP BY row_prd_id ". (!is_numeric($number) || $number < 1 ? ', stat_type ' : '');

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


			$this->_getProducts($rs_prd);
			$products = rs2arr($rs_prd, 'id');

			$stats = array();
			foreach ($products as $prd) {
				$stats[$prd['id']]['name']	= $prd['name'];
				$stats[$prd['id']]['code']	= $prd['code'];
			}

			$rs = $this->_db->query($sql);
			while ($r = $rs->row()) {
				

				if (!is_numeric($number) || $number < 1) {

					 $stats[$r['row_prd_id']]['aantal_regels'][$r['stat_type']] = $r['aantal_regels'];
					 $stats[$r['row_prd_id']]['aantal_items'][$r['stat_type']] = $r['aantal_items'];

				} else {

					$stats[$r['row_prd_id']]['aantal_regels'] = $r['aantal_regels'];
					$stats[$r['row_prd_id']]['aantal_items'] = $r['aantal_items'];
			

				}


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

			return $stats;

		}

	}

	function getStatsOrder($stat_type, $number, $year, $org_id=null, $grp_id=null, $usr_id=null) {

		if ($year > 0) {

			$sql = "SELECT
						ord_id
					".(!is_numeric($number) || $number < 1 ? ', '.$stat_type .'(ord_date) as stat_type' : '')."
					,	IF(SUM(IF(row_amount_received >= row_amount, 0, 1)) > 0, 0, 1) as order_complete
					,	SUM(IFNULL(row_amount_received,0)) as amount_received
					,	COUNT(row_id) as stock_rows
					,	ord_status
					FROM dia_order
					LEFT JOIN dia_order_row ON row_ord_id = ord_id AND row_type = 'stock'
					WHERE ". (is_numeric($number) && $number > 0 ? $stat_type ."(ord_date) = ".$number." AND " : "") ." YEAR(ord_date) = ".$year."
					".(is_numeric($org_id) && $org_id>0 ? ' AND ord_org_id = '.$org_id : '')."
					".(is_numeric($grp_id) && $grp_id>0 ? ' AND ord_grp_id = '.$grp_id : '')."
					".(is_numeric($usr_id) && $usr_id>0 ? ' AND ord_usr_id = '.$usr_id : '')."
					GROUP BY ord_id";

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

			$stats = array();
			$stats['OPEN']['name']			= 'Openstaand';
			$stats['PART_OPEN']['name']		= 'Gedeeltelijk ontvangen - Open';
			$stats['PART_CLOSE']['name']	= 'Gedeeltelijk ontvangen - Gesloten';
			$stats['CLOSE_ACK']['name']		= 'Volledig ontvangen';
			$stats['CLOSE_NACK']['name']	= 'Geen ontvangst';

			$rs = $this->_db->query($sql);
			while ($r = $rs->row()) {
				

				if ($r['ord_status'] == 'NEW') {
					if ($r['amount_received'] == 0) {
						$stats['OPEN']['aantal_items'][$r['stat_type']]++;
					} else {
						$stats['PART_OPEN']['aantal_items'][$r['stat_type']]++;
					}
				} else {
				
					if ($r['order_complete'] == 1) {
						$stats['CLOSE_ACK']['aantal_items'][$r['stat_type']]++;
					} else {
						
						if ($r['amount_received'] == 0) {
							$stats['CLOSE_NACK']['aantal_items'][$r['stat_type']]++;
						} else {
							$stats['PART_CLOSE']['aantal_items'][$r['stat_type']]++;
						}

					}

				}

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

			return $stats;

		}

	}



	/************************************************************************
	* Basic Troyce Catalog functions (new & extending)
	*************************************************************************/

	function getCategoryByCode($cat_code) {

		$rs = $this->_db->Query("SELECT cat_id FROM tbl_ctl_catagories WHERE cat_code = '".mysql_escape_string($cat_code)."' AND cat_org_id = ".$this->_variables->public->org_id);
		$cat_id = $rs->Row('cat_id');

		if (is_numeric($cat_id)) {
			return $this->_getCatagory($cat_id);
		}
	}

	

	function _getProductAttribute($prd_id, $att_code) {

		$sql = "SELECT
					IFNULL(opt_value, val_value) as value
				,	lbl_label as label
				FROM tbl_ctl_att_values
				INNER JOIN tbl_ctl_attributes ON att_id = val_att_id AND att_code = '".$att_code."' AND att_org_id = ".$this->_variables->public->org_id."
				LEFT JOIN tbl_ctl_att_options ON opt_att_id = att_id AND opt_id = val_value
				LEFT JOIN tbl_ctl_labels ON lbl_itm_id = opt_id AND lbl_itm_tbl = 'tbl_ctl_att_options' AND lbl_itm_col = 'opt_name' AND lbl_lng_id = ".$this->_variables->private->lng_id."
				WHERE val_prd_id = ".$prd_id;

		$rs = $this->_db->query($sql);
		$att = $rs->Row();
		$rs->Close();

		return $att;
	}

	function getProducts($prd_ids) {

		if (!is_array($prd_ids)) return;

		$this->_getProducts($rs_prods, implode(',',$prd_ids));

		$products = array();
		while ($r = $rs_prods->row()) {
			$this->_formatRow(&$r);
			$products[$r['id']] = $r;
			$rs_prods->moveNext();
		}
		$rs_prods->Close();

		return $products;
	}

	function _getCatProducts(&$rst, $grp_code = null, $parent_id = 1) {
		
		if ($grp_code) {
			if (!($grp_id = $this->_getGroupID($grp_code))) {
				$this->triggerError(TCAT_ERR_INVALID_GRP);
				return false;
			}
		}
		
		if ($this->_variables->public->items_per_page > 0) {
			$limit = $this->_variables->public->items_per_page;
			$offset = $this->_variables->public->page_offset * $limit;
		}

		// Make sure that the order string is valid
		if (preg_match('/^((id|def_id|box_id|discount_id|img_uri|code|weight|stocklevel|price|hideprice|name|description|favorite)(\s(asc|desc))?,?)+$/i', $this->_variables->public->sorting->products) == 1) $order = $this->_variables->public->sorting->products;
		else $order = 'l1.lbl_label';

		$rst = $this->_db->Query("
			select 
				prd_id as id
			,	prd_def_id as def_id
			,	prd_box_id as box_id
			,	prd_dcs_id as discount_id
			,	prd_img_uri as img_uri
			,	prd_code as code
			,	prd_weight as weight
			,	prd_stocklevel as stocklevel
			,	prd_price as price
			,	prd_hideprice as hideprice
			,	l1.lbl_label as name
			,	l2.lbl_label as description
			,	if(pfv_id, 1, 0) as favorite 

			".($this->_variables->public->grp_id ? 
				",	sto_id
				,	sto_max
				,	sto_min_hard
				,	sto_min_soft
				,	sto_current

				,	IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0) as sto_backorder
				,	IF(
						(sto_max - (sto_current + IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0))) < 0,
						0,
						(sto_max - (sto_current + IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0)))
						) AS sto_order_advice
				,	(IF(
						(sto_current + (IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0))*val_value) < sto_min_hard, 
						'HARD', 
						IF(
							(sto_current + (IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0))*val_value) < sto_min_soft,
							'SOFT',
							'OK')
						)) as sto_state
				" : "") ."
			from 
				tbl_ctl_products
			inner join
				tbl_ctl_prd_connections
			on	pcn_prd_id = prd_id 
			and	pcn_cat_id = ".$parent_id."
			".($grp_id ? "and pcn_grp_id = ".$grp_id : "")."

			left join 
				tbl_ctl_labels as l1
			on l1.lbl_itm_id = prd_id
			and l1.lbl_itm_tbl = 'tbl_ctl_products'
			and	l1.lbl_itm_col = 'prd_name'
			and	l1.lbl_lng_id = ".$this->_variables->private->lng_id." 

			left join 
				tbl_ctl_labels as l2
			on	l2.lbl_itm_id = prd_id
			and	l2.lbl_itm_tbl = 'tbl_ctl_products'
			and	l2.lbl_itm_col = 'prd_description'
			and	l2.lbl_lng_id = ".$this->_variables->private->lng_id." 

			LEFT JOIN tbl_ctl_attributes ON att_code = 'ORDER_AMOUNT' AND att_org_id = ".$this->_variables->public->org_id."
			LEFT JOIN tbl_ctl_att_values ON val_prd_id = prd_id AND val_att_id = att_id

			left join
				tbl_ctl_prd_favorites
			on	pfv_prd_id = prd_id
			and pfv_usr_id = ".(is_numeric($this->_variables->public->usr_id) ? $this->_variables->public->usr_id : 0)." 

				".($this->_variables->public->grp_id ? 
					"
					LEFT JOIN dia_order ON ord_grp_id = ".$this->_variables->public->grp_id ." AND ord_status != 'CLOSED'
					LEFT JOIN dia_order_row ON row_ord_id = ord_id AND row_prd_id = prd_id AND row_type = 'stock'
					LEFT JOIN
						dia_stock_row
					ON
						sto_prd_id = prd_id 
					AND sto_grp_id = ".$this->_variables->public->grp_id : "")."

			where
				prd_org_id = ".$this->_variables->public->org_id."
			and	(prd_startdate is null or prd_startdate <= now())
			and (prd_enddate is null or prd_enddate >= now())
			".($this->_variables->public->grp_id ? "GROUP BY prd_id" : "")."
			order by ".$order."
		", $offset, $limit);

		return true;
		
	} // _getCatProducts



	/*
	 * Returns the specified products
	 * 
	 * @param $rst			The return recordset
	 * @param $prd_ids		One ore more (comma separated) product ids
	 * @param $filter		Additional filter criteria.
	 * @param $favorites	Only fetch favorite products
	 * @access private
	 * @return void
	 */
	function _getProducts(&$rst, $prd_ids = null, $filter = null, $favorites = false) {

		$limit = null;
		$offset = null;
		if ($this->_variables->public->items_per_page > 0) {
			$limit = $this->_variables->public->items_per_page;
			$offset = $this->_variables->public->page_offset * $limit;
		}

		// Make sure that the order string is valid
		if (preg_match('/^((id|def_id|box_id|discount_id|img_uri|code|weight|stocklevel|price|hideprice|name|description|favorite)(\s(asc|desc))?,?)+$/i', $this->_variables->public->sorting->products) == 1) $order = $this->_variables->public->sorting->products;
		else $order = 'l1.lbl_label';

//,	(IF ((sto_current + IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0)) < sto_min_hard, 'HARD', IF((sto_current + IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0)) < sto_min_soft, 'SOFT', 'OK'))) as sto_state

		$rst = $this->_db->Query("
			select 
				prd_id as id,
				prd_def_id as def_id,
				prd_box_id as box_id,
				prd_dcs_id as discount_id,
				prd_img_uri as img_uri,
				prd_code as code,
				prd_weight as weight,
				prd_stocklevel as stocklevel,
				prd_price as price,
				prd_hideprice as hideprice,
				l1.lbl_label as name,
				l2.lbl_label as description,
				if(pfv_id, 1, 0) as favorite 

			".($this->_variables->public->grp_id ? 
				",	sto_id
				,	sto_max
				,	sto_min_hard
				,	sto_min_soft
				,	sto_current

				,	IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0) as sto_backorder
				,	IF(
						(sto_max - (sto_current + IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0))) < 0,
						0,
						(sto_max - (sto_current + IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0)))
						) AS sto_order_advice

				,	(IF(
						(sto_current + (IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0))*val_value) < sto_min_hard, 
						'HARD', 
						IF(
							(sto_current + (IFNULL(SUM(row_amount - IFNULL(row_amount_received,0)),0))*val_value) < sto_min_soft,
							'SOFT',
							'OK')
						)) as sto_state
				" : "") ."
			from 
				tbl_ctl_products
				left join 
					tbl_ctl_labels as l1
				on 
					l1.lbl_itm_id = prd_id and 
					l1.lbl_itm_tbl = 'tbl_ctl_products' and
					l1.lbl_itm_col = 'prd_name' and
					l1.lbl_lng_id = ".$this->_variables->private->lng_id." 
				left join 
					tbl_ctl_labels as l2
				on 
					l2.lbl_itm_id = prd_id and 
					l2.lbl_itm_tbl = 'tbl_ctl_products' and
					l2.lbl_itm_col = 'prd_description' and
					l2.lbl_lng_id = ".$this->_variables->private->lng_id." 
				".($favorites ? "inner" : "left")." join
					tbl_ctl_prd_favorites
				on
					pfv_prd_id = prd_id and 
					pfv_usr_id = ".(is_numeric($this->_variables->public->usr_id) ? $this->_variables->public->usr_id : 0)." 

			LEFT JOIN tbl_ctl_attributes ON att_code = 'ORDER_AMOUNT' AND att_org_id = ".$this->_variables->public->org_id."
			LEFT JOIN tbl_ctl_att_values ON val_prd_id = prd_id AND val_att_id = att_id


				".($this->_variables->public->grp_id ? 
					"
					LEFT JOIN dia_order ON ord_grp_id = ".$this->_variables->public->grp_id ." AND ord_status != 'CLOSED'
					LEFT JOIN dia_order_row ON row_ord_id = ord_id AND row_prd_id = prd_id AND row_type = 'stock'
					LEFT JOIN
						dia_stock_row
					ON
						sto_prd_id = prd_id 
					AND sto_grp_id = ".$this->_variables->public->grp_id : "")."
			where
				".($prd_ids ? "prd_id in (".$prd_ids.") and" : "")." 
				prd_org_id = ".$this->_variables->public->org_id." and 
				(prd_startdate is null or prd_startdate <= now()) and 
				(prd_enddate is null or prd_enddate >= now()) 
				".($filter ? "and (l1.lbl_label like '%".$filter."%' or l2.lbl_label like '%".$filter."%' or prd_code like '%".$filter."%')" : "")."
				".($this->_variables->public->grp_id ? "GROUP BY prd_id" : "")."

			order by 
				".$order."
		", $offset, $limit);

	} // _getProducts

}

/**
 *	Single function which needs a recordset as an argument and returns an array of the complete result of the recordset
 *
 * @access public
 * @param  Recordset $rs De recordset
 * @param  boolean $key_as_index De key die als index moet fungeren
 * @param  boolean $single_row Een Rij?
 * @return mixed
 **/
function rs2arr(&$rs, $key_as_index=false, $single_row=false) {

	$new_arr = array();

	while ($r = $rs->row()) {

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

		if (count($r) == 1) {
			$value = current($r);
		} elseif (count($r) == 2 && $key_as_index !== false) {
			$tmp_r = $r;
			unset($tmp_r[$key_as_index]);
			$value = current($tmp_r);
		} else {
			$value = $r;
			
		}
		if ($key_as_index && isset($r[$key_as_index])) {
			$new_arr[$r[$key_as_index]] = $value;
		} else {
			$new_arr[] = $value;
		}		

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

	return ($single_row) ? current($new_arr) : $new_arr;
}

function array_values_multi(&$arr, $key) {
	$return = array();

	foreach ($arr as $item) {

		foreach ($item as $index => $value) {
			if ($index == $key) {
				$return[] = $value;
			}
		}
	}

	return $return;

}

?>