<?php

require_once "app/class-organisation.php";
require_once "app/class-lov-manager.php";
require_once "app/class-data-provisions.php";
require_once 'includes/data-access/class-transaction.php';

/**
 * Common Model context
 *
 * Enables Organisation management
 *
 * @author balexandre - Advantis
 * @version 1.0.1
 * @package Backend\Organisations
 */
class context_organizations extends context {
	public $contextname = "organizations";
	
	/**
	 * Constructor & Authorization
	 */
	function context_organizations() {
		main::check_auth_session ();
	}
	
	/**
	 * 
	 * Context entry point, shows organisation list
	 */
	function index() {
		$em = new EntityManager ( 'organisations' );
		
		$list = $em->load ();
		
		$em = new EntityManager ( DataProvisions::LISTVIEW );
		
		$listDPA = $em->load ( "provisionagreements_active is true" );
		
		$this->screen ( 'organizations/index', array (
				'list' => $list,
				'listdpa' => $listDPA 
		) );
	}
	
	/**
	 *
	 * Shows new organisation screen
	 * @param string $pvars        	
	 */
	function neworganization($pvars = null) {
		$em = new EntityManager ( "languages" );
		
		$language_list = $em->load ( "active is true" );
		
		$lm = new LovManager ();
		
		$listRegType = $lm->getLov_RegisteringOrganisation ();
		
		$em = new EntityManager ( "organisationtypes" );
		
		$orgtype_list = $em->load ( "active=true" );
		
		$this->screen ( 'organizations/detail', array (
				'pvars' => $pvars,
				'orgtype_list' => $orgtype_list,
				'lang_list' => $language_list,
				'reg_list' => $listRegType 
		) );
	}
	
	/**
	 * 
	 * Creates a new organisation
	 */
	function create() {
		//if (!empty ( filter_input_array ( INPUT_POST ) )) {
			 if ($_POST) {
			try {
				$needrollback = false;
				Transaction::beginTransaction ();
				
				$em = new EntityManager ( 'organisations' );
				
				$org = new Organisation ();
				// TODO : Check is ALL fields not empty
				$org->organisationname = $_POST ["organisationname"];
				$org->internationalname = $_POST ["internationalname"];
				$org->languageid = $_POST ["languageid"];
				$org->registercodeid = $_POST ["registercodeid"];
				
				$orgid = null;
				
				$neworg = $em->create ( $org );
				
				if (isset ( $neworg->id )) {
					$em = new EntityManager ( "organisation_organisationtypes" );
					
					foreach ( $_POST [organisationtype] as $typeid ) {
						
						$orgtype = new stdClass ();
						$orgtype->organisationid = $neworg->id;
						$orgtype->organisationtypeid = $typeid;
						
						// print_r($orgtype);exit();
						
						$orgtyperes = $em->create ( $orgtype );
						
						if (! isset ( $orgtyperes->id )) {
							$needrollback = true;
						}
					}
				} else { // error creating org
					$needrollback = true;
				}
				
				if ($needrollback) {
					Transaction::rollback ();
					
					LogManagement::log ( "New Organisation error", "create", "organisations", __LOGTYPE_SECURITY, __LOGLEVEL_ERROR );
					setNotification ( getError ( "msg_error_new_organisation" ) , Notification::TYPE_ERROR);
				} else {
					Transaction::commit ();
					setNotification ( getSuccess ( "msg_new_organisation" ) );
					LogManagement::log ( "New Organisation (" . $_POST ["organisationname"] . ") created", "create", "organisations", __LOGTYPE_SECURITY );
				}
			} catch ( Exception $exp ) {
				Transaction::rollback ();
				dump_errorlog ( 'Organizations', 'create', $exp->getMessage () );
			}
		}
		header ( 'Location:' . __SITEBASE . '/' . $this->contextname );
	}
	
	/**
	 *
	 * Shows the organisation eedition screen
	 * @param string $pvars        	
	 */
	function edit($pvars = null) {
		$org = null;
		
		$orgid = $_REQUEST ["id"];
		
		if ($orgid) {
			$org = new Organisation ( $orgid );
		}
		
		$em = new EntityManager ( "languages" );
		
		$language_list = $em->load ( "active is true" );
		
		$em = new EntityManager ( "users" );
		
		$user_list = $em->load ( "organisationid=:orgid AND active=true", array(':orgid' => $orgid ) );
		
		$em = new EntityManager ( "organisationtypes" );
		
		$orgtype_list = $em->load ( "active=true" );
		
		$em = new EntityManager ( "organisation_organisationtypes" );
		
		$org_orgtypes = $em->load ( "organisationid=:orgid", array(':orgid' => $orgid ));
		
		$lm = new LovManager ();
		
		$listRegType = $lm->getLov_RegisteringOrganisation ();
		
		$orgtypes = array ();
		
		foreach ( $org_orgtypes as $orgtype ) {
			
			array_push ( $orgtypes, $orgtype->organisationtypeid );
		}
		$dpa = new EntityManager ( DataProvisions::LISTVIEW );
		$listDPA = $dpa->load ( "provisionagreements_active is true" );
		
		$this->screen ( 'organizations/detail', array (
				'org' => $org,
				'lang_list' => $language_list,
				'user_list' => $user_list,
				'orgtype_list' => $orgtype_list,
				'orgtypes' => $orgtypes,
				'pvars' => $pvars,
				'reg_list' => $listRegType,
				'listdpa' => $listDPA 
		) );
	}
	
