<?php
require_once 'app/class-user.php';
require_once "app/class-lime-manager.php";
require_once "app/class-data-structures-manager.php";
require_once "app/class-wf-engine.php";
require_once "app/class-llo-record.php";
require_once 'includes/data-access/class-transaction.php';

/**
 * LLORecord Context
 *
 * Context for Data Record information LLO support resident in external system
 *
 * @author balexandre - Advantis
 * @version 1.0.1
 * @package Backend\DataRecords
 */
class context_collectdata extends context {
	private $contextname = "collectdata";
	function context_collectdata() {
		main::check_auth_session ();
	}
	
	/**
	 * select entry point (collect,analyse or publish)
	 */
	function index() {
		$userrole = Session::get_activerole ();
		
		switch ($userrole->role_code) {
			
			case 'LC' :
				$this->collect ();
				break;
			case 'LA' :
				$this->analyse ();
				break;
			case 'DA' :
				$this->analyse ();
			case 'LP' :
				$this->publish ();
				break;
		}
	}
	
	/**
	 *
	 * Responsible to open lime popup
	 *
	 * @param unknown_type $list        	
	 */
	private function getOpenLime(&$list) {
		$openlimeobj = null;
		
		if ($_REQUEST ['openid']) {
			
			// find obj from user objs
			foreach ( $list as $responseobj ) {
				if ($responseobj->id == $_REQUEST ['openid']) {
					$openlimeobj = $responseobj;
					break;
				}
			}
		}
		
		return $openlimeobj;
	}
	
	/**
	 *
	 * shows the publish screen and data
	 *
	 * @param string $pvars        	
	 */
	function publish($pvars = null) {
		$em = new EntityManager ( 'responsestatuslist' );
		
		/**
		 * load valid, for organization
		 */
		
		if ($_POST["type"]) {
			$list = $em->load ( "user_organisationid=:user_organisationid AND (codelistitems_code='V' OR codelistitems_code='IV') AND statisticaltypeid=:type", array(':user_organisationid' => Session::get_user ()->organisationid , ':type' => $_POST['type']) );
		}
		else {
			$list = $em->load ( "user_organisationid=:user_organisationid AND (codelistitems_code='V' OR codelistitems_code='IV')", array(':user_organisationid' => Session::get_user ()->organisationid) );
		}
		
		$openlimeobj = $this->getOpenLime ( $list );
		/**
		 * ------------------------------------------
		 */
		
		$this->screen ( $this->contextname . "/index", array (
				'list' => $list,
				'pvars' => $pvars,
				'openlimeobj' => $openlimeobj 
		) );
                                                                                                                                                 	}
	
	/**
	 *
	 * shows analyse screen and data
	 *
	 * @param string $pvars        	
	 */
	function analyse($pvars = null) {
		$em = new EntityManager ( 'responsestatuslist' );
		
		/**
		 * load completed,valid or invalid for organization
		 */
		
		$list = null;
		
		if ($_POST["type"]) {
			
			$list = $em->load ( "user_organisationid=:user_organisationid AND (codelistitems_code='C' OR codelistitems_code='FR' ) AND statisticaltypeid=:type", array(':user_organisationid' => Session::get_user ()->organisationid , ':type' => $_POST['type']) );
			
		} else {
		
			$list = $em->load ( "user_organisationid=:user_organisationid AND (codelistitems_code='C' OR codelistitems_code='FR' )", array(':user_organisationid' => Session::get_user ()->organisationid) );
		
		}
		
		$openlimeobj = $this->getOpenLime ( $list );
		
		/**
		 * ------------------------------------------
		 */
		
		$this->screen ( $this->contextname . "/index", array (
				'list' => $list,
				'pvars' => $pvars,
				'openlimeobj' => $openlimeobj 
		) );
	}
	
