<?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";
require_once 'includes/data-access/class-transaction.php';

/**
 * Context for NDP managment
 *
 * Shows and configures National profiles for Victims and Traffickers
 * 
 * @author tm - Advantis
 * @version 1.0.1
 * @package Backend\DataStructures
 */
class context_nationalprofile extends context {
	public $contextname = "nationalprofile";
	private $baseentity = "datastructuredefinitions";
	private $listentity = "dsdlist";
	
	/**
	 * Constructor method
	 *
	 * validates authorization for the user in session based on the current role
	 */
	function context_nationalprofile() {
		main::check_auth_session ();
	}
	
	/**
	 * default action for this context
	 */
	function index() {
		if ($_POST ['statisticaltype'] == __STATISTICAL_TYPE_TRAFFICKERS) {
			$this->traffickers ();
		} else {
			$this->victims ();
		}
	}
	
	/**
	 * Presents NDP Victims list
	 */
	function victims() {
		$em = new EntityManager ( $this->listentity );
		
		$list = $em->load ( "datastructuredefinitions_statisticaltypeid=:STATISTICAL_TYPE_VICTIMS and datastructuredefinitions_levelcodeid=:DSD_LEVEL_NDP order by datastructuredefinitions_id desc" , array(':STATISTICAL_TYPE_VICTIMS' => __STATISTICAL_TYPE_VICTIMS, ':DSD_LEVEL_NDP' => __DSD_LEVEL_NDP));
		
		$this->screen ( $this->contextname . "/index", array (
				'page' => 'victims',
				"list" => $list,
				"contextname" => $this->contextname 
		) );
	}
	
	/**
	 * Presents NDP Traffickers list
	 */
	function traffickers() {
		$em = new EntityManager ( $this->listentity );
		
		$list = $em->load ( "datastructuredefinitions_statisticaltypeid=:STATISTICAL_TYPE_TRAFFICKERS and datastructuredefinitions_levelcodeid=:DSD_LEVEL_NDP order by datastructuredefinitions_id desc", array(':STATISTICAL_TYPE_TRAFFICKERS' => __STATISTICAL_TYPE_TRAFFICKERS, ':DSD_LEVEL_NDP' => __DSD_LEVEL_NDP) );
		
		$this->screen ( $this->contextname . "/index", array (
				'page' => 'traffickers',
				"list" => $list,
				"contextname" => $this->contextname 
		) );
	}
	
	/**
	 * Presents form for new NDP of victims or traffickers
	 *
	 * @param string $page
	 *        	- ['victims','traffickers']
	 */
	function newndp($page) {
		$type = ($page == "victims") ? "V" : "T";
		
		$edsd = new EntityManager ( $this->baseentity );
		$eql = new EntityManager ( "questionlist" );
		$list = $eql->load ( "statisticaltype_code=:type AND lime_index IS NOT NULL",array(':type' => $type) );
		
		$lm = new LovManager ();
		$listVoid = $lm->getLov_VoidReason ();
		
		$this->screen ( $this->contextname . "/detail", array (
				'listvoid' => $listVoid,
				'isdraft' => true,
				'page' => $page,
				"list" => $list,
				"contextname" => $this->contextname 
		) );
	}
	
	/**
	 * Presents form for new victims NDP
	 */
	function newndpvictims($pvars = null) {
		$this->newndp ( "victims" );
	}
	
	/**
	 * Presents form for new trafickers NDP
	 */
	function newndptraffickers($pvars = null) {
		$this->newndp ( "traffickers" );
	}
	