	/**
	 * 
	 * Saves organisation posted data
	 */
	function save() {
		
		// not allowed for main organisation
		if ($_POST ["id"] && $_POST ["id"] != 1) {
			
			// check errors
			//
			$orgid = $_POST ["id"];
			try {
				$needrollback = false;
				Transaction::beginTransaction ();
				$org = new Organisation ( $orgid );
				
				$org->organisationname = $_POST ["organisationname"];
				$org->internationalname = $_POST ["internationalname"];
				$org->languageid = $_POST ["languageid"];
				if ($_POST ['userid'] > 0) {
					$org->userid = $_POST ["userid"];
				}
				$org->registercodeid = $_POST ["registercodeid"];
				
				$org->save ();
				
				// delete types
				if (isset ( $org->id )) {
					
					// reassign types
					$em = new EntityManager ( "organisation_organisationtypes" );
					if (! empty ( $_POST ["organisationtype"] )) {
						$da = new DataAccess ();
						$cfgdb = new ConfigDB ();
						$schema = $cfgdb->connections ["DEFAULT"] ["DBSCHEMA"];
						
						$da->func_get ( "DELETE FROM " . $schema . ".organisation_organisationtypes WHERE organisationid=:orgid", array(':orgid' => $orgid) );
						
						foreach ( $_POST ["organisationtype"] as $typeid ) {
							
							$orgtype = new stdClass ();
							$orgtype->organisationid = $org->id;
							$orgtype->organisationtypeid = $typeid;
							// print_r($orgtype);exit();
							
							$orgres = $em->create ( $orgtype );
							
							if (! isset ( $orgres->id )) {
								$needrollback = true;
							}
						}
					}
				} else { // error
					$needrollback = true;
				}
				
				if ($needrollback) {
					Transaction::rollback ();
					
					LogManagement::log ( "Save organisation " . $orgid . " error", "update", "organisations", __LOGTYPE_DATA, __LOGLEVEL_ERROR );
					setNotification ( getError ( "msg_save_organisation_error" ) , Notification::TYPE_ERROR);
				} else {
					Transaction::commit ();
					setNotification ( getSuccess ( "msg_save_organisation_ok" ) );
					LogManagement::log ( "Save Organisation " . $orgid, "update", "organisations", __LOGTYPE_DATA );
				}
			} catch ( Exception $exp ) {
				Transaction::rollback ();
				dump_errorlog ( 'Organisations', 'save', $exp->getMessage () );
				header ( 'Location:' . __SITEBASE . '/' . $this->contextname );
			}
		} else {
			LogManagement::log ( "Main Organisation can not be edit", "update", "organisations", __LOGTYPE_SECURITY, __LOGLEVEL_ERROR );
		}
		header ( 'Location:' . __SITEBASE . '/' . $this->contextname );
	}
	
	/**
	 * 
	 * Disables a given organisation
	 */
	function disable() {
		$orgid = $_REQUEST ["id"];
		$em = new EntityManager ( "users" );
		$user_list = $em->load ( "organisationid=:orgid AND active=TRUE", array(':orgid' => $orgid) );
		$em = new EntityManager ( "provisionagreements" );
		$orgtype_list = $em->load ( "fromorganisationid=:orgid AND active=TRUE", array(':orgid' => $orgid));
		$org_users = array_filter ( $user_list );
		$data_providers = array_filter ( $orgtype_list );
		if (empty ( $org_users ) && empty ( $org_users )) {
			$org = new Organisation ( $orgid );
			$org->active = 0;
			$org->save ();
			
			setNotification ( getSuccess ( "msg_disable_organisation_ok" ) );
			
			LogManagement::log ( "Organisation " . $org->organisationname . " as been disable", "update", "organisations", __LOGTYPE_SECURITY );
		}
		
		header ( 'Location:' . __SITEBASE . '/' . $this->contextname );
	}
	
	/**
	 * 
	 * Deletes an organisation
	 */
	function delete() {
		$orgid = $_REQUEST ["id"];
		$em = new EntityManager ( "users" );
		$user_list = $em->load ( "organisationid=?", array (
				$orgid 
		) );
		$em = new EntityManager ( "provisionagreements" );
		$dpas = $em->load ( "fromorganisationid=?", array (
				$orgid 
		) );
		
		if (empty ( $user_list ) && empty ( $dpas )) {
			
			// delete Orgtypes
			
			$em = new EntityManager ( "organisation_organisationtypes" );
			$orgtype_list = $em->load ( "organisationid=?", array (
					$orgid 
			) );
			
			foreach ( $orgtype_list as $orgtype ) {
				$orgtype->delete ();
			}
			//
			
			$org = new Organisation ( $orgid );
			$org->id = $orgid;
			$org->delete ();
			
			setNotification ( getSuccess ( "msg_delete_organisation_ok" ) );
			
			LogManagement::log ( "Organisation " . $org->organisationname . " removed", "delete", "organisations", __LOGTYPE_SECURITY );
		}
		header ( 'Location:' . __SITEBASE . '/' . $this->contextname );
	}
}
?>