<commit_before><?php

$page_access = 'guest';
require_once __DIR__ . '/includes/inc_default.php';
require_once __DIR__ . '/includes/inc_transactions.php';

$orderby = $_GET['orderby'] ?? 'cdate';
$asc = $_GET['asc'] ?? 0;
$limit = $_GET['limit'] ?? 25;
$start = $_GET['start'] ?? 0;
$id = $_GET['id'] ?? false;
$add = isset($_GET['add']) ? true : false;
$submit = isset($_POST['zend']) ? true : false;

$mid = $_GET['mid'] ?? false;
$tuid = $_GET['tuid'] ?? false;
$tus = $_GET['tus'] ?? false;
$fuid = $_GET['fuid'] ?? false;
$uid = $_GET['uid'] ?? false;
$inline = isset($_GET['inline']) ? true : false;

$q = $_GET['q'] ?? '';
$fcode = $_GET['fcode'] ?? '';
$tcode = $_GET['tcode'] ?? '';
$andor = $_GET['andor'] ?? 'and';
$fdate = $_GET['fdate'] ?? '';
$tdate = $_GET['tdate'] ?? '';

/**
 * add
 */
if ($add)
{
	if ($s_guest)
	{
		$app['eland.alert']->error('Je hebt geen rechten om een transactie toe te voegen.');
		cancel();
	}

	$transaction = [];

	$redis_transid_key = $schema . '_transid_u_' . $s_id;

	if ($submit)
	{
		$stored_transid = $app['redis']->get($redis_transid_key);

		if (!$stored_transid)
		{
			$errors[] = 'Formulier verlopen.';
		}

		$transaction['transid'] = $_POST['transid'];
		$transaction['description'] = $_POST['description'];

		list($letscode_from) = explode(' ', $_POST['letscode_from']);
		list($letscode_to) = explode(' ', $_POST['letscode_to']);

		$transaction['amount'] = $amount = ltrim($_POST['amount'], '0 ');;
		$transaction['date'] = gmdate('Y-m-d H:i:s');

		$group_id = $_POST['group_id'];

		if ($stored_transid != $transaction['transid'])
		{
			$errors[] = 'Fout transactie id.';
		}

		if ($app['db']->fetchColumn('select transid from transactions where transid = ?', [$stored_transid]))
		{
			$errors[] = 'Een herinvoer van de transactie werd voorkomen.';
		}

		if (strlen($transaction['description']) > 60)
		{
			$errors[] = 'De omschrijving mag maximaal 60 tekens lang zijn.';
		}

		if ($group_id != 'self')
		{
			$group = $app['db']->fetchAssoc('SELECT * FROM letsgroups WHERE id = ?', [$group_id]);

			if (!isset($group))
			{
				$errors[] = 'Letsgroep niet gevonden.';
			}
		}

		if ($s_user && !$s_master)
		{
			$fromuser = $app['db']->fetchAssoc('SELECT * FROM users WHERE id = ?', [$s_id]);
		}
		else
		{
			$fromuser = $app['db']->fetchAssoc('SELECT * FROM users WHERE letscode = ?', [$letscode_from]);
		}

		$letscode_touser = ($group_id == 'self') ? $letscode_to : $group['localletscode'];

		$touser = $app['db']->fetchAssoc('select * from users where letscode = ?', [$letscode_touser]);

		if ($group_id == 'self')
		{
			if ($touser['status'] == 7)
			{
				$errors[] = 'Je kan niet rechtstreeks naar een interletsrekening overschrijven.';
			}
		}

		if ($fromuser['status'] == 7)
		{
			$errors[] = 'Je kan niet rechtstreeks van een interletsrekening overschrijven.';
		}

		$transaction['id_from'] = $fromuser['id'];
		$transaction['id_to'] = $touser['id'];

		if (!$transaction['description'])
		{
			$errors[]= 'De omschrijving is niet ingevuld';
		}

		if (!$transaction['amount'])
		{
			$errors[] = 'Bedrag is niet ingevuld';
		}

		else if (!(ctype_digit((string) $transaction['amount'])))
		{
			$errors[] = 'Het bedrag is geen geldig getal';
		}

		if(($fromuser['saldo'] - $amount) < $fromuser['minlimit'] && !$s_admin)
		{
			$errors[] = 'Je beschikbaar saldo laat deze transactie niet toe';
		}

		if(empty($fromuser))
		{
			$errors[] = 'Gebruiker bestaat niet';
		}

		if (!strlen($letscode_to))
		{
			$errors[] = 'Geen letscode ingevuld';
		}

		if(empty($touser))
		{
			if ($group_id == 'self')
			{
				$errors[] = 'Bestemmeling bestaat niet';
			}
			else
			{
				$errors[] = 'De interletsrekening bestaat niet';
			}
		}

		if($fromuser['letscode'] == $touser['letscode'])
		{
			$errors[] = 'Van en Aan letscode zijn hetzelfde';
		}

		if(($touser['saldo'] + $transaction['amount']) > $touser['maxlimit'] && !$s_admin)
		{
			$t_account = ($group_id == 'self') ? 'bestemmeling' : 'interletsrekening';
			$errors[] = 'De ' . $t_account . ' heeft zijn maximum limiet bereikt.';
		}

		if($group_id == 'self'
			&& !$s_admin
			&& !($touser['status'] == '1' || $touser['status'] == '2'))
		{
			$errors[] = 'De bestemmeling is niet actief';
		}

		if ($s_user)
		{
			$balance_eq = readconfigfromdb('balance_equilibrium');

			if (($fromuser['status'] == 2) && (($fromuser['saldo'] - $amount) < $balance_eq))
			{
				$errors[] = 'Als uitstapper kan je geen ' . $amount . ' ' . readconfigfromdb('currency') . ' uitgeven.';
			}

			if (($touser['status'] == 2) && (($touser['saldo'] + $amount) > $balance_eq))
			{
				$dest = ($group_id == 'self') ? 'De bestemmeling' : 'De letsgroep';
				$errors[] = $dest . ' is uitstapper en kan geen ' . $amount . ' ' . readconfigfromdb('currency') . ' ontvangen.';
			}
		}

		if (!$transaction['date'])
		{
			$errors[] = 'Datum is niet ingevuld';
		}
		else if (strtotime($transaction['date']) == -1)
		{
			$errors[] = 'Fout in datumformaat (jjjj-mm-dd)';
		}

		if ($error_token = $app['eland.form_token']->get_error())
		{
			$errors[] = $error_token;
		}

		$contact_admin = ($s_admin) ? '' : ' Contacteer een admin.';

		if (isset($group['url']))
		{
			$group_domain = get_host($group);
		}
		else
		{
			$group_domain = false;
		}

		if(count($errors))
		{
			$app['eland.alert']->error($errors);
		}
		else if ($group_id == 'self')
		{
			if ($id = insert_transaction($transaction))
			{
				$transaction['id'] = $id;
				mail_transaction($transaction);
				$app['eland.alert']->success('Transactie opgeslagen');
			}
			else
			{
				$app['eland.alert']->error('Gefaalde transactie');
			}

			cancel();
		}
		else if ($group['apimethod'] == 'mail')
		{
			if ($id = insert_transaction($transaction))
			{
				$transaction['id'] = $id;
				$transaction['letscode_to'] = $letscode_to;

				mail_mail_interlets_transaction($transaction);

				$app['eland.alert']->success('Interlets transactie opgeslagen (verwerking per mail).');
			}
			else
			{
				$app['eland.alert']->error('Gefaalde interlets transactie');
			}

			cancel();
		}
		else if ($group['apimethod'] != 'elassoap')
		{
			$app['eland.alert']->error('Interlets groep ' . $group['groupname'] . ' heeft geen geldige api methode.' . $contact_admin);

			cancel();
		}
		else if (!$group_domain)
		{
			$app['eland.alert']->error('Geen url voor interlets groep ' . $group['groupname'] . '. ' . $contact_admin);

			cancel();
		}
		else if (!(isset($schemas[$group_domain])))
		{
			// The interlets group uses eLAS or is on another server

			if (!$group['remoteapikey'])
			{
				$errors[] = 'Geen apikey voor deze interlets groep ingesteld.' . $contact_admin;
			}

			if (!$group['presharedkey'])
			{
				$errors[] = 'Geen preshared key voor deze interlets groep ingesteld.' . $contact_admin;
			}

			if (!$group['myremoteletscode'])
			{
				$errors[] = 'Geen remote letscode ingesteld voor deze interlets groep.' . $contact_admin;
			}

			$currencyratio = readconfigfromdb('currencyratio');

			if (!$currencyratio || !ctype_digit((string) $currencyratio) || $currencyratio < 1)
			{
				$errors[] = 'De currencyratio is niet correct ingesteld. ' . $contact_admin;
			}

			if (strlen($letscode_to))
			{
				$active_users = json_decode($app['redis']->get($group['url'] . '_typeahead_data'), true);

				$user_letscode_found = false;

				foreach ($active_users as $active_user)
				{
					if ($active_user['c'] == $letscode_to)
					{
						$real_name_to = $active_user['n'];
						$user_letscode_found = true;
						break;
					}
				}

				if ($user_letscode_found)
				{
					if(!$real_name_to)
					{
						$errors[] = 'Er werd geen naam gevonden voor de gebruiker van de interlets groep.';
					}
				}
				else
				{
					$errors[] = 'Er werd geen gebruiker gevonden met letscode ' . $letscode_to;
				}
			}

			if (count($errors))
			{
				$app['eland.alert']->error($errors);
				cancel();
			}

			$trans = $transaction;

			$trans['amount'] = $trans['amount'] / $currencyratio;
			$trans['amount'] = (float) $trans['amount'];
			$trans['amount'] = round($trans['amount'], 5);

			$trans['letscode_to'] = $letscode_to;

			$soapurl = ($group['elassoapurl']) ?: $group['url'] . '/soap';
			$soapurl .= '/wsdlelas.php?wsdl';

			$client = new nusoap_client($soapurl, true);

			$error = $client->getError();

			if ($error)
			{
				$app['eland.alert']->error('eLAS soap error: ' . $error . ' <br>' . $contact_admin);
				cancel();				
			}

			$result = $client->call('dopayment', [
				'apikey' 		=> $group['remoteapikey'],
				'from' 			=> $group['myremoteletscode'],
				'real_from' 	=> link_user($fromuser, false, false),
				'to' 			=> $letscode_to,
				'description' 	=> $trans['description'],
				'amount' 		=> $trans['amount'],
				'transid' 		=> $trans['transid'],
				'signature' 	=> sign_transaction($trans, trim($group['presharedkey'])),
			]);

			$error = $client->getError();

			if ($error)
			{
				$app['eland.alert']->error('eLAS soap error: ' . $error . ' <br>' . $contact_admin);
				cancel();
			}

			if ($result == 'OFFLINE')
			{
				$errors[] = 'De andere letsgroep is offline. Probeer het later opnieuw. ';
			}

			if ($result == 'FAILED')
			{
				$errors[] = 'De interlets transactie is gefaald.' . $contact_admin;
			}

			if ($result == 'SIGFAIL')
			{
				$errors[] = 'De signatuur van de interlets transactie is gefaald. ' . $contact_admin;
			}

			if ($result == 'DUPLICATE')
			{
				$errors[] = 'De transactie bestaat reeds in de andere letsgroep. ' . $contact_admin;
			}

			if ($result == 'NOUSER')
			{
				$errors[] = 'De gebruiker in de interletsgroep werd niet gevonden. ';
			}

			if ($result == 'APIKEYFAIL')
			{
				$errors[] = 'De apikey is niet correct. ' . $contact_admin;
			}

			if (!count($errors) && $result != 'SUCCESS')
			{
				$errors[] = 'De interlets transactie kon niet verwerkt worden. ' . $contact_admin;
			}
				
			if (count($errors))
			{
				$app['eland.alert']->error($errors);
				cancel();
			}

			$transaction['real_to'] = $letscode_to . ' ' . $real_name_to;

			$app['monolog']->debug('insert transation: --  ' . http_build_query($transaction) . ' --');

			$id = insert_transaction($transaction);

			if (!$id)
			{				
				$subject = 'Interlets FAILURE!';
				$text = 'WARNING: LOCAL COMMIT OF TRANSACTION ' . $transaction['transid'] . ' FAILED!!!  This means the transaction is not balanced now!';
				$text .= ' group:' . $group['groupname'];

				mail_q(['to' => 'admin', 'subject' => $subject, 'text' => $text]);

				$app['eland.alert']->error('De lokale commit van de interlets transactie is niet geslaagd. ' . $contact_admin);
				cancel();
			}

			$transaction['id'] = $id;

			mail_transaction($transaction);

			$app['eland.alert']->success('De interlets transactie werd verwerkt.');
			cancel();
		}
		else
		{
			// the interlets group is on the same server (eLAND)

			$remote_schema = $schemas[$group_domain];

			$to_remote_user = $app['db']->fetchAssoc('select *
				from ' . $remote_schema . '.users
				where letscode = ?', [$letscode_to]);

			if (!$to_remote_user)
			{
				$errors[] = 'De interlets gebruiker bestaat niet.';
			}

			if (!in_array($to_remote_user['status'], ['1', '2']))
			{
				$errors[] = 'De interlets gebruiker is niet actief.';
			}

			$remote_group = $app['db']->fetchAssoc('select *
				from ' . $remote_schema . '.letsgroups
				where url = ?', [$app['eland.base_url']]);

			if (!$remote_group)
			{
				$errors[] = 'De remote interlets groep heeft deze letsgroep ('. readconfigfromdb('systemname') . ') niet geconfigureerd.';
			}

			if (!$remote_group['localletscode'])
			{
				$errors[] = 'Er is geen interlets account gedefiniëerd in de remote interlets groep.';
			}

			$remote_interlets_account = $app['db']->fetchAssoc('select *
				from ' . $remote_schema . '.users
				where letscode = ?', [$remote_group['localletscode']]);

			if (!$remote_interlets_account)
			{
				$errors[] = 'Er is geen interlets account in de remote interlets group.';
			}

			if ($remote_interlets_account['accountrole'] != 'interlets')
			{
				$errors[] = 'Het interlets account in de remote interlets groep heeft geen juiste rol. Deze moet van het type interlets zijn.';
			}

			if (!in_array($remote_interlets_account['status'], [1, 2, 7]))
			{
				$errors[] = 'Het interlets account in de remote interlets groep heeft geen juiste status. Deze moet van het type extern, actief of uitstapper zijn.';
			}

			$remote_currency = readconfigfromdb('currency', $remote_schema);
			$remote_currencyratio = readconfigfromdb('currencyratio', $remote_schema);
			$remote_balance_eq = readconfigfromdb('balance_equilibrium', $remote_schema);
			$currencyratio = readconfigfromdb('currencyratio');

			if (!$currencyratio || !ctype_digit((string) $currencyratio) || $currencyratio < 1)
			{
				$errors[] = 'De currencyratio is niet correct ingesteld. ' . $contact_admin;
			}

			if (!$remote_currencyratio ||
				!ctype_digit((string) $remote_currencyratio)
				|| $remote_currencyratio < 1)
			{
				$errors[] = 'De currencyratio van de andere groep is niet correct ingesteld. ' . $contact_admin;
			}

			$remote_amount = round(($transaction['amount'] * $remote_currencyratio) / $currencyratio);

			if ($remote_amount < 1)
			{
				$errors[] = 'Het bedrag is te klein want het kan niet uitgedrukt worden in de gebruikte munt van de interletsgroep.';
			} 

			if(($remote_interlets_account['saldo'] - $remote_amount) < $remote_interlets_account['minlimit'])
			{
				$errors[] = 'De interlets account van de remote interlets groep heeft onvoldoende saldo beschikbaar.';
			}

			if(($to_remote_user['saldo'] + $remote_amount) > $to_remote_user['maxlimit'])
			{
				$errors[] = 'De interlets gebruiker heeft zijn maximum limiet bereikt.';
			}

			if (($remote_interlets_account['status'] == 2) && (($remote_interlets_account['saldo'] - $remote_amount) < $remote_balance_eq))
			{
				$errors[] = 'Het remote interlets account heeft de status uitstapper en kan geen ' . $remote_amount . ' ' . $remote_currency . ' uitgeven (' . $amount . ' ' . readconfigfromdb('currency') . ').';
			}

			if (($to_remote_user['status'] == 2) && (($to_remote_user['saldo'] + $remote_amount) > $remote_balance_eq))
			{
				$errors[] = 'De remote bestemmeling is uitstapper en kan geen ' . $remote_amount . ' ' . $remote_currency . ' ontvangen (' . $amount . ' ' . readconfigfromdb('currency') . ').';
			}

			if (count($errors))
			{
				$app['eland.alert']->error($errors);
				cancel();
			}

			//
			$transaction['creator'] = ($s_master) ? 0 : $s_id;
			$transaction['cdate'] = gmdate('Y-m-d H:i:s');
			$transaction['real_to'] = $to_remote_user['letscode'] . ' ' . $to_remote_user['name'];

			$app['db']->beginTransaction();

			try
			{
				$app['db']->insert('transactions', $transaction);
				$id = $app['db']->lastInsertId('transactions_id_seq');
				$app['db']->executeUpdate('update users
					set saldo = saldo + ? where id = ?',
					[$transaction['amount'], $transaction['id_to']]);
				$app['db']->executeUpdate('update users
					set saldo = saldo - ? where id = ?',
					[$transaction['amount'], $transaction['id_from']]);

				$trans_org = $transaction;
				$trans_org['id'] = $id;

				$transaction['creator'] = 0;
				$transaction['amount'] = $remote_amount;
				$transaction['id_from'] = $remote_interlets_account['id'];
				$transaction['id_to'] = $to_remote_user['id'];
				$transaction['real_from'] = link_user($fromuser['id'], false, false);
				unset($transaction['real_to']);

				$app['db']->insert($remote_schema . '.transactions', $transaction);
				$id = $app['db']->lastInsertId($remote_schema . '.transactions_id_seq');
				$app['db']->executeUpdate('update ' . $remote_schema . '.users
					set saldo = saldo + ? where id = ?',
					[$remote_amount, $transaction['id_to']]);
				$app['db']->executeUpdate('update ' . $remote_schema . '.users
					set saldo = saldo - ? where id = ?',
					[$transaction['amount'], $transaction['id_from']]);
				$transaction['id'] = $id;

				$app['db']->commit();

			}
			catch(Exception $e)
			{
				$app['db']->rollback();
				$app['eland.alert']->error('Transactie niet gelukt.');
				throw $e;
				exit;
			}

			readuser($fromuser['id'], true);
			readuser($touser['id'], true);

			readuser($remote_interlets_account['id'], true, $remote_schema);
			readuser($to_remote_user['id'], true, $remote_schema);

			mail_transaction($trans_org);
			mail_transaction($transaction, $remote_schema);

			$app['monolog']->info('direct interlets transaction ' . $transaction['transid'] . ' amount: ' .
				$amount . ' from user: ' .  link_user($fromuser['id'], false, false) .
				' to user: ' . link_user($touser['id'], false, false));

			$app['monolog']->info('direct interlets transaction (receiving) ' . $transaction['transid'] .
				' amount: ' . $remote_amount . ' from user: ' . $remote_interlets_account['letscode'] . ' ' .
				$remote_interlets_account['name'] . ' to user: ' . $to_remote_user['letscode'] . ' ' .
				$to_remote_user['name'], ['schema' => $remote_schema]);

			autominlimit_queue($transaction['id_from'], $transaction['id_to'], $remote_amount, $remote_schema);

			$app['eland.alert']->success('Interlets transactie uitgevoerd.');
			cancel();
		}

		$transaction['letscode_to'] = $_POST['letscode_to'];
		$transaction['letscode_from'] = ($s_admin || $s_master) ? $_POST['letscode_from'] : link_user($s_id, false, false);
	}
	else
	{
		//GET form

		$transid = generate_transid();

		$app['redis']->set($redis_transid_key, $transid);
		$app['redis']->expire($redis_transid_key, 3600);

		$transaction = [
			'date'			=> gmdate('Y-m-d H:i:s'),
			'letscode_from'	=> ($s_master) ? '' : link_user($s_id, false, false),
			'letscode_to'	=> '',
			'amount'		=> '',
			'description'	=> '',
			'transid'		=> $transid,
		];

		$group_id = 'self';
		$to_schema_table = '';

		if ($tus)
		{
			if (isset($hosts[$tus]))
			{
				$host_from_tus = $hosts[$tus];

				$group_id = $app['db']->fetchColumn('select id
					from letsgroups
					where url = ?', [$app['eland.protocol'] . $host_from_tus]);
				$to_schema_table = $tus . '.';
			}
		}

		if ($mid && !($tus xor $host_from_tus))
		{
			$row = $app['db']->fetchAssoc('SELECT
					m.content, m.amount, m.id_user, u.letscode, u.name, u.status
				from ' . $to_schema_table . 'messages m,
					'. $to_schema_table . 'users u
				where u.id = m.id_user
					and m.id = ?', [$mid]);

			if (($s_admin && !$tus) || $row['status'] == 1 || $row['status'] == 2)
			{
				$transaction['letscode_to'] = $row['letscode'] . ' ' . $row['name'];
				$transaction['description'] =  substr('#m.' . $to_schema_table . $mid . ' ' . $row['content'], 0, 60);
				$amount = $row['amount'];
				if ($tus)
				{
					$amount = round((readconfigfromdb('currencyratio') * $amount) / readconfigfromdb('currencyratio', $tus));
				}
				$transaction['amount'] = $amount;
				$tuid = $row['tuid'];
			}
		}
		else if ($tuid)
		{
			$row = readuser($tuid, false, ((isset($host_from_tus)) ? $tus : false));

			if (($s_admin && !$tus) || $row['status'] == 1 || $row['status'] == 2)
			{
				$transaction['letscode_to'] = $row['letscode'] . ' ' . $row['name'];
			}
		}

		if ($fuid && $s_admin && ($fuid != $tuid))
		{
			$row = readuser($fuid);
			$transaction['letscode_from'] = $row['letscode'] . ' ' . $row['name'];
		}

		if ($tuid == $s_id && !$fuid && $tus != $schema)
		{
			$transaction['letscode_from'] = '';
		}
	}

	$app['eland.assets']->add(['typeahead', 'typeahead.js']);

	$balance = $session_user['saldo'];

	$groups = $app['db']->fetchAll('SELECT id, groupname, url FROM letsgroups where apimethod <> \'internal\'');

	$groups = array_merge([[
		'groupname' => readconfigfromdb('systemname'),
		'id'		=> 'self',
	]], $groups);

	$top_buttons .= aphp('transactions', [], 'Lijst', 'btn btn-default', 'Transactielijst', 'exchange', true);

	if (!$s_master)
	{
		$top_buttons .= aphp('transactions', ['uid' => $s_id], 'Mijn transacties', 'btn btn-default', 'Mijn transacties', 'user', true);
	}

	$h1 = 'Nieuwe transactie';
	$fa = 'exchange';

	include __DIR__ . '/includes/inc_header.php';

	$minlimit = $session_user['minlimit'];

	if (!$s_master)
	{
		echo '<div>';
		echo '<p><strong>' . link_user($session_user) . ' huidige ' . readconfigfromdb('currency') . ' stand: ';
		echo '<span class="label label-info">' . $balance . '</span></strong> ';
		echo '<strong>Minimum limiet: <span class="label label-danger">' . $minlimit . '</span></strong></p>';
		echo '</div>';
	}

	echo '<div class="panel panel-info">';
	echo '<div class="panel-heading">';

	echo '<form  method="post" class="form-horizontal" autocomplete="off">';

	echo ($s_admin) ? '' : '<div style="display:none;">';

	echo '<div class="form-group"';
	echo ($s_admin) ? '' : ' disabled="disabled" ';
	echo '>';
	echo '<label for="letscode_from" class="col-sm-2 control-label">';
	echo '<span class="label label-info">Admin</span> ';
	echo 'Van letscode</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="letscode_from" name="letscode_from" ';
	echo 'data-typeahead-source="group_self" ';
	echo 'value="' . $transaction['letscode_from'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo ($s_admin) ? '' : '</div>';

	echo '<div class="form-group">';
	echo '<label for="group_id" class="col-sm-2 control-label">Aan letsgroep</label>';
	echo '<div class="col-sm-10">';
	echo '<select type="text" class="form-control" id="group_id" name="group_id">';

	foreach ($groups as $l)
	{
		echo '<option value="' . $l['id'] . '" ';

		if ($l['id'] == 'self')
		{
			echo 'id="group_self" ';

			if ($s_admin)
			{
				$typeahead = ['users_active', 'users_inactive', 'users_ip', 'users_im'];
			}
			else
			{
				$typeahead = 'users_active';
			}

			$typeahead = $app['eland.typeahead']->get($typeahead);
		}
		else
		{
			$typeahead = $app['eland.typeahead']->get('users_active', $l['url'], $l['id']);
		}

		echo 'data-typeahead="' . $typeahead . '"';
		echo ($l['id'] == $group_id) ? ' selected="selected" ' : '';
		echo '>' . htmlspecialchars($l['groupname'], ENT_QUOTES) . '</option>';
	}

	echo '</select>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="letscode_to" class="col-sm-2 control-label">Aan letscode</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="letscode_to" name="letscode_to" ';
	echo 'data-typeahead-source="group_id" ';
	echo 'value="' . $transaction['letscode_to'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="amount" class="col-sm-2 control-label">Aantal ' . readconfigfromdb('currency') . '</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="number" class="form-control" id="amount" name="amount" ';
	echo 'value="' . $transaction['amount'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="description" class="col-sm-2 control-label">Omschrijving</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="description" name="description" ';
	echo 'value="' . $transaction['description'] . '" required maxlength="60">';
	echo '</div>';
	echo '</div>';

	echo aphp('transactions', [], 'Annuleren', 'btn btn-default') . '&nbsp;';
	echo '<input type="submit" name="zend" value="Overschrijven" class="btn btn-success">';
	$app['eland.form_token']->generate();
	echo '<input type="hidden" name="transid" value="' . $transaction['transid'] . '">';

	echo '</form>';
	echo '</div>';
	echo '</div>';

	echo '<ul><small><i>';

	echo '<li>Tip: Het veld Aan LETSCode geeft autosuggesties door naam of letscode in te typen. ';
	echo 'Kies eerst de juiste letsgroep om de juiste suggesties te krijgen.</li>';

	echo '<li>';
	echo readconfigfromdb('currencyratio');
	echo ' ' . readconfigfromdb('currency') . ' staat gelijk aan 1 LETS-uur.</li>';

	echo '</i></small></ul>';

	include __DIR__ . '/includes/inc_footer.php';
	exit;
}

/*
 * interlets accounts schemas needed for interlinking users.
 */

$interlets_accounts_schemas = $app['eland.interlets_groups']->get_eland_accounts_schemas($schema);

$s_inter_schema_check = array_merge($eland_interlets_groups, [$s_schema => true]);

/**
 * show a transaction
 */

if ($id)
{
	$transaction = $app['db']->fetchAssoc('select t.*
		from transactions t
		where t.id = ?', [$id]);

	$inter_schema = false;

	if ($interlets_accounts_schemas[$transaction['id_from']])
	{
		$inter_schema = $interlets_accounts_schemas[$transaction['id_from']];
	}
	else if ($interlets_accounts_schemas[$transaction['id_to']])
	{
		$inter_schema = $interlets_accounts_schemas[$transaction['id_to']];
	}

	if ($inter_schema)
	{
		$inter_transaction = $app['db']->fetchAssoc('select t.*
			from ' . $inter_schema . '.transactions t
			where t.transid = ?', [$transaction['transid']]);
	}
	else
	{
		$inter_transaction = false;
	}

	$next = $app['db']->fetchColumn('select id
		from transactions
		where id > ?
		order by id asc
		limit 1', [$id]);

	$prev = $app['db']->fetchColumn('select id
		from transactions<commit_msg>fix unset var warnings<commit_after><?php

$page_access = 'guest';
require_once __DIR__ . '/includes/inc_default.php';
require_once __DIR__ . '/includes/inc_transactions.php';

$orderby = $_GET['orderby'] ?? 'cdate';
$asc = $_GET['asc'] ?? 0;
$limit = $_GET['limit'] ?? 25;
$start = $_GET['start'] ?? 0;
$id = $_GET['id'] ?? false;
$add = isset($_GET['add']) ? true : false;
$submit = isset($_POST['zend']) ? true : false;

$mid = $_GET['mid'] ?? false;
$tuid = $_GET['tuid'] ?? false;
$tus = $_GET['tus'] ?? false;
$fuid = $_GET['fuid'] ?? false;
$uid = $_GET['uid'] ?? false;
$inline = isset($_GET['inline']) ? true : false;

$q = $_GET['q'] ?? '';
$fcode = $_GET['fcode'] ?? '';
$tcode = $_GET['tcode'] ?? '';
$andor = $_GET['andor'] ?? 'and';
$fdate = $_GET['fdate'] ?? '';
$tdate = $_GET['tdate'] ?? '';

/**
 * add
 */
if ($add)
{
	if ($s_guest)
	{
		$app['eland.alert']->error('Je hebt geen rechten om een transactie toe te voegen.');
		cancel();
	}

	$transaction = [];

	$redis_transid_key = $schema . '_transid_u_' . $s_id;

	if ($submit)
	{
		$stored_transid = $app['redis']->get($redis_transid_key);

		if (!$stored_transid)
		{
			$errors[] = 'Formulier verlopen.';
		}

		$transaction['transid'] = $_POST['transid'];
		$transaction['description'] = $_POST['description'];

		list($letscode_from) = explode(' ', $_POST['letscode_from']);
		list($letscode_to) = explode(' ', $_POST['letscode_to']);

		$transaction['amount'] = $amount = ltrim($_POST['amount'], '0 ');;
		$transaction['date'] = gmdate('Y-m-d H:i:s');

		$group_id = $_POST['group_id'];

		if ($stored_transid != $transaction['transid'])
		{
			$errors[] = 'Fout transactie id.';
		}

		if ($app['db']->fetchColumn('select transid from transactions where transid = ?', [$stored_transid]))
		{
			$errors[] = 'Een herinvoer van de transactie werd voorkomen.';
		}

		if (strlen($transaction['description']) > 60)
		{
			$errors[] = 'De omschrijving mag maximaal 60 tekens lang zijn.';
		}

		if ($group_id != 'self')
		{
			$group = $app['db']->fetchAssoc('SELECT * FROM letsgroups WHERE id = ?', [$group_id]);

			if (!isset($group))
			{
				$errors[] = 'Letsgroep niet gevonden.';
			}
		}

		if ($s_user && !$s_master)
		{
			$fromuser = $app['db']->fetchAssoc('SELECT * FROM users WHERE id = ?', [$s_id]);
		}
		else
		{
			$fromuser = $app['db']->fetchAssoc('SELECT * FROM users WHERE letscode = ?', [$letscode_from]);
		}

		$letscode_touser = ($group_id == 'self') ? $letscode_to : $group['localletscode'];

		$touser = $app['db']->fetchAssoc('select * from users where letscode = ?', [$letscode_touser]);

		if ($group_id == 'self')
		{
			if ($touser['status'] == 7)
			{
				$errors[] = 'Je kan niet rechtstreeks naar een interletsrekening overschrijven.';
			}
		}

		if ($fromuser['status'] == 7)
		{
			$errors[] = 'Je kan niet rechtstreeks van een interletsrekening overschrijven.';
		}

		$transaction['id_from'] = $fromuser['id'];
		$transaction['id_to'] = $touser['id'];

		if (!$transaction['description'])
		{
			$errors[]= 'De omschrijving is niet ingevuld';
		}

		if (!$transaction['amount'])
		{
			$errors[] = 'Bedrag is niet ingevuld';
		}

		else if (!(ctype_digit((string) $transaction['amount'])))
		{
			$errors[] = 'Het bedrag is geen geldig getal';
		}

		if(($fromuser['saldo'] - $amount) < $fromuser['minlimit'] && !$s_admin)
		{
			$errors[] = 'Je beschikbaar saldo laat deze transactie niet toe';
		}

		if(empty($fromuser))
		{
			$errors[] = 'Gebruiker bestaat niet';
		}

		if (!strlen($letscode_to))
		{
			$errors[] = 'Geen letscode ingevuld';
		}

		if(empty($touser))
		{
			if ($group_id == 'self')
			{
				$errors[] = 'Bestemmeling bestaat niet';
			}
			else
			{
				$errors[] = 'De interletsrekening bestaat niet';
			}
		}

		if($fromuser['letscode'] == $touser['letscode'])
		{
			$errors[] = 'Van en Aan letscode zijn hetzelfde';
		}

		if(($touser['saldo'] + $transaction['amount']) > $touser['maxlimit'] && !$s_admin)
		{
			$t_account = ($group_id == 'self') ? 'bestemmeling' : 'interletsrekening';
			$errors[] = 'De ' . $t_account . ' heeft zijn maximum limiet bereikt.';
		}

		if($group_id == 'self'
			&& !$s_admin
			&& !($touser['status'] == '1' || $touser['status'] == '2'))
		{
			$errors[] = 'De bestemmeling is niet actief';
		}

		if ($s_user)
		{
			$balance_eq = readconfigfromdb('balance_equilibrium');

			if (($fromuser['status'] == 2) && (($fromuser['saldo'] - $amount) < $balance_eq))
			{
				$errors[] = 'Als uitstapper kan je geen ' . $amount . ' ' . readconfigfromdb('currency') . ' uitgeven.';
			}

			if (($touser['status'] == 2) && (($touser['saldo'] + $amount) > $balance_eq))
			{
				$dest = ($group_id == 'self') ? 'De bestemmeling' : 'De letsgroep';
				$errors[] = $dest . ' is uitstapper en kan geen ' . $amount . ' ' . readconfigfromdb('currency') . ' ontvangen.';
			}
		}

		if (!$transaction['date'])
		{
			$errors[] = 'Datum is niet ingevuld';
		}
		else if (strtotime($transaction['date']) == -1)
		{
			$errors[] = 'Fout in datumformaat (jjjj-mm-dd)';
		}

		if ($error_token = $app['eland.form_token']->get_error())
		{
			$errors[] = $error_token;
		}

		$contact_admin = ($s_admin) ? '' : ' Contacteer een admin.';

		if (isset($group['url']))
		{
			$group_domain = get_host($group);
		}
		else
		{
			$group_domain = false;
		}

		if(count($errors))
		{
			$app['eland.alert']->error($errors);
		}
		else if ($group_id == 'self')
		{
			if ($id = insert_transaction($transaction))
			{
				$transaction['id'] = $id;
				mail_transaction($transaction);
				$app['eland.alert']->success('Transactie opgeslagen');
			}
			else
			{
				$app['eland.alert']->error('Gefaalde transactie');
			}

			cancel();
		}
		else if ($group['apimethod'] == 'mail')
		{
			if ($id = insert_transaction($transaction))
			{
				$transaction['id'] = $id;
				$transaction['letscode_to'] = $letscode_to;

				mail_mail_interlets_transaction($transaction);

				$app['eland.alert']->success('Interlets transactie opgeslagen (verwerking per mail).');
			}
			else
			{
				$app['eland.alert']->error('Gefaalde interlets transactie');
			}

			cancel();
		}
		else if ($group['apimethod'] != 'elassoap')
		{
			$app['eland.alert']->error('Interlets groep ' . $group['groupname'] . ' heeft geen geldige api methode.' . $contact_admin);

			cancel();
		}
		else if (!$group_domain)
		{
			$app['eland.alert']->error('Geen url voor interlets groep ' . $group['groupname'] . '. ' . $contact_admin);

			cancel();
		}
		else if (!(isset($schemas[$group_domain])))
		{
			// The interlets group uses eLAS or is on another server

			if (!$group['remoteapikey'])
			{
				$errors[] = 'Geen apikey voor deze interlets groep ingesteld.' . $contact_admin;
			}

			if (!$group['presharedkey'])
			{
				$errors[] = 'Geen preshared key voor deze interlets groep ingesteld.' . $contact_admin;
			}

			if (!$group['myremoteletscode'])
			{
				$errors[] = 'Geen remote letscode ingesteld voor deze interlets groep.' . $contact_admin;
			}

			$currencyratio = readconfigfromdb('currencyratio');

			if (!$currencyratio || !ctype_digit((string) $currencyratio) || $currencyratio < 1)
			{
				$errors[] = 'De currencyratio is niet correct ingesteld. ' . $contact_admin;
			}

			if (strlen($letscode_to))
			{
				$active_users = json_decode($app['redis']->get($group['url'] . '_typeahead_data'), true);

				$user_letscode_found = false;

				foreach ($active_users as $active_user)
				{
					if ($active_user['c'] == $letscode_to)
					{
						$real_name_to = $active_user['n'];
						$user_letscode_found = true;
						break;
					}
				}

				if ($user_letscode_found)
				{
					if(!$real_name_to)
					{
						$errors[] = 'Er werd geen naam gevonden voor de gebruiker van de interlets groep.';
					}
				}
				else
				{
					$errors[] = 'Er werd geen gebruiker gevonden met letscode ' . $letscode_to;
				}
			}

			if (count($errors))
			{
				$app['eland.alert']->error($errors);
				cancel();
			}

			$trans = $transaction;

			$trans['amount'] = $trans['amount'] / $currencyratio;
			$trans['amount'] = (float) $trans['amount'];
			$trans['amount'] = round($trans['amount'], 5);

			$trans['letscode_to'] = $letscode_to;

			$soapurl = ($group['elassoapurl']) ?: $group['url'] . '/soap';
			$soapurl .= '/wsdlelas.php?wsdl';

			$client = new nusoap_client($soapurl, true);

			$error = $client->getError();

			if ($error)
			{
				$app['eland.alert']->error('eLAS soap error: ' . $error . ' <br>' . $contact_admin);
				cancel();				
			}

			$result = $client->call('dopayment', [
				'apikey' 		=> $group['remoteapikey'],
				'from' 			=> $group['myremoteletscode'],
				'real_from' 	=> link_user($fromuser, false, false),
				'to' 			=> $letscode_to,
				'description' 	=> $trans['description'],
				'amount' 		=> $trans['amount'],
				'transid' 		=> $trans['transid'],
				'signature' 	=> sign_transaction($trans, trim($group['presharedkey'])),
			]);

			$error = $client->getError();

			if ($error)
			{
				$app['eland.alert']->error('eLAS soap error: ' . $error . ' <br>' . $contact_admin);
				cancel();
			}

			if ($result == 'OFFLINE')
			{
				$errors[] = 'De andere letsgroep is offline. Probeer het later opnieuw. ';
			}

			if ($result == 'FAILED')
			{
				$errors[] = 'De interlets transactie is gefaald.' . $contact_admin;
			}

			if ($result == 'SIGFAIL')
			{
				$errors[] = 'De signatuur van de interlets transactie is gefaald. ' . $contact_admin;
			}

			if ($result == 'DUPLICATE')
			{
				$errors[] = 'De transactie bestaat reeds in de andere letsgroep. ' . $contact_admin;
			}

			if ($result == 'NOUSER')
			{
				$errors[] = 'De gebruiker in de interletsgroep werd niet gevonden. ';
			}

			if ($result == 'APIKEYFAIL')
			{
				$errors[] = 'De apikey is niet correct. ' . $contact_admin;
			}

			if (!count($errors) && $result != 'SUCCESS')
			{
				$errors[] = 'De interlets transactie kon niet verwerkt worden. ' . $contact_admin;
			}
				
			if (count($errors))
			{
				$app['eland.alert']->error($errors);
				cancel();
			}

			$transaction['real_to'] = $letscode_to . ' ' . $real_name_to;

			$app['monolog']->debug('insert transation: --  ' . http_build_query($transaction) . ' --');

			$id = insert_transaction($transaction);

			if (!$id)
			{				
				$subject = 'Interlets FAILURE!';
				$text = 'WARNING: LOCAL COMMIT OF TRANSACTION ' . $transaction['transid'] . ' FAILED!!!  This means the transaction is not balanced now!';
				$text .= ' group:' . $group['groupname'];

				mail_q(['to' => 'admin', 'subject' => $subject, 'text' => $text]);

				$app['eland.alert']->error('De lokale commit van de interlets transactie is niet geslaagd. ' . $contact_admin);
				cancel();
			}

			$transaction['id'] = $id;

			mail_transaction($transaction);

			$app['eland.alert']->success('De interlets transactie werd verwerkt.');
			cancel();
		}
		else
		{
			// the interlets group is on the same server (eLAND)

			$remote_schema = $schemas[$group_domain];

			$to_remote_user = $app['db']->fetchAssoc('select *
				from ' . $remote_schema . '.users
				where letscode = ?', [$letscode_to]);

			if (!$to_remote_user)
			{
				$errors[] = 'De interlets gebruiker bestaat niet.';
			}

			if (!in_array($to_remote_user['status'], ['1', '2']))
			{
				$errors[] = 'De interlets gebruiker is niet actief.';
			}

			$remote_group = $app['db']->fetchAssoc('select *
				from ' . $remote_schema . '.letsgroups
				where url = ?', [$app['eland.base_url']]);

			if (!$remote_group)
			{
				$errors[] = 'De remote interlets groep heeft deze letsgroep ('. readconfigfromdb('systemname') . ') niet geconfigureerd.';
			}

			if (!$remote_group['localletscode'])
			{
				$errors[] = 'Er is geen interlets account gedefiniëerd in de remote interlets groep.';
			}

			$remote_interlets_account = $app['db']->fetchAssoc('select *
				from ' . $remote_schema . '.users
				where letscode = ?', [$remote_group['localletscode']]);

			if (!$remote_interlets_account)
			{
				$errors[] = 'Er is geen interlets account in de remote interlets group.';
			}

			if ($remote_interlets_account['accountrole'] != 'interlets')
			{
				$errors[] = 'Het interlets account in de remote interlets groep heeft geen juiste rol. Deze moet van het type interlets zijn.';
			}

			if (!in_array($remote_interlets_account['status'], [1, 2, 7]))
			{
				$errors[] = 'Het interlets account in de remote interlets groep heeft geen juiste status. Deze moet van het type extern, actief of uitstapper zijn.';
			}

			$remote_currency = readconfigfromdb('currency', $remote_schema);
			$remote_currencyratio = readconfigfromdb('currencyratio', $remote_schema);
			$remote_balance_eq = readconfigfromdb('balance_equilibrium', $remote_schema);
			$currencyratio = readconfigfromdb('currencyratio');

			if (!$currencyratio || !ctype_digit((string) $currencyratio) || $currencyratio < 1)
			{
				$errors[] = 'De currencyratio is niet correct ingesteld. ' . $contact_admin;
			}

			if (!$remote_currencyratio ||
				!ctype_digit((string) $remote_currencyratio)
				|| $remote_currencyratio < 1)
			{
				$errors[] = 'De currencyratio van de andere groep is niet correct ingesteld. ' . $contact_admin;
			}

			$remote_amount = round(($transaction['amount'] * $remote_currencyratio) / $currencyratio);

			if ($remote_amount < 1)
			{
				$errors[] = 'Het bedrag is te klein want het kan niet uitgedrukt worden in de gebruikte munt van de interletsgroep.';
			} 

			if(($remote_interlets_account['saldo'] - $remote_amount) < $remote_interlets_account['minlimit'])
			{
				$errors[] = 'De interlets account van de remote interlets groep heeft onvoldoende saldo beschikbaar.';
			}

			if(($to_remote_user['saldo'] + $remote_amount) > $to_remote_user['maxlimit'])
			{
				$errors[] = 'De interlets gebruiker heeft zijn maximum limiet bereikt.';
			}

			if (($remote_interlets_account['status'] == 2) && (($remote_interlets_account['saldo'] - $remote_amount) < $remote_balance_eq))
			{
				$errors[] = 'Het remote interlets account heeft de status uitstapper en kan geen ' . $remote_amount . ' ' . $remote_currency . ' uitgeven (' . $amount . ' ' . readconfigfromdb('currency') . ').';
			}

			if (($to_remote_user['status'] == 2) && (($to_remote_user['saldo'] + $remote_amount) > $remote_balance_eq))
			{
				$errors[] = 'De remote bestemmeling is uitstapper en kan geen ' . $remote_amount . ' ' . $remote_currency . ' ontvangen (' . $amount . ' ' . readconfigfromdb('currency') . ').';
			}

			if (count($errors))
			{
				$app['eland.alert']->error($errors);
				cancel();
			}

			//
			$transaction['creator'] = ($s_master) ? 0 : $s_id;
			$transaction['cdate'] = gmdate('Y-m-d H:i:s');
			$transaction['real_to'] = $to_remote_user['letscode'] . ' ' . $to_remote_user['name'];

			$app['db']->beginTransaction();

			try
			{
				$app['db']->insert('transactions', $transaction);
				$id = $app['db']->lastInsertId('transactions_id_seq');
				$app['db']->executeUpdate('update users
					set saldo = saldo + ? where id = ?',
					[$transaction['amount'], $transaction['id_to']]);
				$app['db']->executeUpdate('update users
					set saldo = saldo - ? where id = ?',
					[$transaction['amount'], $transaction['id_from']]);

				$trans_org = $transaction;
				$trans_org['id'] = $id;

				$transaction['creator'] = 0;
				$transaction['amount'] = $remote_amount;
				$transaction['id_from'] = $remote_interlets_account['id'];
				$transaction['id_to'] = $to_remote_user['id'];
				$transaction['real_from'] = link_user($fromuser['id'], false, false);
				unset($transaction['real_to']);

				$app['db']->insert($remote_schema . '.transactions', $transaction);
				$id = $app['db']->lastInsertId($remote_schema . '.transactions_id_seq');
				$app['db']->executeUpdate('update ' . $remote_schema . '.users
					set saldo = saldo + ? where id = ?',
					[$remote_amount, $transaction['id_to']]);
				$app['db']->executeUpdate('update ' . $remote_schema . '.users
					set saldo = saldo - ? where id = ?',
					[$transaction['amount'], $transaction['id_from']]);
				$transaction['id'] = $id;

				$app['db']->commit();

			}
			catch(Exception $e)
			{
				$app['db']->rollback();
				$app['eland.alert']->error('Transactie niet gelukt.');
				throw $e;
				exit;
			}

			readuser($fromuser['id'], true);
			readuser($touser['id'], true);

			readuser($remote_interlets_account['id'], true, $remote_schema);
			readuser($to_remote_user['id'], true, $remote_schema);

			mail_transaction($trans_org);
			mail_transaction($transaction, $remote_schema);

			$app['monolog']->info('direct interlets transaction ' . $transaction['transid'] . ' amount: ' .
				$amount . ' from user: ' .  link_user($fromuser['id'], false, false) .
				' to user: ' . link_user($touser['id'], false, false));

			$app['monolog']->info('direct interlets transaction (receiving) ' . $transaction['transid'] .
				' amount: ' . $remote_amount . ' from user: ' . $remote_interlets_account['letscode'] . ' ' .
				$remote_interlets_account['name'] . ' to user: ' . $to_remote_user['letscode'] . ' ' .
				$to_remote_user['name'], ['schema' => $remote_schema]);

			autominlimit_queue($transaction['id_from'], $transaction['id_to'], $remote_amount, $remote_schema);

			$app['eland.alert']->success('Interlets transactie uitgevoerd.');
			cancel();
		}

		$transaction['letscode_to'] = $_POST['letscode_to'];
		$transaction['letscode_from'] = ($s_admin || $s_master) ? $_POST['letscode_from'] : link_user($s_id, false, false);
	}
	else
	{
		//GET form

		$transid = generate_transid();

		$app['redis']->set($redis_transid_key, $transid);
		$app['redis']->expire($redis_transid_key, 3600);

		$transaction = [
			'date'			=> gmdate('Y-m-d H:i:s'),
			'letscode_from'	=> ($s_master) ? '' : link_user($s_id, false, false),
			'letscode_to'	=> '',
			'amount'		=> '',
			'description'	=> '',
			'transid'		=> $transid,
		];

		$group_id = 'self';
		$to_schema_table = '';

		if ($tus)
		{
			if (isset($hosts[$tus]))
			{
				$host_from_tus = $hosts[$tus];

				$group_id = $app['db']->fetchColumn('select id
					from letsgroups
					where url = ?', [$app['eland.protocol'] . $host_from_tus]);
				$to_schema_table = $tus . '.';
			}
		}

		if ($mid && !($tus xor $host_from_tus))
		{
			$row = $app['db']->fetchAssoc('SELECT
					m.content, m.amount, m.id_user, u.letscode, u.name, u.status
				from ' . $to_schema_table . 'messages m,
					'. $to_schema_table . 'users u
				where u.id = m.id_user
					and m.id = ?', [$mid]);

			if (($s_admin && !$tus) || $row['status'] == 1 || $row['status'] == 2)
			{
				$transaction['letscode_to'] = $row['letscode'] . ' ' . $row['name'];
				$transaction['description'] =  substr('#m.' . $to_schema_table . $mid . ' ' . $row['content'], 0, 60);
				$amount = $row['amount'];
				if ($tus)
				{
					$amount = round((readconfigfromdb('currencyratio') * $amount) / readconfigfromdb('currencyratio', $tus));
				}
				$transaction['amount'] = $amount;
				$tuid = $row['tuid'];
			}
		}
		else if ($tuid)
		{
			$row = readuser($tuid, false, ((isset($host_from_tus)) ? $tus : false));

			if (($s_admin && !$tus) || $row['status'] == 1 || $row['status'] == 2)
			{
				$transaction['letscode_to'] = $row['letscode'] . ' ' . $row['name'];
			}
		}

		if ($fuid && $s_admin && ($fuid != $tuid))
		{
			$row = readuser($fuid);
			$transaction['letscode_from'] = $row['letscode'] . ' ' . $row['name'];
		}

		if ($tuid == $s_id && !$fuid && $tus != $schema)
		{
			$transaction['letscode_from'] = '';
		}
	}

	$app['eland.assets']->add(['typeahead', 'typeahead.js']);

	$balance = $session_user['saldo'];

	$groups = $app['db']->fetchAll('SELECT id, groupname, url FROM letsgroups where apimethod <> \'internal\'');

	$groups = array_merge([[
		'groupname' => readconfigfromdb('systemname'),
		'id'		=> 'self',
	]], $groups);

	$top_buttons .= aphp('transactions', [], 'Lijst', 'btn btn-default', 'Transactielijst', 'exchange', true);

	if (!$s_master)
	{
		$top_buttons .= aphp('transactions', ['uid' => $s_id], 'Mijn transacties', 'btn btn-default', 'Mijn transacties', 'user', true);
	}

	$h1 = 'Nieuwe transactie';
	$fa = 'exchange';

	include __DIR__ . '/includes/inc_header.php';

	$minlimit = $session_user['minlimit'];

	if (!$s_master)
	{
		echo '<div>';
		echo '<p><strong>' . link_user($session_user) . ' huidige ' . readconfigfromdb('currency') . ' stand: ';
		echo '<span class="label label-info">' . $balance . '</span></strong> ';
		echo '<strong>Minimum limiet: <span class="label label-danger">' . $minlimit . '</span></strong></p>';
		echo '</div>';
	}

	echo '<div class="panel panel-info">';
	echo '<div class="panel-heading">';

	echo '<form  method="post" class="form-horizontal" autocomplete="off">';

	echo ($s_admin) ? '' : '<div style="display:none;">';

	echo '<div class="form-group"';
	echo ($s_admin) ? '' : ' disabled="disabled" ';
	echo '>';
	echo '<label for="letscode_from" class="col-sm-2 control-label">';
	echo '<span class="label label-info">Admin</span> ';
	echo 'Van letscode</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="letscode_from" name="letscode_from" ';
	echo 'data-typeahead-source="group_self" ';
	echo 'value="' . $transaction['letscode_from'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo ($s_admin) ? '' : '</div>';

	echo '<div class="form-group">';
	echo '<label for="group_id" class="col-sm-2 control-label">Aan letsgroep</label>';
	echo '<div class="col-sm-10">';
	echo '<select type="text" class="form-control" id="group_id" name="group_id">';

	foreach ($groups as $l)
	{
		echo '<option value="' . $l['id'] . '" ';

		if ($l['id'] == 'self')
		{
			echo 'id="group_self" ';

			if ($s_admin)
			{
				$typeahead = ['users_active', 'users_inactive', 'users_ip', 'users_im'];
			}
			else
			{
				$typeahead = 'users_active';
			}

			$typeahead = $app['eland.typeahead']->get($typeahead);
		}
		else
		{
			$typeahead = $app['eland.typeahead']->get('users_active', $l['url'], $l['id']);
		}

		echo 'data-typeahead="' . $typeahead . '"';
		echo ($l['id'] == $group_id) ? ' selected="selected" ' : '';
		echo '>' . htmlspecialchars($l['groupname'], ENT_QUOTES) . '</option>';
	}

	echo '</select>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="letscode_to" class="col-sm-2 control-label">Aan letscode</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="letscode_to" name="letscode_to" ';
	echo 'data-typeahead-source="group_id" ';
	echo 'value="' . $transaction['letscode_to'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="amount" class="col-sm-2 control-label">Aantal ' . readconfigfromdb('currency') . '</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="number" class="form-control" id="amount" name="amount" ';
	echo 'value="' . $transaction['amount'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="description" class="col-sm-2 control-label">Omschrijving</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="description" name="description" ';
	echo 'value="' . $transaction['description'] . '" required maxlength="60">';
	echo '</div>';
	echo '</div>';

	echo aphp('transactions', [], 'Annuleren', 'btn btn-default') . '&nbsp;';
	echo '<input type="submit" name="zend" value="Overschrijven" class="btn btn-success">';
	$app['eland.form_token']->generate();
	echo '<input type="hidden" name="transid" value="' . $transaction['transid'] . '">';

	echo '</form>';
	echo '</div>';
	echo '</div>';

	echo '<ul><small><i>';

	echo '<li>Tip: Het veld Aan LETSCode geeft autosuggesties door naam of letscode in te typen. ';
	echo 'Kies eerst de juiste letsgroep om de juiste suggesties te krijgen.</li>';

	echo '<li>';
	echo readconfigfromdb('currencyratio');
	echo ' ' . readconfigfromdb('currency') . ' staat gelijk aan 1 LETS-uur.</li>';

	echo '</i></small></ul>';

	include __DIR__ . '/includes/inc_footer.php';
	exit;
}

/*
 * interlets accounts schemas needed for interlinking users.
 */

$interlets_accounts_schemas = $app['eland.interlets_groups']->get_eland_accounts_schemas($schema);

$s_inter_schema_check = array_merge($eland_interlets_groups, [$s_schema => true]);

/**
 * show a transaction
 */

if ($id)
{
	$transaction = $app['db']->fetchAssoc('select t.*
		from transactions t
		where t.id = ?', [$id]);

	$inter_schema = false;

	if (isset($interlets_accounts_schemas[$transaction['id_from']]))
	{
		$inter_schema = $interlets_accounts_schemas[$transaction['id_from']];
	}
	else if (isset($interlets_accounts_schemas[$transaction['id_to']]))
	{
		$inter_schema = $interlets_accounts_schemas[$transaction['id_to']];
	}

	if ($inter_schema)
	{
		$inter_transaction = $app['db']->fetchAssoc('select t.*
			from ' . $inter_schema . '.transactions t
			where t.transid = ?', [$transaction['transid']]);
	}
	else
	{
		$inter_transaction = false;
	}

	$next = $app['db']->fetchColumn('select id
		from transactions
		where id > ?
		order by id asc
		limit 1', [$id]);

	$prev = $app['db']->fetchColumn('select id
		from transactions
{'fraction_non_alphanumeric': 0.20605699533313473, 'fraction_numerical': 0.0024227981332538974, 'mean_word_length': 3.8419230769230768, 'pattern_counts': {'":': 0, '<': 171, '<?xml version=': 0, '>': 327, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4777077', 'n_tokens_mistral': 20842, 'n_tokens_neox': 18090, 'n_words': 3600}