<?php
/**
 * Export Manager
 *
 * Performs XML FILE Data Exports
 * @author ba - Advantis Solutions
 * @version 1.0.1
 * @package Backend\Files
 */
class ExportManager extends context {
	
	/**
	 */
	function victims() {
		$em = new EntityManager ( 'publishfiles' );
		
		$obj = new stdClass ();
		
		$time = time ();
		
		$obj->creationdate = $time;
		$obj->statisticaltypeid = __STATISTICAL_TYPE_VICTIMS;
		$obj->efporgid = __NFP_CODE;
		$obj->userid = Session::get_user ()->id;
		
		$obj = $em->create ( $obj );
		
		$em = new EntityManager ( 'publish_victims' );
		
		$list = $em->load ();
		
		$this->exportXML ( $list, 'victims', $obj->id, $time );
	}
	/**
	 */
	function traffickers() {
		$em = new EntityManager ( 'publishfiles' );
		
		$obj = new stdClass ();
		
		$time = time ();
		
		$obj->creationdate = $time;
		$obj->statisticaltypeid = __STATISTICAL_TYPE_TRAFFICKERS;
		$obj->efporgid = __NFP_CODE;
		
		if (Session::get_user ()) {
			
			$obj->userid = Session::get_user ()->id;
		}
		
		$obj = $em->create ( $obj );
		
		$em = new EntityManager ( 'publish_traffickers' );
		
		$list = $em->load ();
		
		$this->exportXML ( $list, 'traffickers', $obj->id, $time );
	}
	
	/**
	 *
	 * @param unknown $list        	
	 * @param unknown $type        	
	 * @param unknown $id        	
	 * @param unknown $time        	
	 */
	function exportXML($list, $type, $id, $time) {
		$result = '<root fromyear=% toyear=% date=\'' . $time . '\' type=\'' . $type . '\'>' . PHP_EOL;
		
		$minyear = null;
		$maxyear = null;
		
		foreach ( $list as $item ) {
			
			$result .= '<record>' . PHP_EOL;
			
			foreach ( $item as $key => $value ) {
				
				/* min - max date calculation */
				
				if ($key == 'yearfrom') {
					if ($minyear == null || $value < $minyear)
						$minyear = $value;
					if ($maxyear == null || $value > $maxyear)
						$maxyear = $value;
				}
				
				/* -------------------- */
				
				if ($value && $key != 'internal_name') {
					
					$result .= '<' . $key . '>';
					$result .= $value;
					$result .= '</' . $key . '>' . PHP_EOL;
				}
			}
			
			$result .= '</record>' . PHP_EOL;
		}
		
		// * year max and min on root node */
		$result = str_replace ( 'fromyear=%', "fromyear='$minyear'", $result );
		$result = str_replace ( 'toyear=%', "toyear='$minyear'", $result );
		/**
		 * --------------------
		 */
		
		$result .= '</root>';
		
		$filename = $id;
		
		$basepath = __EXPORT_FILE_PATH;
		
		$NFP_CODE = __NFP_CODE;
		
		$path = $basepath . '/' . $NFP_CODE . '/' . $type;
		
		if (! file_exists ( $basepath . '/' . $NFP_CODE )) {
			mkdir ( $basepath . '/' . $NFP_CODE, true );
		}
		
		if (! file_exists ( $path )) {
			mkdir ( $path, true );
		}
		
		// echo $path.'/'.$filename;
		
		$file = fopen ( $path . '/' . $filename, "w" ) or die ( "Unable to open file!" );
		
		fwrite ( $file, $result );
		
		fclose ( $file );
	}
}