	/**
	 * Creates the new NDP 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
			                    
				// DATASTRUCTURE
				$dsd = new DataStructures ();
				
				$dsd->setNew ( $_POST ['statisticaltype'], $dsd::LEVEL_NDP, $version->id, $_POST ['description'] );
				$em = new EntityManager ( $dsd::BASEENTITY );
				
				$dsd = $em->create ( $dsd );
				
				if ($dsd->id) { // IF DATASTRUCTURE OK
				                
					// DataStructuresQuestions
					$questions = $this->getQuestionsList ( $_POST );
					$em = new EntityManager ( DataStructuresQuestions::BASEENTITY );
					
					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'] );
							
							$dsdquestion = $em->create ( $dsdquestion );
						}
					}
					LogManagement::log ( "Create New NDP", "create", "National Profiles", __LOGTYPE_DATA );
				} else { // error DSD
					$needrollback = true;
				}
			} else { // error version
				$needrollback = true;
			}
			
			if ($needrollback) {
				Transaction::rollback ();
				
				LogManagement::log ( "New NDP error", "create", "National Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_error_new_NDP" ) , Notification::TYPE_ERROR);
			} else {
				Transaction::commit ();
				
				LogManagement::log ( "New NDP " . $dsd->id, "create", "National Profiles", __LOGTYPE_DATA );
				
				setNotification ( getSuccess ( "msg_new_NDP_ok" ) );
			}
			
			header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
		} catch ( Exception $exp ) {
			Transaction::rollback ();
			dump_errorlog ( $this->context, 'edit', $exp->getMessage () );
			
			setNotification ( getError ( "msg_error_new_NDP" ), 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 NDP 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") ? "V" : "T";
		
		$edsd = new EntityManager ( $dsd::BASEENTITY );
		$eql = new EntityManager ( "questionlist" );
		$list = $eql->load ( "statisticaltype_code=:type AND lime_index IS NOT NULL",array(':type' => $type ));
		
		$lm = new LovManager ();
		$listVoid = $lm->getLov_VoidReason ();
		
		$version = new Version ( $dsd->versionregistryid );
		
		$dsdm = new DataStructuresNDPManager ();
		$cangolive = $dsdm->can_go_live ( $dsd );
		$candisable = $dsdm->can_be_disabled ( $dsd );
		$listEdit = $dsdm->get_questions ( $dsd );
		$isdraft = $dsdm->is_draft ( $dsd );
		
		$this->screen ( $this->contextname . "/detail", array (
				'version' => $version,
				'dsd' => $dsd,
				'listvoid' => $listVoid,
				'cangolive' => $cangolive,
				'candisable' => $candisable,
				'isdraft' => $isdraft,
				'page' => $page,
				"list" => $list,
				"listedit" => $listEdit,
				"contextname" => $this->contextname 
		) );
	}
	
	/**
	 * Saves editing data for NDP
	 */
	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'];
					$version->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=:dsdid", array(':dsdid' => $dsd->id));

					$questions = $this->getQuestionsList ( $_POST );
					$em = new EntityManager ( DataStructuresQuestions::BASEENTITY );
					
					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'] );
							
							$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 NDP " . $_POST ["id"] . " error", "update", "National Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_save_NDP_error" ) , Notification::TYPE_ERROR);
			} else {
				Transaction::commit ();
				
				LogManagement::log ( "Edit Draft NDP " . $_POST ["id"], "update", "National Profiles", __LOGTYPE_DATA );
				
				setNotification ( getSuccess ( "msg_save_NDP_ok" ) );
			}
			
			header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
		} catch ( Exception $exp ) {
			Transaction::rollback ();
			dump_errorlog ( $this->context, 'edit', $exp->getMessage () );
			
			setNotification ( getError ( "msg_error_save_NDP" ), 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 DataStructuresNDPManager ();
				
				if ($dsdm->can_go_live ( $dsd )) {
					if ($dsdm->go_live ( $dsd )) {
						// Msg sucess
						LogManagement::log ( "Turn NDP Live", "update", "National Profiles", __LOGTYPE_DATA );
						setNotification ( getSuccess ( "msg_GOLIVE_NDP_ok" ) );
					} else {
						
						// Msg error
						LogManagement::log ( "Turn NDP Live error", "update", "National Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
						setNotification ( getError ( "msg_GOLIVE_NDP_error" ), Notification::TYPE_ERROR );
					}
				} else {
					// warning can't ?
					LogManagement::log ( "can't go live NDP " . $_REQUEST ["id"], "update", "National Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				}
			}
		}
		
		header ( $this->getparentreturnurl ( $dsd->statisticaltypeid ) );
	}
	
	/**
	 * Disables NDP
	 */
	function disable() {
		if ($_REQUEST ["id"]) {
			
			$dsd = new DataStructures ( $_REQUEST ["id"] );
			
			if ($dsd) {
				$dsdm = new DataStructuresNDPManager ();
				if ($dsdm->can_be_disabled ( $dsd )) {
					if ($dsdm->disable ( $dsd )) {
						
						// Msg sucess
						LogManagement::log ( "Disable NDP", "update", "National Profiles", __LOGTYPE_DATA );
						setNotification ( getSuccess ( "msg_disable_NDP_ok" ) );
					} else {
						
						// Msg error
						LogManagement::log ( "Disable NDP error", "update", "National Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
						setNotification ( getError ( "msg_error_disable_NDP" ), Notification::TYPE_ERROR );
					}
				} else {
					// warning can't
					LogManagement::log ( "Can't Disable NDP " . $_REQUEST ["id"], "update", "National 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 DataStructuresNDPManager ();
				$newdsdid = $dsdm->save_new_from ( $dsd );
				
				if (isset ( $newdsdid )) {
					
					LogManagement::log ( "Save new Draft NDP from other NDP", "create", "National Profiles", __LOGTYPE_DATA );
					setNotification ( getSuccess ( "msg_savenew_NDP_ok" ) );
					$shownew = true;
				} else {
					LogManagement::log ( "Save new Draft NDP from other NDP error", "create", "National Profiles", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
					setNotification ( getError ( "msg_error_savenew_NDP" ), 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");
	}
}
?>	