	/**
	 *
	 * shows collect screen and data
	 *
	 * @param string $pvars        	
	 */
	function collect($pvars = null) {
		$em = new EntityManager ( 'responsestatuslist' );
		
		/**
		 * load uncompleted and "for review" from user
		 */
		
		$list = $em->load ( "userid=:userid AND (codelistitems_code='UC' OR codelistitems_code='FR')", array(':userid' => Session::get_user ()->id ) );
		$list1 = $em->load ( "user_organisationid=:user_organisationid AND (codelistitems_code='UC' OR codelistitems_code='FR')", array(':user_organisationid' => Session::get_user ()->organisationid) );
		$dpam = new DataStructuresDPAManager ();
		
		$newvictim = $dpam->can_collect_data ( __STATISTICAL_TYPE_VICTIMS );
		$newtrafficker = $dpam->can_collect_data ( __STATISTICAL_TYPE_TRAFFICKERS );
		
		/* ------------------------------------------ */
		
		/**
		 * call from external page ie:alerts ------------
		 */
		
		$openlimeobj = $this->getOpenLime ( $list1 );
		
		// -----------------------------------------------
		
		$this->screen ( $this->contextname . "/index", array (
				'list' => $list,
				'pvars' => $pvars,
				'newvictim' => $newvictim,
				'newtrafficker' => $newtrafficker,
				'openlimeobj' => $openlimeobj 
		) );
	}
	
	/**
	 *
	 * searches record by uid
	 *
	 * @param string $pvars        	
	 */
	function finduid($pvars = null) {
		$em = new EntityManager ( 'responsestatuslist' );
		
		if ($_REQUEST ['searchuid']) {
			
			$searchuid = $_REQUEST ['searchuid'];
			
			$list = $em->load ( "recordcode=:searchuid", array(':searchuid' => $searchuid) );
			
			if ($list) {
				
				header ( "location:" . __SITEBASE . "/collectdata?openid=" . $list [0]->id );
			}
			
			$pvars = array (
					'notfound' => true 
			);
			$this->collect ( $pvars );
		}
	}
	
	/**
	 * jumps to LimeSurvey add victim screen
	 */
	function addvictim() {
		$user = new User ( Session::get_user ()->id );
		
		$limemanager = new LimeManager ();
		
		$results = $limemanager->createToken ( LS_VICTIMS_SURVEY, $user );
		
		$token = $results [0];
		// print_r($token);
		
		$org = new Entity ( "organisations", Session::get_user ()->organisationid );
		
		$dpam = new DataStructuresDPAManager ();
		
		$properties = array (
				"attribute_1" => $dpam->get_token ( __STATISTICAL_TYPE_VICTIMS ),
				"attribute_2" => internationalname,
				"attribute_3" => html_entity_decode(Session::get_user ()->username) ,
				"attribute_4" => $_REQUEST['uid']
		);
		
		$limemanager->setTokenProperties ( $token ['tid'], LS_VICTIMS_SURVEY, $properties );
		
		/**
		 * create reg in mosy database
		 */
		$em = new EntityManager ( "responsestatus" );
		
		$obj = new stdClass ();
		
		$obj->userid = Session::get_user ()->id;
		
		$obj->provisionagreementid = $dpam->can_collect_data ( __STATISTICAL_TYPE_VICTIMS );
		
		$obj->statisticaltypeid = __STATISTICAL_TYPE_VICTIMS;
		
		$obj->limetoken = $token ['token'];
		
		$obj->statuscodeid = __RECORD_STATUS_UNCOMPLETED;
		
		$obj->publishcodeid = __PUBLISHED_STATUS_UNPUBLISHED;
		
		$obj->recordcode = $_REQUEST['uid'];
		
		$obj = $em->create ( $obj );
		
		$this->createHistoryResponse ( $obj );
		
		// TODO : TM error treatment
		
		Session::set_lime_callback_id ( $obj->id );
		
		/**
		 * end create reg in mosy database
		 */
		
		// $limeurl = LS_BASEURL."/survey/index/sid/".LS_VICTIMS_SURVEY."/token/".$token['token'];
		
		// $this->index(array('limeurl'=>$limeurl));
		
		header ( "Location:" . LS_BASEURL . "/survey/index/sid/" . LS_VICTIMS_SURVEY . "/token/" . $token ['token']."/newtest/Y?lang=".substr ( Session::get_language ()->code, 0, 2 ) );
		
	}
	
