<?php
require_once "app/class-lov-manager.php";
require_once "app/class-version.php";
require_once "app/class-data-structures.php";
require_once "app/class-data-structures-questions.php";
require_once "app/class-data-structures-manager.php";

/**
 * Context for LDP managment
 * 
 * Shows and configures Local profiles for Victims and Traffickers
 * @author tm - Advantis
 * @version 1.0.1
 * @package Backend\DataStructures
 */
class context_localprofile extends context {
	
	public $contextname = "localprofile";
	private $baseentity = "datastructuredefinitions";
	private $listentity = "dsdlist";
	
	/**
	 * Constructor method
	 *
	 * validates authorization for the user in session based on the current role
	 */
	function context_localprofile() {
		main::check_auth_session ();
	}
	
	/**
	 * default action for this context
	 */
	function index() {
		if ($_POST ['statisticaltype'] == __STATISTICAL_TYPE_TRAFFICKERS) {
			$this->traffickers ();
		} else {
			$this->victims ();
		}
	}
	
	/**
	 * Presents LDP Victims list
	 */
	function victims() {
		$em = new EntityManager ( $this->listentity );
		
		$list = $em->load ( "datastructuredefinitions_statisticaltypeid=? and datastructuredefinitions_levelcodeid=? order by datastructuredefinitions_id desc", array (
				__STATISTICAL_TYPE_VICTIMS,
				__DSD_LEVEL_LDP 
		) );
		
		$dsdm = new DataStructuresLDPManager ();
		$can_add_new = $dsdm->can_add_new ( __STATISTICAL_TYPE_VICTIMS );
		
		$this->screen ( $this->contextname . "/index", array (
				'page' => 'victims',
				"list" => $list,
				"contextname" => $this->contextname,
				"canaddnew" => $can_add_new 
		) );
	}
	
	/**
	 * Presents LDP Traffickers list
	 */
	function traffickers() {
		$em = new EntityManager ( $this->listentity );
		
		$list = $em->load ( "datastructuredefinitions_statisticaltypeid=? and datastructuredefinitions_levelcodeid=? order by datastructuredefinitions_id desc", array (
				__STATISTICAL_TYPE_TRAFFICKERS,
				__DSD_LEVEL_LDP 
		) );
		
		$dsdm = new DataStructuresLDPManager ();
		$can_add_new = $dsdm->can_add_new ( __STATISTICAL_TYPE_TRAFFICKERS );
		
		$this->screen ( $this->contextname . "/index", array (
				'page' => 'traffickers',
				"list" => $list,
				"contextname" => $this->contextname,
				"canaddnew" => $can_add_new 
		) );
	}
	
	/**
	 * Presents form for new LDP of victims or traffickers
	 *
	 * @param string $page
	 *        	- ['victims','traffickers']
	 */
	function newldp($page, $pvars) {
		$type = ($page == "victims") ? __STATISTICAL_TYPE_VICTIMS : __STATISTICAL_TYPE_TRAFFICKERS;
		
		$edsd = new EntityManager ( $this->baseentity );
		
		// get list NDP for the statisticaltype
		$em = new EntityManager ( $this->listentity );
		
		$listndp = $em->load ( "datastructuredefinitions_statisticaltypeid=? and datastructuredefinitions_levelcodeid=? and versionregistry_validto is null order by datastructuredefinitions_id desc", array (
				$type,
				__DSD_LEVEL_NDP 
		) );
		
		if ($_POST ['ndp_id']) {
			$ndpSelected = $_POST ['ndp_id'];
		} else {
			$ndpSelected = $listndp [0]->datastructuredefinitions_id;
		}
		// get dsd from selected NDP
		
		$eql = new EntityManager ( "dsdquestionlist" );
		$list = $eql->load ( 'dsd_id=?', array (
				$ndpSelected 
		) );
		
		$lm = new LovManager ();
		$listVoid = $lm->getLov_VoidReason ();
		
		$this->screen ( $this->contextname . "/detail", array (
				'ndp' => $ndpSelected,
				'isdraft' => true,
				'listvoid' => $listVoid,
				'listndp' => $listndp,
				'page' => $page,
				"list" => $list,
				"contextname" => $this->contextname 
		) );
	}
	
