<?php

class Export_xml extends View {

	public function array_to_xml( $data, &$xml_data, $depth, $node_id = '', $xmlhtml = FALSE ) {
		$attribute = array();
		unset($this->depth[$depth]);
		$this->depth[$depth] = &$data;
		foreach( $data as $key => $value ) {
			if (substr($key, 0, 1) == '@') {
				$attribute[substr($key, 1)] = $value;
			}
		}
		if ($node_id != '' && !count($attribute)) $attribute['id'] = $node_id;
		foreach($attribute as $akey => $avalue) {
			$xml_data->addAttribute($akey, $avalue);
		}
		
		foreach( $data as $key => $value ) {
			if (substr($key, 0, 1) == '@') continue;
			$theid = '';
			if (is_numeric($key)) {
				$theid = "item_$key"; $key = 'item';
			}
			if( is_array($value) ) {
				if ($key === '') $key = 'unknown';
				$subnode = $xml_data->addChild($key);
				$this->array_to_xml($value, $subnode, $depth + 1, $theid, $xmlhtml);
			} else {
				$subnode = $xml_data->addChild($key, htmlspecialchars($value));
			}
			
			if ($xmlhtml && isset($this->outputclass->links[$key])) {
				$macro = $this->_ExpandMacro($this->outputclass->links[$key], $data, $depth);
				$subnode->addAttribute('href', $macro);
			}
			
		}
	}
	
	// only if not a simple view
	private function _EvaluateArray($return, $current_depth) {
		$temp = $this->depth;
		$elements = explode('/', $return);
		foreach($elements as $element) {
			if ($element == '..') {
				if ($current_depth > 0) $current_depth--;
			} elseif (isset($temp[$current_depth][$element])) {
				if (is_array($temp[$current_depth][$element])) {		// untested
					$temp = array_slice($temp, 0, $current_depth + 1);
					$current_depth++;
					$temp[$current_depth] = &$temp[$current_depth][$element];
				} else {
					return $temp[$current_depth][$element];
				}
			} else {
				return $element;
			}
		}
		return '';
	}

	private function _ExpandMacro($macrotext, $data, $depth) {
		$this->x_datarow = $data;
		$macrotext = preg_replace_callback('~\{(.*?)\}~', function ($match) use ($depth) {
			$return = trim(strtolower($match[1]));
			if (isset($this->x_datarow[$return])) {
				return $this->x_datarow[$return];
			} else {
				return $this->_EvaluateArray($return, $depth);
			}
		}, $macrotext);

		return $macrotext;
	}
	
	public function render($data) {
		header('Content-type: text/plain; charset=UTF-8');		// wrong type
		$xml_data = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><data></data>');
		if ($data == NULL) {
			$data = ['status' => 'error', 'message' => 'data cannot be null'];
		}
		$this->depth = [];
		$this->array_to_xml($data, $xml_data, 0);

		//		return $xml_data->asXML();
		$dom = dom_import_simplexml($xml_data)->ownerDocument;
		$dom->formatOutput = TRUE;
		echo $dom->saveXML();
	}
}