	/**
	 * jumps to LimeSurvey add trafficker screen
	 */
	function addtrafficker() {
		$user = new User ( Session::get_user ()->id );
		
		$limemanager = new LimeManager ();
		
		$results = $limemanager->createToken ( LS_TRAFFICKERS_SURVEY, $user );
		
		$token = $results [0];
		
		$org = new Entity ( "organisations", Session::get_user ()->organisationid );
		
		$dpam = new DataStructuresDPAManager ();
		
		$properties = array (
				"attribute_1" => $dpam->get_token ( __STATISTICAL_TYPE_TRAFFICKERS ),
				"attribute_2" => $org->internationalname,
				"attribute_3" => html_entity_decode(Session::get_user ()->username) ,
				"attribute_4" => $_REQUEST['uid']
		);
		
		$limemanager->setTokenProperties ( $token ['tid'], LS_TRAFFICKERS_SURVEY, $properties );
		
		/**
		 * create reg in mosy database
		 */
		$em = new EntityManager ( "responsestatus" );
		
		$obj = new stdClass ();
		
		$obj->userid = Session::get_user ()->id;
		
		$obj->statisticaltypeid = __STATISTICAL_TYPE_TRAFFICKERS;
		
		$obj->provisionagreementid = $dpam->can_collect_data ( __STATISTICAL_TYPE_TRAFFICKERS );
		
		$obj->limetoken = $token ['token'];
		
		$obj->statuscodeid = __RECORD_STATUS_UNCOMPLETED;
		
		$obj->publishcodeid = __PUBLISHED_STATUS_UNPUBLISHED;
		
		$obj->recordcode = $_REQUEST['uid'];
		
		$obj = $em->create ( $obj );
		
		$this->createHistoryResponse ( $obj );
		
		// TODO : TM error treatment
		
		Session::set_lime_callback_id ( $obj->id );
		
		/**
		 * end create reg in mosy database
		 */
		
		// $limeurl = LS_BASEURL."/survey/index/sid/".LS_TRAFFICKERS_SURVEY."/token/".$token['token'];
		
		// $this->index(array('limeurl'=>$limeurl));
		
		header ( "Location:" . LS_BASEURL . "/survey/index/sid/" . LS_TRAFFICKERS_SURVEY . "/token/" . $token ['token']."/newtest/Y?lang=".substr ( Session::get_language ()->code, 0, 2 ) );
		
	}
	
	/**
	 * callback method after LimeSurvey form is closed or completed
	 */
	function callback() {
		if (Session::get_lime_callback_id ()) {
			
			$responsestatus = new Entity ( "responsestatus", Session::get_lime_callback_id () );
			
			$currentstatus = $responsestatus->statuscodeid;
			
			$wfe = new WFEngine ();
			
			$listStates = $wfe->get_wf_llorecord_next_states ( SESSION::get_activerole ()->role_code, $responsestatus->statuscodeid, $responsestatus->id );
			
			/**
			 * end available status
			 */
			
			$this->screen ( $this->contextname . "/endcollect", array (
					'currentstatus' => $currentstatus,
					'availablestatus' => $listStates,
					'responsestatus' => $responsestatus 
			), 'empty' );
		}
	}
	
	/**
	 * End of the survey form (shows last notes and submits)
	 */
	function end() {
		if (Session::get_lime_callback_id ()) {
			
			if ($_POST) {
				
				try {
					Transaction::beginTransaction ();
					
					$obj = new Entity ( 'responsestatus', Session::get_lime_callback_id () );
					
					$wfe = new WFEngine ();
					$role = SESSION::get_activerole ()->role_code;
					$listStates = $wfe->get_wf_llorecord_next_states ( $role, $obj->statuscodeid, $obj->id );
					
					$step = $wfe::search_step ( $listStates, $_POST ['statuscodeid'] );
					
					if ($step != null) {
						
						$obj->annotation = $_POST ['annotation'];
						
						$obj->statuscodeid = $_POST ['statuscodeid'];
						
						$obj->updatedate = date("Y-m-d H:i:s");
						
						$obj->save ();
						
						$this->createHistoryResponse ( $obj );
						
						$obj = new Entity ( 'responsestatus', Session::get_lime_callback_id () );
						//
						$wfe->run_postaction_step ( $step );
						
						LogManagement::log ( "LLO Collect data edit " . $obj->id, "update", "LLORecord", __LOGTYPE_DATA );
						
						Transaction::commit ();
					}
				} catch ( Exception $exp ) {
					Transaction::rollback ();
					dump_errorlog ( 'Collectdata', 'end', $exp->getMessage () );
				}
			}
		}
		
		Session::set_lime_callback_id ( null );
		
		$this->screen ( $this->contextname . "/endcollect", array (
				'closemodal' => 1 
		), 'empty' );
	}
	
