<?php
require_once "app/class-record.php";
require_once "app/class-cluster.php";
require_once "app/class-cluster-member.php";
require_once "app/class-user-manager.php";
require_once "app/class-recordset.php";
require_once "app/class-wf-engine.php";
require_once 'includes/data-access/class-transaction.php';

/**
 * ClusterDetail Context
 *
 * Context for cluster detail managment
 *
 * @author tmouzinho - Advantis Solutions
 * @version 1.0.1
 * @package Backend\Clusters
 */
class context_clusterdetail extends context {
	public $contextname = "clusterdetail";
	
	/**
	 * Constructor & Authorization
	 */
	function context_clusterdetail() {
		main::check_auth_session ();
	}
	
	/**
	 * Default action shows cluster detail by id
	 */
	function index() {
		$bakkey = Navigation::resolve_step ( $this );
		
		$navkey = Navigation::set_step ( $this->contextname, Navigation::BACKPOST_TYPE_GET );
		
		if (! isset ( $_GET ['cid'] )) {
			
			LogManagement::log ( "cluster detail error : inexisting cluster index", "create", "Clusters", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
		} else {
			
			$cluster = new Cluster ( $_GET ['cid'] );
			
			$listmembers = $cluster->get_members ();
			
			$wfe = new WFEngine ();
			$role = SESSION::get_activerole ()->role_code;
			
			$listStates = $wfe->get_wf_cluster_next_states ( $role, $cluster->statuscodeid );
			
			foreach ( $listmembers as $member ) {
				$member->listStatus = $wfe->get_wf_clustermember_next_states ( $role, $member->clustermembers_statuscodeid, $cluster->id );
			}
			
			$this->screen ( $this->contextname . "/index", array (
					'list' => $listmembers,
					'item' => $cluster,
					'pvars' => $pvars,
					'navkey' => $navkey,
					'bakkey' => $bakkey,
					'states' => $listStates 
			) );
		}
	}
	
	/**
	 * Creates new cluster via POST
	 */
	function newcluster() {
		$listrecords = get_ck_list_ids ( $_POST );
		$listrecordsvalid = false;
		
		if (count ( $listrecords ) > 1) {
			
			$em = new EntityManager ( DataRecord::LISTVIEW );
			$list = $em->load ( "id in (" . implode ( ",", $listrecords ) . ")" );
			
			foreach ( $list as $item ) {
				$listrecordsvalid = (! isset ( $item->clusterid ) && $item->statuscodeid == __RECORD_STATUS_VALID);
				if (! $listrecordsvalid)
					break;
			}
		}
		
		if (! $listrecordsvalid) { // invalid record list to create new cluster
			
			$rsp = getError ( "msg_error_invalid_records_new_cluster" );
			
			Navigation::set_step ( $_POST [Navigation::NEXTKEY], Navigation::BACKPOST_TYPE_POST, $rsp );
			
			LogManagement::log ( "create cluster error : one or more selected records not available for clustering", "create", "Clusters", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
		} else {
			// new cluster
			
			try {
				$needrollback = false;
				Transaction::beginTransaction ();
				
				$um = new UserManager ();
				
				$da = new DataAccess ();
				
				$cluster = new Cluster ();
				$annotation = "";
				$cluster->setNew ( __CLUSTER_SYSTEM_DETECTION_PROCESS_INTERACTIVE, __CLUSTER_PRIORITY_MEDIUM, $um->get_userid_in_session (), $annotation );
				
				$em = new EntityManager ( $cluster::BASEENTITY );
				$cluster = $em->create ( $cluster );
				
				if (isset ( $cluster->id )) {
					
					if ($cluster->createHistory ()) {
						// Members
						if (! $cluster->createMembers ( $listrecords )) {
							// error creating members
							$needrollback = true;
						} else { // ALL OK
							$_GET ['cid'] = $cluster->id;
						}
					} else {
						$needrollback = true;
						// Error on history creation and Logo
					}
				} else {
					
					// Error creating cluster and log
					$needrollback = true;
				}
				
				if ($needrollback) {
					Transaction::rollback ();
					
					LogManagement::log ( "New Cluster error", "create", "Cluster", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
					
					setNotification ( getError ( "msg_error_new_Cluster" ), Notification::TYPE_ERROR );
					
					header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
				} else {
					Transaction::commit ();
					LogManagement::log ( "New Cluster " . $cluster->id, "create", "Cluster", __LOGTYPE_DATA );
					header ( 'Location:' . __SITEBASE . '/' . 'clusterdetail?cid=' . $cluster->id . '&' . Navigation::get_returnkey () );
				}
			} catch ( Exception $exp ) {
				Transaction::rollback ();
				dump_errorlog ( 'ClusterDetail', 'newcluster', $exp->getMessage () );
				header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
			}
		}
	}
	
	/**
	 * Saves cluster data
	 */
	function savecluster() {
		if ($_POST) {
			try {
				$needrollback = false;
				Transaction::beginTransaction ();
				
				$um = new UserManager ();
				
				$da = new DataAccess ();
				
				$wfe = new WFEngine ();
				$role = SESSION::get_activerole ()->role_code;
				$cluster = new Cluster ( $_POST ['cid'] );
				
				foreach ( $_POST as $key => $value ) {
					
					$pieces = explode ( "_", $key );
					
					if ($pieces [0] == "cmstatus") {
						$clustermember = new ClusterMember ( $pieces [1] );
						
						$listStatus = $wfe->get_wf_clustermember_next_states ( $role, $clustermember->statuscodeid, $clustermember->responserecordid, $cluster->id );
						
						$step = $wfe::search_step ( $listStatus, $value );
						
						if ($step != null) {
							
							$clustermember->statuscodeid = $value;
							$clustermember->save ();
							
							$clustermember->createHistory ();
							
							$wfe->run_postaction_step ( $step );
						} 						// error
						else {
							$rsp = getError ( "msg_error_save_cluster" );
							
							Navigation::set_step ( $_POST [Navigation::NEXTKEY], Navigation::BACKPOST_TYPE_GET, $rsp );
							
							LogManagement::log ( "save cluster error : parameters error", "update", "Clusters", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
							
							header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl () );
						}
					}
				}
				
				$listStates = $wfe->get_wf_cluster_next_states ( $role, $cluster->statuscodeid, $cluster->id );
				
				$step = $wfe::search_step ( $listStates, $_POST ['clusterstatus'] );
				
				if ($step != null) {
					
					if (isset ( $cluster->id )) {
						$cluster->annotation = $_POST ['annotation'];
						$cluster->statuscodeid = $_POST ['clusterstatus'];
						$cluster->prioritycodeid = $_POST ['priority'];
						$cluster->userid = $um->get_userid_in_session ();
						
						$cluster->save ();
						
						$cluster->createHistory ();
						$wfe->run_postaction_step ( $step );
					}
				} else { // error
					$needrollback = true;
				}
				
				$_GET ['cid'] = $cluster->id;
				if ($needrollback) {
					Transaction::rollback ();
					
					LogManagement::log ( "Save Cluster error", "update", "Cluster", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
					setNotification ( getError ( "msg_error_save_cluster" ), Notification::TYPE_ERROR );
					header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
				} else {
					Transaction::commit ();
					LogManagement::log ( "Save Cluster " . $cluster->id, "update", "Cluster", __LOGTYPE_DATA );
					header ( 'Location:' . __SITEBASE . '/' . 'clusterdetail?cid=' . $cluster->id . '&' . Navigation::get_returnkey () );
				}
			} catch ( Exception $exp ) {
				Transaction::rollback ();
				dump_errorlog ( 'ClusterDetail', 'savecluster', $exp->getMessage () );
				header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
			}
		} else { // error no post
			
			$rsp = getError ( "msg_error_save_cluster" );
			
			Navigation::set_step ( $_POST [Navigation::NEXTKEY], Navigation::BACKPOST_TYPE_POST, $rsp );
			
			LogManagement::log ( "save cluster error : parameters error", "update", "Clusters", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
		}
	}
	
	/**
	 * Creates new Recordset via POST
	 */
	function newrecordset() {
		if ($_POST) {
			try {
				$needrollback = false;
				Transaction::beginTransaction ();
				$listrecords = get_ck_list_ids ( $_POST );
				
				$listrecordsvalid = false;
				
				$clusterid = $_POST ['cid'];
				
				$cluster = new Cluster ( $clusterid );
				
				if (count ( $listrecords ) > 1 && isset ( $cluster->statuscodeid ) && $cluster->statuscodeid == __CLUSTER_STATUS_CONFIRMED) {
					$em = new EntityManager ( DataRecord::LISTVIEW );
					$list = $em->load ( "id in (" . implode ( ",", $listrecords ) . ")" );
					
					foreach ( $list as $item ) {
						$listrecordsvalid = ! isset ( $item->recorsetid );
						if (! $listrecordsvalid)
							break;
					}
					
					$em = new EntityManager ( ClusterMember::BASEENTITY );
					$listM = $em->load ( "responserecordid in (" . implode ( ",", $listrecords ) . ") and clusterid = " . $clusterid );
					
					foreach ( $listM as $item ) {
						$listrecordsvalid = ($item->statuscodeid == __CLUSTER_MEMBER_STATUS_DUPLICATE) ? true : false;
						if (! $listrecordsvalid)
							break;
					}
				}
				
				if (! $listrecordsvalid) { // invalid record list to create new cluster
					
					$rsp = getError ( "msg_error_invalid_records_new_recordset" );
					
					Navigation::set_step ( $_POST [Navigation::NEXTKEY], Navigation::BACKPOST_TYPE_GET, $rsp );
					
					LogManagement::log ( "create recordset error : one or more selected records not available for recordset", "create", "Recorsets", __LOGTYPE_DATA,__LOGLEVEL_ERROR );
					
					header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl () );
				} else {
					// new cluster
					
					$um = new UserManager ();
					
					$rs = new Recordset ();
					$rs->setNew ( $clusterid, $um->get_userid_in_session () );
					
					$em = new EntityManager ( $rs::BASEENTITY );
					
					$rs = $em->create ( $rs );
					
					if ($rs->id) {
						foreach ( $listrecords as $recordid ) {
							$record = new DataRecord ( $recordid );
							$record->recordsetid = $rs->id;
							
							$record->save ();
							
						}
					} else {
						$needrollback = true;
					}
					if ($needrollback) {
						Transaction::rollback ();
						
						LogManagement::log ( "Save Cluster error", "update", "Cluster", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
						setNotification ( getError ( "msg_error_new_recordset" ) , Notification::TYPE_ERROR);
						header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
						exit();
					} else {
						Transaction::commit ();
						LogManagement::log ( "Create Recordset" . $rs->id, "create", "Recordset", __LOGTYPE_DATA );
						header ( 'Location:' . __SITEBASE . '/' . 'recordconsolidation?uid=' . $record->recordsetid . '&' . Navigation::get_returnkey () );
						exit();
					}
					
					header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl () );
				}
			} catch ( Exception $exp ) {
				Transaction::rollback ();
				dump_errorlog ( 'ClusterDetail', 'newrecordset', $exp->getMessage () );
				header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
			}
		} else { // error no post
			
			$rsp = getError ( "msg_error_new_recordset" );
			
			Navigation::set_step ( $_POST [Navigation::NEXTKEY], Navigation::BACKPOST_TYPE_POST, $rsp );
			
			LogManagement::log ( "new recordset error : parameters error", "create", "Recordset", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			header ( 'Location:' . __SITEBASE . '/' . Navigation::get_backurl ( $this->contextname ) );
		}
	}
}

?>