<?php header('Content-type: application/xml; charset=UTF-8;'); ?>
<?php
	// Load the changed data and the stylesheet into domdocuments.
	$changes_bxml = new DomDocument('1.0','UTF-8');
	$changes_bxml->loadXML(preg_replace('/&([^\w])/','&amp;$1',$GLOBALS['HTTP_RAW_POST_DATA']));
	$xsl = new DomDocument('1.0','UTF-8');
	$xsl->load("data/bxml2xml_standard.xsl");

	// Create the processor and import the stylesheet.
	$proc = new XsltProcessor();
	$xsl = $proc->importStylesheet($xsl);
	
	// Transform the changes from BXML to XML.
	$changes_xml = $proc->transformToDoc($changes_bxml);
	
	// Load the original data into a domdocument.
	$original_xml = new DomDocument('1.0','UTF-8');
	$original_xml->load("data/filmdata.xml");
	
	// Remove from the original document all films that were changed,
	// and copy into the original document all changed films that were not deleted.
	$cfilms = $changes_xml->getElementsByTagName('film');
	$opath = new DOMXPath($original_xml);
	foreach($cfilms as $cfilm){
		$ofilm = $opath->query("//film[@film-id='".$cfilm->getAttribute('film-id')."']")->item(0);
		if($ofilm) $original_xml->firstChild->removeChild($ofilm);
		if($cfilm->getAttribute('changed') != 'deleted'){
			$cfilm->removeAttribute('changed');
			$original_xml->firstChild->appendChild($original_xml->importNode($cfilm, true));
		}
	}

	// Save the document to a file and send a response.
	$original_xml->save("data/filmdata_new.xml");
	print('<response>New number of films is: ' . $original_xml->getElementsByTagName('film')->length . "</response>\n");
?>