	/**
	 * jumps to LimeSurvey
	 */
	function gotoLIME() {
		$surveytype = $_REQUEST ['s'];
		$surveyid = null;
		
		if ($surveytype == __STATISTICAL_TYPE_VICTIMS) {
			
			$surveyid = LS_VICTIMS_SURVEY;
		}
		if ($surveytype == __STATISTICAL_TYPE_TRAFFICKERS) {
			
			$surveyid = LS_TRAFFICKERS_SURVEY;
		}
		
		$tokenid = $_REQUEST ['t'];
		
		$responsestatusid = $_REQUEST ['i'];
		
		if ($tokenid && $surveyid && $responsestatusid) {
			
			Session::set_lime_callback_id ( $responsestatusid );
			// echo "Location:".LS_BASEURL."/survey/index/sid/".$surveyid."/token/".$tokenid;
			header ( "Location:" . LS_BASEURL . "/survey/index/sid/" . $surveyid . "/token/" . $tokenid . "/newtest/Y?lang=" . substr ( Session::get_language ()->code, 0, 2 ) );
		} else {
			
			LogManagement::log ( "Gotolime error not a valid url ", "display", "LLORecord", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
		}
	}
	
	/**
	 * Marks posted records as published
	 */
	function markpublishable() {
		if ($_POST) {
			
			$publishableid = __PUBLISHED_STATUS_PUBLISHABLE;
			
			foreach ( $_POST as $key => $value ) {
				
				$id = null;
				$pieces = explode ( 'mark_', $key );
				if (count ( $pieces ) > 0) {
					$id = $pieces [1];
					
					if ($id) {
						
						$obj = new Entity ( "responsestatus", $id );
						
						$obj->publishcodeid = $publishableid;
						
						$obj->save ();
					}
				}
			}
		}
		
		header ( 'Location:' . __SITEBASE . '/collectdata' );
	}
	
	/**
	 * Shows publish victims screen
	 */
	function publishvictims() {
		$ret = $this->publishNFP ( __STATISTICAL_TYPE_VICTIMS );
		
		if (isset ( $ret ) && count ( $ret ) > 0 && isset ( $ret [0]->publishvictims )) {
			
			if ($ret [0]->publishvictims == "0") {
				
				LogManagement::log ( "Publish Victims NFP no action ", "publish to NFP", "Collect LLO", __LOGTYPE_DATA );
				setNotification ( getNotification ( "msg_no_item_publish_victims" ), Notification::TYPE_WARNING );
			} elseif ($ret [0]->publishvictims != null) {
				
				LogManagement::log ( "Publish Victims NFP error " . $ret [0]->publishvictims, "publish to NFP", "Collect LLO", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_error_publish_victims" ), Notification::TYPE_ERROR );
			} else {
				LogManagement::log ( "Publish Victims NFP sucess. ", "publish to NFP", "Collect LLO", __LOGTYPE_DATA );
				setNotification ( getSuccess ( "msg_publish_victims" ) );
			}
		} else {
			LogManagement::log ( "Publish Victims NFP error ", "publish to NFP", "Collect LLO", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			setNotification ( getError ( "msg_error_publish_victims" ), Notification::TYPE_ERROR );
		}
		return $this->publish ( $this->data ['pvars'] );
	}
	
	/**
	 * Shows publish traffickers screen
	 */
	function publishtraffickers() {
		$ret = $this->publishNFP ( __STATISTICAL_TYPE_TRAFFICKERS );
		
		if (isset ( $ret ) && count ( $ret ) > 0 && isset ( $ret [0]->publishtraffickers )) {
			
			if ($ret [0]->publishtraffickers == "0") {
				
				LogManagement::log ( "Publish traffickers NFP no action ", "publish to NFP", "Collect LLO", __LOGTYPE_DATA );
				setNotification ( getNotification ( "msg_no_item_publish_traffickers" ), Notification::TYPE_WARNING );
			} elseif ($ret [0]->publishtraffickers != null) {
				
				LogManagement::log ( "Publish traffickers NFP error " . $ret [0]->publishtraffickers, "publish to NFP", "Collect LLO", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
				
				setNotification ( getError ( "msg_error_publish_traffickers" ), Notification::TYPE_ERROR );
			} else {
				LogManagement::log ( "Publish traffickers NFP sucess. ", "publish to NFP", "Collect LLO", __LOGTYPE_DATA );
				setNotification ( getSuccess ( "msg_publish_traffickers" ) );
			}
		} else {
			LogManagement::log ( "Publish traffickers NFP error ", "publish to NFP", "Collect LLO", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
			
			setNotification ( getError ( "msg_error_publish_traffickers" ), Notification::TYPE_ERROR );
		}
		
		return $this->publish ( $this->data ['pvars'] );
	}
	
	/**
	 *
	 * pusblishes NFP victims or traffickers
	 *
	 * @param unknown $type        	
	 * @return void|multitype:
	 */
	private function publishNFP($type) {
		$da = new DataAccess ();
		
		$args = array ();
		array_push ( $args, $da->helper_args ( 'userid', Session::get_user ()->id, $da::TYPE_INTEGER ) );
		array_push ( $args, $da->helper_args ( 'fromorganisationid', Session::get_org ()->id, $da::TYPE_INTEGER ) );
		
		if ($type == __STATISTICAL_TYPE_VICTIMS) {
			
			$func_name = 'base.publishvictims';
		} else if ($type == __STATISTICAL_TYPE_TRAFFICKERS) {
			
			$func_name = 'base.publishtraffickers';
		} else {
			return;
		}
		
		$sql = "select 	" . $func_name . "(:userid, :fromorganisationid)";
		
		return $da->func_get ( $sql, $args );
	}
	
	/**
	 *
	 * Creates history for response record
	 *
	 * @param Entity $obj
	 *        	- of "responsestatus"
	 */
	private function createHistoryResponse($objresponse) {
		
		if (! isset ($objresponse->id)) {
			return false;
		} else {
			$da = new DataAccess ();
			$cfgdb = new ConfigDB ();
			$schema = $cfgdb->connections ["DEFAULT"] ["DBSCHEMA"];
			
			$da->query("INSERT INTO " . $schema . ".responsestatushistory (responsestatusid, statuscodeid, publishcodeid, annotation,userid,actiondate) select id, statuscodeid, publishcodeid, annotation, userid, now() from " . $schema . ".responsestatus where id = :responseid", array(':responseid' => $objresponse->id));

			return true;
		}
	
	} 
	
	function exportexcel() {
	
		ob_clean();
		
		//-------------- data processing
	
		//checkboxes selected:
	
		$ids = array();
	
		foreach($_POST as $key => $value) {
	
			if (substr( $key, 0, 4 ) === "mark") {
				if ($value == 'on') {
					$pieces = explode("_",$key);
					$id = $pieces[1];
				}
				array_push($ids,$id);
			}
		}
	
		$ids_str = implode(',',$ids);
	
		//end checkboxes selected
	
		$statisticaltypeid = $_POST['type'];
	
		$da = new DataAccess ();
	
		$args = array ();
	
		array_push ( $args, $da->helper_args ( 'ids', $ids_str, $da::TYPE_TEXT ) );
		array_push ( $args, $da->helper_args ( 'statisticaltypeid', $statisticaltypeid, $da::TYPE_INTEGER ) );
		array_push ( $args, $da->helper_args ( 'languageid', Session::get_language()->id, $da::TYPE_INTEGER ) );
	
		$sql = "select * from  base.export_lloresponses (:ids,:statisticaltypeid,:languageid)";
	
		$list = $da->func_get ( $sql, $args );
	
		$aset = array ();
	
		$excel_lines = array();
		foreach ( $list as $item ) {
			$cols = array();
			$cols = explode("*#",$item->excel_line);
			array_push($excel_lines,$cols);
		}
	
		//------------------------------
	
		date_default_timezone_set('Europe/London');
	
	
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
	
		// Set document properties
		$objPHPExcel->getProperties()->setCreator("Mosy")
		->setLastModifiedBy("Mosy")
		->setTitle("Export Excel")
		->setSubject("Export Excel")
		->setDescription("Export Excel")
		->setKeywords("Export Excel");
	
		$objPHPExcel->setActiveSheetIndex(0);
	
	
		$line = 1;
		foreach($excel_lines as $excel_line) {
	
			$col = 'A';
			foreach($excel_line as $colvalue) {
					
				$objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
				//$value = $colvalue;
				$value = html_entity_decode($colvalue);
				$value = str_replace("\\n", "\n", $value);
				$objPHPExcel->getActiveSheet()->setCellValue($col.$line,$value);
				$col++;
			}
			$line++;
		}
	
		//Title
		$objPHPExcel->getActiveSheet()->setTitle('Export from Mosy');
	
	
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="export_mosy.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
	
		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
	
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save('php://output');
	
		exit;
	}
	
}

?>