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

/**
 * Provision Agreement context
 *
 * Shows Provision Agreement for Victims and Traffickers
 * 
 * @version 1.0.1
 * @author balexandre - Advantis
 * @package Backend\DataStructures
 */
class context_provisionagreement extends context {
	public $contextname = "provisionagreement";
	private $baseentity = "provisionagreementdsdlist";
	
	/**
	 * Constructor method
	 *
	 * validates authorization for the user in session based on the current role
	 */
	function context_provisionagreement() {
		main::check_auth_session ();
	}
	
	/**
	 * default action for this context
	 */
	function index() {
		if ($_POST ['statisticaltype'] == __STATISTICAL_TYPE_TRAFFICKERS) {
			$this->traffickers ();
		} else {
			$this->victims ();
		}
	}
	
	/**
	 * Presents DPA Victims list
	 */
	function victims() {
		$em = new EntityManager ( $this->baseentity );
		
		$list = $em->load ( "datastructuredefinitions_statisticaltypeid=:STATISTICAL_TYPE_VICTIMS order by provisionagreements_id desc", array(':STATISTICAL_TYPE_VICTIMS' => __STATISTICAL_TYPE_VICTIMS) );
		
		$dsdm = new DataStructuresDPAManager ();
		$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 DPA Traffickers list
	 */
	function traffickers() {
		$em = new EntityManager ( $this->baseentity );
		
		$list = $em->load ( "datastructuredefinitions_statisticaltypeid=:STATISTICAL_TYPE_TRAFFICKERS order by provisionagreements_id desc", array('STATISTICAL_TYPE_TRAFFICKERS' => __STATISTICAL_TYPE_TRAFFICKERS) );
		
		$dsdm = new DataStructuresDPAManager ();
		$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 DPA of victims or traffickers
	 *
	 * @param string $page
	 *        	- ['victims','traffickers']
	 */
	function newdpa($page, $pvars = null) {
		$type = ($page == "victims") ? "V" : "T";
		
		$em = new EntityManager ( 'organisations' );
		
		$organisation_list = $em->load ( "active=true" );
		
		// get list LDP for the statisticaltype
		$em = new EntityManager ( DataStructures::LISTVIEW );
		
		$listldp = $em->load ( "datastructuredefinitions_statisticaltypeid=:statisticaltypeid and datastructuredefinitions_levelcodeid=:levelcodeid and versionregistry_validto is null order by datastructuredefinitions_id desc", array(':statisticaltypeid' => (($type == "V") ? __STATISTICAL_TYPE_VICTIMS : __STATISTICAL_TYPE_TRAFFICKERS), ':levelcodeid' => __DSD_LEVEL_LDP) );
		
		$lm = new LovManager ();
		$lfrequency = $lm->getLov_TimeFrequency ();
		$lreliability = $lm->getLov_Reliability ();
		
		$this->screen ( $this->contextname . "/detail", array (
				"organisation_list" => $organisation_list,
				"contextname" => $this->contextname,
				"listldp" => $listldp,
				"lfrequency" => $lfrequency,
				"lreliability" => $lreliability,
				"isdraft" => true,
				"cangolive" => false,
				"candisable" => false,
				"saveasnew" => false,
				'pvars' => $pvars,
				"page" => $page 
		) );
	}
	
	/**
	 * Presents form for new victims DPA
	 */
	function newdpavictims($pvars = null) {
		$this->newdpa ( "victims", $pvars );
	}
	
	/**
	 * Presents form for new trafickers DPA
	 */
	function newdpatraffickers($pvars = null) {
		$this->newdpa ( "traffickers", $pvars );
	}
	
	/**
	 * server side validations for DPA
	 *
	 * @return boolean
	 */
	function validateForm() {
		$rsp = "";
		$error = false;
		
		$today = date_create ();
		$validFrom = date_create ( $_POST ['validfrom'] );
		$validTo = date_create ( $_POST ['validto'] );
		$deadline = date_create ( $_POST ['publicationdeadline'] );
		
		if ($validTo <= $today) {
			$error = true;
			$rsp = getError ( "msg_error_dateTo_gt_today", $rsp );
		}
		
		if ($validTo <= $validFrom) {
			$error = true;
			$rsp = getError ( "msg_error_dateTo_gt_dateFrom", $rsp );
		}
		
		if ($validTo < $deadline) {
			$error = true;
			$rsp = getError ( "msg_error_dateTo_gt_dateDeadline", $rsp );
		}
		
		if ($deadline < $validFrom) {
			$error = true;
			$rsp = getError ( "msg_error_dateDeadline_gt_dateFrom", $rsp );
		}
		
		if ($error == true) {
			setNotification ( $rsp, Notification::TYPE_ERROR );
		}
		
		return ! $error;
	}
	
	/**
	 * Creates the new DPA int the DB
	 */
	function create() {
		$needrollback = false;
		try {
			
			Transaction::beginTransaction ();
			
			$page = ($_POST ['statisticaltype'] == __STATISTICAL_TYPE_VICTIMS) ? "victims" : "traffickers";
			
			if (! $this->validateForm ()) {
				$this->newdpa ( $page, $this->data ['pvars'] );
				return;
			}
			
			$version = new Version ();
			$description = $_POST ['name'];
			$version->setNew ( $_POST ['code'], $_POST ['annotation'], $description );
			
			$em = new EntityManager ( $version::BASEENTITY );
			$version = $em->create ( $version );
			
			if ($version->id) {
				$dpa = new DataProvisions ();
				
				$dpa->setNew ( $_POST ['name'], $_POST ['fromorganisationid'], $_POST ['validfrom'], $_POST ['validto'], $_POST ['datastructuredefinitionid'], $_POST ['frequencycodeid'], $_POST ['publicationdeadline'], $_POST ['reliabilitycodeid'], $version->id, $_POST ['embargotime'] );
				
				$em = new EntityManager ( $dpa::BASEENTITY );
				
				$dpa = $em->create ( $dpa );
				
				if ($dpa->id) {
					LogManagement::log ( "Create New DPA", "create", "Data Provision Agreement", __LOGTYPE_DATA );
				} else { // error on getting DPA
					$needrollback = true;
				}
			} else { // error on getting version
				$needrollback = true;
			}
			
			if ($needrollback) {
				Transaction::rollback ();
				
				LogManagement::log ( "New DPA error", "create", "Data Provision Agreement", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_error_new_DPA" ) , Notification::TYPE_ERROR);
			} else {
				Transaction::commit ();
				
				LogManagement::log ( "New DPA " . $dpa->id, "create", "Data Provision Agreement", __LOGTYPE_DATA );
				
				setNotification ( getSuccess ( "msg_new_DPA_ok" ) );
			}
			
			LogManagement::log ( "Create new DPA", "create", "Data Provision Agreement", __LOGTYPE_DATA );
			
			header ( $this->getparentreturnurl ($_POST ['statisticaltype'] ) );
		} catch ( Exception $exp ) {
			Transaction::rollback ();
			dump_errorlog ( $this->context, 'edit', $exp->getMessage () );
			
			setNotification ( getError ( "msg_error_new_DPA" ), Notification::TYPE_ERROR );
			
			header ( $this->getparentreturnurl ($_POST ['statisticaltype']) );
		}
	}
	
	/**
	 * Prepares DPA for editing
	 *
	 * @param string $newid        	
	 */
	function edit($newid = null) {
		$dpa = null;
		if ($_REQUEST ["id"]) {
			$newid = $_REQUEST ["id"];
		}
		
		$em = new EntityManager ( $this->baseentity );
		
		$list = $em->load ( "provisionagreements_id = ? order by provisionagreements_id desc", array (
				$newid 
		) );
		
		if (count ( $list ) > 0) {
			
			$dpa = $list [0];
			
			$page = ($dpa->datastructuredefinitions_statisticaltypeid == __STATISTICAL_TYPE_VICTIMS) ? "victims" : "traffickers";
			
			$em = new EntityManager ( 'organisations' );
			
			$organisation_list = $em->load ( "active=true" );
			
			// get list LDP for the statisticaltype
			$em = new EntityManager ( DataStructures::LISTVIEW );
			
			$listldp = $em->load ( "datastructuredefinitions_statisticaltypeid=:statisticaltypeid and datastructuredefinitions_levelcodeid=:levelcodeid and versionregistry_validto is null order by datastructuredefinitions_id desc", array(':statisticaltypeid' => $dpa->datastructuredefinitions_statisticaltypeid, ':levelcodeid' => __DSD_LEVEL_LDP) );
			
			$lm = new LovManager ();
			$lfrequency = $lm->getLov_TimeFrequency ();
			$lreliability = $lm->getLov_Reliability ();
			
			$dsdm = new DataStructuresDPAManager ();
			$dp = new DataProvisions ( $dpa->provisionagreements_id );
			$cangolive = $dsdm->can_go_live ( $dp );
			$candisable = $dsdm->can_be_disabled ( $dp );
			$isdraft = $dsdm->is_draft ( $dp );
			
			$version = new Version ( $dp->versionregistryid );
			
			$this->screen ( $this->contextname . "/detail", array (
					"organisation_list" => $organisation_list,
					"contextname" => $this->contextname,
					"listldp" => $listldp,
					"lfrequency" => $lfrequency,
					"lreliability" => $lreliability,
					"isdraft" => $isdraft,
					"cangolive" => $cangolive,
					"candisable" => $candisable,
					"saveasnew" => true,
					"dpa" => $dp,
					"version" => $version,
					'pvars' => $pvars,
					"page" => $page 
			) );
		} 

		else {
			$this->index ();
		}
	}
	
	/**
	 * Saves editing data for DPA
	 */
	function save() {
		$needrollback = false;
		try {
			
			Transaction::beginTransaction ();
			
			if ($_POST ["id"]) {
				
				$dpa = new DataProvisions ( $_REQUEST ["id"] );

				if ($dpa) {
					
					$version = new Version ( $dpa->versionregistryid );
					$version->code = $_POST ['code'];
					$version->annotation = $_POST ['annotation'];
					$description = $_POST ['description'];
					$version->save ();
					
					$dpa->description = $_POST ['description'];
					
					if ($dpa->active != 1) {
						$dpa->active = 0;
					}
					$dpa->save ();
				}
			} else { // error no getting id
				$needrollback = true;
			}
			
			if ($needrollback) {
				Transaction::rollback ();
				LogManagement::log ( "Edit Draft DPA " . $_POST ["id"] . " error", "update", "Data Provision Agreement", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_save_DPA_error" ) , Notification::TYPE_ERROR);
			} else {
				Transaction::commit ();
				
				LogManagement::log ( "Edit Draft DPA " . $_POST ["id"], "update", "Data Provision Agreement", __LOGTYPE_DATA );
				
				setNotification ( getSuccess ( "msg_save_DPA_ok" ) );
			}
			
			header ( $this->getparentreturnurl ( $_POST ['statisticaltype'] ) );
		} catch ( Exception $exp ) {
			Transaction::rollback ();
			dump_errorlog ( $this->context, 'edit', $exp->getMessage () );
			
			setNotification ( getError ( "msg_error_save_DPA" ), Notification::TYPE_ERROR );
			
			header ( $this->getparentreturnurl ( $_POST ['statisticaltype'] ) );
		}
	}
	
	/**
	 * Turns DPA Live
	 */
	function golive() {
		if ($_REQUEST ["id"]) {
			
			$dpa = new DataProvisions ( $_REQUEST ["id"] );
			
			if ($dpa) {
				
				$dsdm = new DataStructuresDPAManager ();
				
				if ($dsdm->can_go_live ( $dpa )) {
					if ($dsdm->go_live ( $dpa )) {
						// Msg sucess
						LogManagement::log ( "Turn DPA Live", "update", "Data Provision Agreement", __LOGTYPE_DATA );
						setNotification ( getSuccess ( "msg_GOLIVE_DPA_ok" ) );
					} else {
						// MSG ERROR
						LogManagement::log ( "Turn DPA Live error", "update", "Data Provision Agreement", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
						setNotification ( getError ( "msg_GOLIVE_DPA_error" ), Notification::TYPE_ERROR );
					}
				} else {
					// warning can't
					LogManagement::log ( "can't go live DPA " . $_REQUEST ["id"], "update", "Data Provision Agreement", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				}
			}
		}
		
		header ( $this->getparentreturnurl ( $_REQUEST ['statisticaltype'] ) );
	}
	
	/**
	 * Disables DPA
	 */
	function disable() {
		if ($_REQUEST ["id"]) {
			
			$dpa = new DataProvisions ( $_REQUEST ["id"] );
			
			if ($dpa) {
				$dsdm = new DataStructuresDPAManager ();
				if ($dsdm->can_be_disabled ( $dpa )) {
					if ($dsdm->disable ( $dpa )) {
						
						// Msg sucess
						LogManagement::log ( "Disable DPA", "update", "Data Provision Agreement", __LOGTYPE_DATA );
						setNotification ( getSuccess ( "msg_disable_NDP_ok" ) );
					} else {
						
						// Msg error
						LogManagement::log ( "Disable DPA error", "update", "Data Provision Agreement", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
						setNotification ( getError ( "msg_error_disable_NDP" ), Notification::TYPE_ERROR );
					}
				} else {
					// warning
					LogManagement::log ( "Can't Disable DPA " . $_REQUEST ["id"], "update", "Data Provision Agreement", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				}
			}
		}
		
		header ( $this->getparentreturnurl ( $_REQUEST ['statisticaltype'] ) );
	}
	
	/**
	 * Saves new DPA from another Version for editing
	 */
	function savenewversion() {
		if ($_REQUEST ["id"]) {
			
			$dpa = new DataProvisions ( $_REQUEST ["id"] );
			
			if ($dpa) {
				$dsdm = new DataStructuresDPAManager ();
				$newdsdid = $dsdm->save_new_from ( $dpa );
				
				if (isset ( $newdsdid )) {
					
					LogManagement::log ( "Save new Draft DPA from other DPA", "create", "Data Provision Agreement", __LOGTYPE_DATA );
					setNotification ( getSuccess ( "msg_savenew_DPA_ok" ) );
					$shownew = true;
				} else {
					LogManagement::log ( "Save new Draft DPA from other DPA error", "create", "Data Provision Agreement", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
					setNotification ( getError ( "msg_error_savenew_DPA" ), Notification::TYPE_ERROR );
				}
			}
		}
		
		if ($shownew) {
			header ( 'Location:' . __SITEBASE . '/' . $this->contextname . '/edit?id=' . $newdsdid );
		} else {
			header ( $this->getparentreturnurl ($_REQUEST ['statisticaltype']) );
		}
	}
	
	/**
	 * 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_TRAFFICKERS) ? "victims" : "traffickers");
	}
}