<?php
require_once "app/class-record.php";
require_once "app/class-recordset.php";
require_once "app/class-user-manager.php";
require_once "app/class-wf-engine.php";

/**
 * Context for record consolidation
 *
 * Supports record consolidation operations for creating master records for recordsets
 *
 * @author tm - Advantis
 * @version 1.0.1
 * @package Backend\DataRecords
 */
class context_recordconsolidation extends context {
	public $contextname = "recordconsolidation";
	
	/**
	 * Constructor method
	 *
	 * validates authorization for the user in session based on the current role
	 */
	function context_recordconsolidation() {
		main::check_auth_session ();
	}
	
	/**
	 * default action for this context
	 */
	function index() {
		$bakkey = Navigation::resolve_step ( $this );
		
		$navkey = Navigation::set_step ( $this->contextname, Navigation::BACKPOST_TYPE_GET );
		
		$uid = (isset ( $_POST ['uid'] )) ? $_POST ['uid'] : $_GET ['uid'];
		
		if (! isset ( $uid )) {
			LogManagement::log ( "edit recorset error : invalid id", "update", "Recordset", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
		} else {
			$rs = new Recordset ( $uid );
			
			$recordlist = $rs->get_members (); 
			
			$list1 = array ();
			$list2 = array ();
			$list_questions_rs = array ();
			$values = array ();
			
			foreach ( $recordlist as $record ) {
				
				$item = new Entity ( 'vw_responses', $record->record_id );
				
				$item->reliabilitycodeid = $record->reliabilitycodeid;

				$item->datefrom = $record->validfrom;
				array_push ( $list1, $item );
				
				$em = new EntityManager ( 'vw_responsesdetail' );
				
				$items = $em->load ( 'responserecordid = :recordid', array( ':recordid' => $record->record_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 );
				}
			}
			
			// get recordset results
			$em = new EntityManager ( Recordset::QUESTIONS );
			
			$listqrs = $em->load ( 'recordsetid = :rsid', array(':rsid' => $rs->id ));
			foreach ( $listqrs as $el ) {
				$list_questions_rs [$el->questionid] = $el->responserecordid;
			}
			
			$wfe = new WFEngine ();
			$role = SESSION::get_activerole ()->role_code;
			
			$listStates = $wfe->get_wf_recordset_next_states ( $role, $rs->statuscodeid, $rs->id );
			
			uasort($list2, "compareSequence");
			
			$this->screen ( $this->contextname . "/index", array (
					'recordset' => $rs,
					'list1' => $list1,
					'list2' => $list2,
					'values' => $values,
					'pvars' => $pvars,
					'bakkey' => $bakkey,
					'list_questions_rs' => $list_questions_rs,
					'states' => $listStates 
			) );
		}
	}
	
	/**
	 * Saves new masterrecord, updates data for masterrecord, saves status for record
	 */
	function saverecordset() {
		$tainted = $_POST ['tainted'];
		
		if ($_POST) { 
			$recordset = new Recordset ( $_POST ['uid'] );
			
			$needrollback = false;
			try {
				
				Transaction::beginTransaction ();
				
				if (! isset ( $_POST ['masterid'] ) || $_POST ['masterid'] == '') { // insert
					
					$um = new UserManager ();
					
					$tainted = 1;
					
					$listrecords = $recordset->get_members ();
					
					$record = new DataRecord ();
					$record->setNewMaster ( $listrecords [0]->record_statisticaltypeid, $um->get_userid_in_session (), $recordset->id );
					
					$em = new EntityManager ( DataRecord::BASEENTITY );
					$record = $em->create ( $record );
					
					$record->createHistory ();
					
					$recordset->masterrecordid = $record->id;
					$recordset->save ();
					
					$recordset->createHistory ();
				} else {
					$record = new DataRecord ( $_POST ['masterid'] );
				}
				// if tainted
				
				if ($tainted == 1) {
					// update Values -
					$da = new DataAccess ();
					
					$prerecords = array ();
					$recordsK = array ();
					$recordsV = array ();
					$unknowns = array ();
					
					foreach ( $_POST as $key => $value ) {
						$pieces = explode ( "_", $key );
						if ($pieces [0] == 'rsp') {
							if ($value == 'UNK') {
								array_push ( $unknowns, $pieces [1] );
							} else {
								if (! array_key_exists ( $value, $prerecords )) {
									$prerecords [$value] = array ();
								}
								array_push ( $prerecords [$value], $pieces [1] );
							}
						}
					}
					foreach ( $prerecords as $key => $value ) {
						array_push ( $recordsK, $key );
						array_push ( $recordsV, "\"{" . implode ( ',', $value ) . "}\"" );
					}
					
					$args = array ();
					array_push ( $args, $da->helper_args ( 'recordid', $record->id, $da::TYPE_INTEGER ) );
					array_push ( $args, $da->helper_args ( 'languageid', Session::get_language ()->id, $da::TYPE_INTEGER ) );
					array_push ( $args, $da->helper_args ( 'responsesK', "{" . implode ( ',', $recordsK ) . "}", $da::TYPE_TEXT ) );
					array_push ( $args, $da->helper_args ( 'responsesV', "{" . implode ( ',', $recordsV ) . "}", $da::TYPE_TEXT ) );
					array_push ( $args, $da->helper_args ( 'unknowns', "{" . implode ( ',', $unknowns ) . "}", $da::TYPE_TEXT ) );
					array_push ( $args, $da->helper_args ( 'recordsetid', $recordset->id, $da::TYPE_INTEGER ) );
					
					$sql = "select base.updateMasterRecordresponses(:recordid, :languageid, :unknowns, :responsesK, :responsesV, :recordsetid)";
					
					$strreturn = $da->func_get ( $sql, $args );
					
					// TODO : $strreturn stdClass Object $strreturn->updatemasterrecordresponses != '' ERROR
				}
				
				$wfe = new WFEngine ();
				$role = SESSION::get_activerole ()->role_code;
				$listStates = $wfe->get_wf_recordset_next_states ( $role, $recordset->statuscodeid ,$_POST ['uid']);
				
				$step = $wfe::search_step ( $listStates, $_POST ['recordsettatus'] );
				
				if ($step != null) {
					
					unset ( $recordset->loglevelid );
					$recordset->statuscodeid = $_POST ['recordsettatus'];
					$recordset->save ();
					
					$recordset->createHistory ();
					
					$wfe->run_postaction_step ( $step );
				} else { // error
					$needrollback = true;
				}
				
				//update organisationid e validfrom do masterrecord
				
					$da = new DataAccess();
					
					//organizationid
					$result = $da->query("select base.recordsetquestions.responserecordid,base.responserecords.organisationid from base.vw_responsesdetail  inner join base.recordsetquestions on 
								base.vw_responsesdetail.questionid = base.recordsetquestions.questionid inner join base.responserecords on base.recordsetquestions.responserecordid = base.responserecords.id
								where base.vw_responsesdetail.responserecordid = :responserecordid
								and umlcode = 'organisationName' 
								and base.recordsetquestions.recordsetid = :recordsetid", array(":responserecordid" => $record->id ,":recordsetid"=> $_POST ['uid']));
					
					if ( $result[0]["organisationid"])							
						$record->organisationid = $result[0]["organisationid"];
					
					//validfrom
					$result = $da->query("select base.recordsetquestions.responserecordid,base.responserecords.validfrom from base.vw_responsesdetail  inner join base.recordsetquestions on
								base.vw_responsesdetail.questionid = base.recordsetquestions.questionid inner join base.responserecords on base.recordsetquestions.responserecordid = base.responserecords.id
								where base.vw_responsesdetail.responserecordid = :responserecordid
								and umlcode = 'validFrom'
								and base.recordsetquestions.recordsetid = :recordsetid", array(":responserecordid" => $record->id ,":recordsetid"=> $_POST ['uid']));
					
					if ( $result[0]["validfrom"])
						$record->validfrom = $result[0]["validfrom"];
					
						
					$record->save();
					
				//----------------------------------------------------
				
				
				if ($needrollback) {
					Transaction::rollback ();
					
					$rsp = getError ( "msg_error_save_recordset" );
					
					Navigation::set_step ( $_POST [Navigation::NEXTKEY], Navigation::BACKPOST_TYPE_GET, $rsp );
					
					LogManagement::log ( "save Recordset error : parameters error", "update", "Recordsets", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				} else {
					Transaction::commit ();
					
					LogManagement::log ( "Save recorsetd data " . $recordset->id, "update", "Recordsets", __LOGTYPE_DATA );
				}
				
				header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
				
			} catch ( Exception $exp ) {
				Transaction::rollback ();
				dump_errorlog ( $this->context, 'saverecordset', $exp->getMessage () );
			}
			
			header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
		}
	}
}

function compareSequence($a,$b) {

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

}

?>