	/**
	 * Presents form for new victims LDP
	 */
	function newldpvictims($pvars = null) {
		$this->newldp ( "victims", $pvars );
	}
	
	/**
	 * Presents form for new trafickers LDP
	 */
	function newldptraffickers($pvars = null) {
		$this->newldp ( "traffickers", $pvars );
	}
	
	/**
	 * Creates the new LDP int the DB
	 */
	function create() {
		$needrollback = false;
		try {
			
			Transaction::beginTransaction ();
			
			// VERSION
			$version = new Version ();
			$description = $_POST ['description'];
			$version->setNew ( $_POST ['code'], $_POST ['annotation'], $description );
			
			$em = new EntityManager ( $version::BASEENTITY );
			$version = $em->create ( $version );
			
			if ($version->id) { // IF VERSION OK
				
				$dsd = new DataStructures (); // DATASTRUCTURE
				
				$dsd->setNew ( $_POST ['statisticaltype'], $dsd::LEVEL_LDP, $version->id, $_POST ['description'] );
				$dsd->parentid = $_POST ['ndp_id'];
				$em = new EntityManager ( $dsd::BASEENTITY );
				
				$dsd = $em->create ( $dsd );
				
				if ($dsd->id) { // IF DATASTRUCTURE OK
				                
					// DataStructuresQuestions
					$questions = $this->getQuestionsList ( $_POST );
					
					foreach ( $questions as $key => $value ) {
						
						if ($value ['voidreasoncodeid']) {
							$dsdquestion = new DataStructuresQuestions ();
							$dsdquestion->setNew ( $dsd->id, $value ['questionid'], ($value ['voidreasoncodeid'] == $dsdquestion::VOIDCODE) ? 1 : 0, $value ['voidreasoncodeid'] );
							
							$em = new EntityManager ( $dsdquestion::BASEENTITY );
							
							$dsdquestion = $em->create ( $dsdquestion );
						}
					}
					LogManagement::log ( "Create New LDP", "create", "Local Profiles", __LOGTYPE_DATA );
				} else { // error on getting DSD
					$needrollback = true;
				}
			} else { // error on getting version
				$needrollback = true;
			}
			
			if ($needrollback) {
				Transaction::rollback ();
				
				LogManagement::log ( "New LDP error", "create", "Local Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_error_new_LDP" ) , Notification::TYPE_ERROR);
			} else {
				Transaction::commit ();
				
				LogManagement::log ( "New LDP " . $dsd->id, "create", "Local Profiles", __LOGTYPE_DATA );
				
				setNotification ( getSuccess ( "msg_new_LDP_ok" ) );
			}
			
			LogManagement::log ( "Create new LDP", "create", "Local Profiles", __LOGTYPE_DATA );
			
			header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
		} catch ( Exception $exp ) {
			Transaction::rollback ();
			dump_errorlog ( $this->context, 'create', $exp->getMessage () );
			
			setNotification ( getError ( "msg_error_new_LDP" ), Notification::TYPE_ERROR );
			
			header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
		}
	}
	
	/**
	 * Preparares array from POST as as questions lists checked selected and hidden inputs
	 * for edit and save purposes
	 *
	 * @param array $arrPost
	 *        	- normally $_POST
	 *        	expects : 'ck_'.questions_code
	 *        	'sel_voidreason_'.questions_code
	 *        	'h_ck_'.questions_code
	 * @return Array <string question_code <['voidreasoncodeid']= string, ['questionid']= string>
	 */
	private function getQuestionsList($arrPost) {
		$retArr = array ();
		foreach ( $arrPost as $key => $value ) {
			
			$pieces = explode ( "_", $key );
			if ($pieces [0] == "ck") {
				if (! array_key_exists ( $pieces [1], $retArr )) {
					$retArr [$pieces [1]] = array (
							'questionid' => $value 
					);
				}
				$retArr [$pieces [1]] ['questionid'] = $value;
			}
			
			if ($pieces [0] == "sel") {
				if (! array_key_exists ( $pieces [2], $retArr )) {
					$retArr [$pieces [2]] = array (
							'voidreasoncodeid' => $value 
					);
				}
				$retArr [$pieces [2]] ['voidreasoncodeid'] = $value;
			}
			
			if ($pieces [0] == "h") {
				if (! array_key_exists ( $pieces [2], $retArr )) {
					$retArr [$pieces [2]] = array (
							'questionid' => $value 
					);
				}
				$retArr [$pieces [2]] ['questionid'] = $value;
			}
		}
		
		return $retArr;
	}
	
	/**
	 * Prepares LDP for editing
	 *
	 * @param string $newid        	
	 */
	function edit($newid = null) {
		$dsd = null;
		if ($_REQUEST ["id"]) {
			$dsd = new DataStructures ( $_REQUEST ["id"] );
		} else {
			$dsd = new DataStructures ( $newid );
		}
		
		$page = ($dsd->statisticaltypeid == __STATISTICAL_TYPE_VICTIMS) ? "victims" : "traffickers";
		
		$type = ($page == "victims") ? __STATISTICAL_TYPE_VICTIMS : __STATISTICAL_TYPE_TRAFFICKERS;
		
		// get dsd from selected NDP
		
		$eql = new EntityManager ( "dsdquestionlist" );
		$list = $eql->load ( 'dsd_id=?', array (
				$dsd->parentid 
		) );
		
		$lm = new LovManager ();
		$listVoid = $lm->getLov_VoidReason ();
		
		$em = new EntityManager ( $this->listentity );
		$listndp = $em->load ( "datastructuredefinitions_statisticaltypeid=? and datastructuredefinitions_levelcodeid=? and versionregistry_validto is null order by datastructuredefinitions_id desc", array (
				$type,
				__DSD_LEVEL_NDP 
		) );
		
		$version = new Version ( $dsd->versionregistryid );
		
		$dsdm = new DataStructuresLDPManager ();
		$cangolive = $dsdm->can_go_live ( $dsd );
		$candisable = $dsdm->can_be_disabled ( $dsd );
		$isdraft = $dsdm->is_draft ( $dsd );
		$listEdit = $dsdm->get_questions ( $dsd );
		
		$this->screen ( $this->contextname . "/detail", array (
				'version' => $version,
				'dsd' => $dsd,
				'listvoid' => $listVoid,
				'ndp' => $dsd->parentid,
				'cangolive' => $cangolive,
				'candisable' => $candisable,
				'isdraft' => $isdraft,
				'page' => $page,
				"list" => $list,
				"listedit" => $listEdit,
				'listndp' => $listndp,
				"contextname" => $this->contextname 
		) );
	}
	
	/**
	 * Saves editing data for LDP
	 */
	function save() {
		$needrollback = false;
		try {
			
			Transaction::beginTransaction ();
			if ($_POST ["id"]) {
				
				$dsd = new DataStructures ( $_REQUEST ["id"] );
				
				if ($dsd) {
					
					$version = new Version ( $dsd->versionregistryid );
					$version->code = $_POST ['code'];
					$version->annotation = $_POST ['annotation'];
					$description = $_POST ['description'];
					$version->save ();
					
					$dsd->description = $_POST ['description'];
					
					if ($dsd->active != 1) {
						$dsd->active = 0;
					}
					$dsd->save ();
					
					// clean child questions
					$da = new DataAccess ();
					$cfgdb = new ConfigDB ();
					$schema = $cfgdb->connections ["DEFAULT"] ["DBSCHEMA"];

					$da->query ("DELETE FROM " . $schema . ".dsdquestions WHERE datastructuredefinitionid=:datastructuredefinitionid", array(':datastructuredefinitionid' => $dsd->id  ));
					
					$questions = $this->getQuestionsList ( $_POST );
					
					foreach ( $questions as $key => $value ) {
						
						if (isset ( $value ['voidreasoncodeid'] )) {
							$dsdquestion = new DataStructuresQuestions ();
							$dsdquestion->setNew ( $dsd->id, $value ['questionid'], ($value ['voidreasoncodeid'] == $dsdquestion::VOIDCODE) ? 1 : 0, $value ['voidreasoncodeid'] );
							
							$em = new EntityManager ( $dsdquestion::BASEENTITY );
							
							$dsdquestion = $em->create ( $dsdquestion );
						}
					}
				} else { //  error gettin dsd
					$needrollback = true;
				}
			} else { // error no getting id
				$needrollback = true;
			}
			
			if ($needrollback) {
				Transaction::rollback ();
				LogManagement::log ( "Edit Draft LDP " . $_POST ["id"] . " error", "update", "Local Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_save_LDP_error" ) , Notification::TYPE_ERROR);
			} else {
				Transaction::commit ();
				
				LogManagement::log ( "Edit Draft LDP " . $_POST ["id"], "update", "Local Profiles", __LOGTYPE_DATA );
				
				setNotification ( getSuccess ( "msg_save_LDP_ok" ) );
			}
			
			header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
		} catch ( Exception $exp ) {
			Transaction::rollback ();
			dump_errorlog ( $this->context, 'edit', $exp->getMessage () );
			
			setNotification ( getError ( "msg_error_save_LDP" ), Notification::TYPE_ERROR );
			
			header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
		}
	}
	
	/**
	 * Turns NDP Live
	 */
	function golive() {
		if ($_REQUEST ["id"]) {
			
			$dsd = new DataStructures ( $_REQUEST ["id"] );
			
			if ($dsd) {
				
				$dsdm = new DataStructuresLDPManager ();
				
				if ($dsdm->can_go_live ( $dsd )) {
					if ($dsdm->go_live ( $dsd )) {
						// Msg sucess
						LogManagement::log ( "Turn LDP Live", "update", "Local Profiles", __LOGTYPE_DATA );
						setNotification ( getSuccess ( "msg_GOLIVE_LDP_ok" ) );
					} else {
						
						// Msg error
						LogManagement::log ( "Turn LDP Live error", "update", "Local Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
						setNotification ( getError ( "msg_GOLIVE_LDP_error" ), Notification::TYPE_ERROR );
					}
				} else {
					// warning can't ?
					LogManagement::log ( "can't go live LDP " . $_REQUEST ["id"], "update", "Local Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				}
			}
		}
		
		header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
	}
	
	/**
	 * Disables LDP
	 */
	function disable() {
		if ($_REQUEST ["id"]) {
			
			$dsd = new DataStructures ( $_REQUEST ["id"] );
			
			if ($dsd) {
				$dsdm = new DataStructuresLDPManager ();
				if ($dsdm->can_be_disabled ( $dsd )) {
					if ($dsdm->disable ( $dsd )) {
						
						// Msg sucess
						LogManagement::log ( "Disable LDP", "update", "Local Profiles", __LOGTYPE_DATA );
						setNotification ( getSuccess ( "msg_disable_LDP_ok" ) );
					} else {
						
						// Msg error
						LogManagement::log ( "Disable LDP error", "update", "Local Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
						setNotification ( getError ( "msg_error_disable_LDP" ), Notification::TYPE_ERROR );
					}
				} else {
					// warning can't
					LogManagement::log ( "Can't Disable LDP " . $_REQUEST ["id"], "update", "Local Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				}
			}
		}
		
		header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
	}

	/**
	 * Saves new NDP from another Version for editing
	 */
	function savenewversion() {
		$shownew = false;
		if ($_REQUEST ["id"]) {
			
			$dsd = new DataStructures ( $_REQUEST ["id"] );
			
			if ($dsd) {
				$dsdm = new DataStructuresLDPManager ();
				$newdsdid = $dsdm->save_new_from ( $dsd );
				
				if (isset ( $newdsdid )) {
					
					LogManagement::log ( "Save new Draft LDP from other LDP", "create", "Local Profiles", __LOGTYPE_DATA );
					setNotification ( getSuccess ( "msg_savenew_LDP_ok" ) );
					$shownew = true;
				} else {
					LogManagement::log ( "Save new Draft LDP from other LDP error", "create", "Local Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
					setNotification ( getError ( "msg_error_savenew_LDP" ), Notification::TYPE_ERROR );
				}
			}
		}
		
		if ($shownew) {
			header ( 'Location:' . __SITEBASE . '/' . $this->contextname . '/edit?id=' . $newdsdid );
		} else {
			header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
		}
	}
	
	/**
	 * Prepares return navigation to parent list with correct navigation
	 *
	 * @param int $statisticaltypeid        	
	 * @return string
	 */
	function getparentreturnurl($statisticaltypeid) {
		return 'Location:' . __SITEBASE . '/' . $this->contextname . '/' . (($statisticaltypeid == __STATISTICAL_TYPE_VICTIMS) ? "victims" : "traffickers");
	}
}
?>	