<?php
/**
 * DataRecord Context
 *
 * Context for NFP comparing operations on data records
 * @author tm - Advantis
 * @version 1.0.1
 * @package Backend\DataRecords
 */
class context_comparerecords extends context {
	public $contextname = "comparerecords";
	
	/**
	 * Constructor & Authorization
	 */
	function context_comparerecords() {
		main::check_auth_session ();
	}
	 
	/**
	 * Default action expects POST with ids of the Data Records to compare
	 */
	function index() {
		$bakkey = Navigation::resolve_step ( $this );
		
		$uid = get_ck_list_ids ( $_POST ); // list of records
		
		$list1 = array ();
		$list2 = array ();
		$values = array ();
		
		if (! isset ( $uid ) || count ( $uid ) < 2) {
			
			LogManagement::log ( "Compare records error", "display", "Records", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			setNotification ( getError ( "msg_comparerecords_insuficient" ), Notification::TYPE_ERROR );
			
			header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl () );
		} else {
			
			foreach ( $uid as $id ) {
				
				$item = new Entity ( 'vw_responses', $id );
				
				array_push ( $list1, $item );
				
				$em = new EntityManager ( 'vw_responsesdetail' );
				
				$items = $em->load ( 'responserecordid = :id', array(':id' => $id ) );
				
				foreach ( $items as $item ) {
					
					$list2 [$item->questionid] = $item;
					
					if (! $values [$item->responserecordid . '_' . $item->questionid]) {
						
						$values [$item->responserecordid . '_' . $item->questionid] = array ();
					}
					$value = '';
					if ($item->codelist_descriptioncode) {
						$value = D ( $item->codelist_descriptioncode );
					} else {
						$value = $item->originalvalue;
					}
					array_push ( $values [$item->responserecordid . '_' . $item->questionid], $value );
				}
			}
		}
		
		uasort($list2, "compareSequence");
		
		$this->screen ( $this->contextname . "/index", array (
				'list1' => $list1,
				'list2' => $list2,
				'values' => $values,
				'pvars' => $pvars,
				'bakkey' => $bakkey 
		) );
	}
	
	
}

function compareSequence($a,$b) {

	if(  $a->sequence ==  $b->sequence ){ return 0 ; }
	return ($a->sequence < $b->sequence) ? -1 : 1;

}
?>
