<?php header('Content-type: application/xml; charset=UTF-8;'); ?>
<?php
	// Load the changed data into a domdocument.
	$xml_src = $_POST['xmldata'];
	if (get_magic_quotes_gpc()) $xml_src = stripslashes($xml_src);
	$changes_xml = new DomDocument('1.0','UTF-8');
	$changes_xml->loadXML($xml_src);

	// 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");
?>