<?php

class Export_Csv extends View {

// if a simple table has been created, use DataTables to display it
	public function render($data) {
		header('Content-type: text/plain; charset=UTF-8');
		reset($data);
		$k = key($data);
		if (!is_array($data[$k])) {		// simple array
			$data = $this->_convert_to_table($data);
		}
		echo $this->_CreateDataTablesPage($data);
	}
	
	private function _convert_to_table($data) {
		$output = array();
		foreach($data as $key => $value) {
			$output[] = array('key' => $key, 'value' => $value);
		}
		return $output;
	}
	
	private function _CreateDataTablesPage($data) {
		reset($data);
		$key = key($data);
		$fieldnames = array_keys($data[$key]);
		$c = count($fieldnames);
		$titlerow = '';
		foreach($fieldnames as $index => $fieldname) {
			if ($titlerow != '') $titlerow .= ',';
			$titlerow .= $this->_exportField($fieldname);
		}
		$body = '';
		foreach($data as $datarow) {
			$line = '';
			foreach($fieldnames as $index => $fieldname) {
				if ($line != '') $line .= ',';
				$line .= $this->_exportField($datarow[$fieldname]);
			}
			$body .= "$line\n";
		}
		
		return "$titlerow\n$body";
	}
	
	private function _exportField($item) {
		if ($item === NULL) return '\\N';
		if (is_numeric($item)) return $item;
		if (is_array($item)) $item = serialize($item);
		return '"' . addslashes($item) . '"';
	}
}