<?php
require_once 'app/class-file-manager.php';

/**
 * EFPcollect Context
 *
 * Context for DataSet Record collection at EFP level
 *
 * @author tm - Advantis
 * @version 1.0.1
 * @package Backend\DataSets
 */
class context_efpcollect extends context {
	public $contextname = "efpcollect";
	
	/**
	 * Constructor & Authorization
	 */
	function context_efpcollect() {
		main::check_auth_session ();
	}
	
	/**
	 * Default action shows Dataset listing acording to filtering via POST
	 */
	function index() {
		Navigation::resolve_step ( $this );
		
		$navkey = Navigation::set_step ( $this->contextname, Navigation::BACKPOST_TYPE_POST );
		
		$pvars = $this->data ['pvars'];
		
		$list = array ();
		
		if (! isset ( $_POST ['type'] )) {
			$_POST ['type'] = __STATISTICAL_TYPE_VICTIMS;
		}
		
		$em = new EntityManager ( 'vw_organisationproviders' );
		
		$organisation_list = $em->load ();
		
		if (count ( $_POST ) > 0) {
			$da = new DataAccess ();
			
			$args = array ();
			array_push ( $args, $da->helper_args ( 'fromdate', strtotime ( $_POST ['fromdate'] ), $da::TYPE_INTEGER ) );
			array_push ( $args, $da->helper_args ( 'todate', strtotime ( $_POST ['todate'] ), $da::TYPE_INTEGER ) );
			array_push ( $args, $da->helper_args ( 'statisticaltype', $_POST ['type'], $da::TYPE_INTEGER ) );
			array_push ( $args, $da->helper_args ( 'orgid', $_POST ['organisationid'], $da::TYPE_INTEGER ) );
			array_push ( $args, $da->helper_args ( 'status', __RECORD_STATUS_UNCOMPLETED . "," . __RECORD_STATUS_DUPLICATE . "," . __RECORD_STATUS_COMPLETED . "," . __RECORD_STATUS_WITH_ERRORS, $da::TYPE_TEXT ) );
			
			$sql = "select id , statisticaltypeid , organisationname , statuscodeid , setdate , fromperiod ,toperiod , annotation ,orgid
					from base.datasetfileselect(:fromdate,:todate, :statisticaltype, :orgid, :status)";
			
			$list = $da->func_get ( $sql, $args );
		}
		
		/**
		 * verify files on filesystem *
		 */
		$fileoklist = array ();
		foreach ( $list as $rfile ) {
			$ftype = $rfile->statisticaltypeid == __STATISTICAL_TYPE_VICTIMS ? 'victims' : ($rfile->statisticaltypeid == __STATISTICAL_TYPE_TRAFFICKERS ? 'traffickers' : '');
			$fileok = FileManager::verifyfile ( $rfile->orgid, $rfile->id, $ftype );
			if ($fileok)
				array_push ( $fileoklist, $rfile->id );
		}
		/* ----------------------------- */
		
		$this->screen ( $this->contextname . "/index", array (
				'list' => $list,
				'fileoklist' => $fileoklist,
				'pvars' => $pvars,
				'navkey' => $navkey,
				'organisation_list' => $organisation_list 
		) );
	}
	
	/**
	 * Request syncronization from EFP with NFP org id via ws uploading dataset files
	 */
	function sync() {
		if ($_REQUEST ['orgid']) {
			
			$filename = __EFP_WSGET_URL . '?orgid=' . $_REQUEST ['orgid'];
			
			$h = fopen ( $filename, 'r' );
			
			$this->screen ( $this->contextname . "/endsync", array () );
		}
	}
}

?>