<?php

// always come first!
session_start();

include_once(dirname(__FILE__) . '/Config/qidportal.cfg.php');
include_once(dirname(__FILE__) . '/UbiLib/dbfuncs.' . UC_LIB_DBAPI . '.php');
include_once(dirname(__FILE__) . '/UbiLib/funcs_email.php');
include_once(dirname(__FILE__) . '/UbiLib/funcs_varia.php');
include_once(dirname(__FILE__) . '/UbiLib/funcs_strings.php');
include_once(dirname(__FILE__) . '/UbiLib/uc_vies.php');
include_once(dirname(__FILE__) . '/UbiLib/commons_auth.php');
include_once(dirname(__FILE__) . '/Lib/funcs_data_enterprise.php');
include_once(dirname(__FILE__) . '/Lib/funcs_data_log.php');
include_once(dirname(__FILE__) . '/Lib/funcs_data_preset.php');
include_once(dirname(__FILE__) . '/Lib/funcs_qid_specs.php');
include_once(dirname(__FILE__) . '/UbiLib/countries-data.utf8.php');
include_once(dirname(__FILE__) . '/UbiLib/funcs_countries.php');
include_once(dirname(__FILE__) . '/Styles/corporate_styles_stuff.php');
include_once(dirname(__FILE__) . '/Lib/uc_corporate_htm_parts.php');
include_once(dirname(__FILE__) . '/Lib/funcs_forms.php');

if (isset($_SESSION) && isset($_SESSION['username']) && ($_SESSION['username'] != ''))
	{ $logged_in = true; }
else
	{ $logged_in = false; }

if (!isset($_REQUEST['oper'])) { $oper = 'noop'; }
else { $oper = $_REQUEST['oper']; }

if ($oper == 'logout')
{
	// actually, I don't need to destroy the session, just to drop all its vars
	$skeys = array_keys($_SESSION);
	foreach($skeys as $ckey) unset($_SESSION[$ckey]); // that includes key 'username'
	$logged_in = false;
}

// array to deal with form variables, fields:
//                 name (0), DB var (1), is required and cannot be empty (2), allowed characters (3), max length (4),
//                 variable descritption (5), default (or current, if the code wants to change it) content (6)
// the key and the form var name MUST BE THE SAME, redundancy here is for practical purposes

$regvara = array
(
	// 2015.01.13: FCL says that EDESC is not asked for nor recorded
	// 'ent_edesc'           => array('ent_edesc', 'edesc',                 false, 'ascii-no-quotes', 40, 'EDESC',             ''),
	// not for the moment
	// 'ent_address_site'    => array('ent_address_site',    'address_site',    false, 'ascii-no-quotes', 40, 'address (site)',    ''),
	// 'ent_city_site'       => array('ent_city_site',       'city_site'   ,    false, 'ascii-no-quotes', 40, 'city (site)',       ''),

	'ent_name'            => array('ent_name',            'company_name',    true,  'any',             40, 'Company name',      ''),
	'ent_fiscal_code'     => array('ent_fiscal_code',     'fiscal_code',     true,  'ascii-no-quotes', 40, 'VAT number',        ''),
	'ent_address_billing' => array('ent_address_billing', 'address_billing', true,  'any',             40, 'Address (billing)', ''),
	'ent_zip_billing'     => array('ent_zip_billing',     'zip_billing',     true,  'ascii-no-quotes', 16, 'Post code / ZIP (billing)', ''),
	'ent_city_billing'    => array('ent_city_billing',    'city_billing'   , true,  'any',             40, 'City (billing)',    ''),
	'ent_state'           => array('ent_state',           'state',           false, 'alpha-and-space', 40, 'State',             ''),
	'ent_country'         => array('ent_country',         'country',         true,  'alpha-and-space', 2,  'Country',           ''),
	'ent_referee_name'    => array('ent_referee_name',    'referee_name',    true,  'ascii',           40, 'Referee name',      ''),
	'ent_referee_surname' => array('ent_referee_surname', 'referee_surname', true,  'ascii',           40, 'Referee surname',   ''),
	'ent_email'           => array('ent_email',           'email_main',      true,  'email',           40, 'e-mail',             ''),
	'ent_email_check'     => array('ent_email_check',     false,             true,  'email',           40, 'e-mail (check)',     ''),
	'ent_phone_leased'    => array('ent_phone_leased',    'phone_leased',    false, 'digit-and-space', 20, 'Phone (leased)',    ''),
	'ent_phone_mobile'    => array('ent_phone_mobile',    'phone_mobile',    false, 'digit-and-space', 20, 'Phone (mobile)',    '')
);

// since 2015.01.21, I am doing this the smart way and rely on the global settings
// ...so the fields in the regvara array are changed according to what is in array qidportal_tbl_enterprise_flda
$kregvara = array_keys($regvara);
foreach($kregvara as $ckk)
{
	$dbcol = $regvara[$ckk][1];
	if (is_string($dbcol)) // otherwise it maust be false, meaning that there is no correspondence with a table column
	{
		// print_r($qidportal_tbl_enterprise_flda[$dbcol]);
		// can it be null -> not(cannot be empty)
		$regvara[$ckk][2] = !($qidportal_tbl_enterprise_flda[$dbcol][0]);
		// format
		$regvara[$ckk][3] = $qidportal_tbl_enterprise_flda[$dbcol][1];
		// max lenght
		$regvara[$ckk][4] = $qidportal_tbl_enterprise_flda[$dbcol][2];
	}
}


echo '<!DOCTYPE html>
<html lang="en">
';

// produce standard HTML head tag and content

uc_qidportal_corporate_htm_head('Q-ID : Corporate : Registration', '');

echo '
<body class="corp_reg_body">
	<div id="divMain" class="nxd_divmain">
';
qidportal_show_main_menu(!$logged_in);

// display the menu and the central box for the workarea

uc_qidportal_corporate_central_box_open($logged_in, ($logged_in ? $_SESSION['username'] : false),
	'corporate_registration.php', 'Registration form');

if ($logged_in)
{

	echo '
		<br /><br /><br /><font class="problem">ERROR: you are logged in, consequently, you have already registered!</font><br /><br />
	';

	// horizontal menu, no more: echo uc_qidportal_corporate_inops_menu() . "<br />\n";
}
else
{
	switch($oper)
	{

		// the user has filled the form with the basic company data,
		// record the data for the registrant (enteprise / company), send e-mail with link for confirmation

		case 'register_enterprise':

			openlog('reg-enterprise', QID_PORTAL_SYSLOG_OPTION, QID_PORTAL_SYSLOG_FACILITY);

			$errmsga = array(); // if not empty, an error has occurred
			$prevent_redisplay = false; // set this to true if the operation failed but I do not want to redisplay the form

			$all_filled = true; // this is to track that all required fields have been filled and to display the error message just once

			foreach($regvara as $vvk => $vva)
			{
				$vname = $vva[0]; // must be the same: $vvk;
				$dbcol = $vva[1]; // may be false
				$maxlen = $vva[4];
				$isrequired = $vva[2];
				$vdescr = $vva[5];
				$vformat = $vva[3];

				if ($dbglvl > 20) syslog(LOG_NOTICE, "DEBUG: checking form var '$vname' ($vdescr), maxlen $maxlen, format $vformat");

				// check that all required vars are filled in the form
				if (!isset($_REQUEST[$vname]) || ($_REQUEST[$vname] == ''))
				{
					// do I want the global variable??? I think it is a very bad idea, may mix with other vars... $$vname = ...
					$vcontent = '';

					if ($isrequired) // if it is required
					{
						if ($dbglvl > 10) syslog(LOG_NOTICE, "ERROR: required var '$vname' not passed or empty");
						if ($all_filled)
						{
							// I do not want to repeat this error message
							$errmsga[] = 'please enter all fields marked with (*)';
							$all_filled = false;
						}
					}
				}
				else
				{
					// do I want the global variable??? I think it is a very bad idea, may mix with other vars... $$vname = ...
					$vcontent = trim($_REQUEST[$vname]); // global variable as the form-passed value
				}

				// now check that it is well-formed (the new way... the old way to do this is in code before 2015.01.20)

				// in such case, optimize + skip errors that uc_format_string would return for empty strings:
				if (!$isrequired && ($vcontent == ''))
				{
					$regvara[$vvk][6] = '';
				}
				else
				{
					$polisheda = uc_string_polish($vcontent, $vformat, array(), '');
					if ($polisheda['err'] != 0)
					{
						syslog(LOG_NOTICE, 'ERROR: form var for ' . $vname . ', error is ' . $polisheda['errmsg']);
						$regvara[$vvk][6] = $vcontent;
						$errmsga[] = ('bad characters in field "' . $vdescr . '", please edit it');
					}
					else
					{
						$regvara[$vvk][6] = $polisheda['newstr'];
						if ($polisheda['changed'])
							{ $errmsga[] = ('field "' . $vdescr . '" modified to make it acceptable, please review the changes'); }
					}
					unset($polisheda);
				}

				// check the length

				if (strlen($regvara[$vvk][6]) > $maxlen)
				{
					$regvara[$vvk][6] = substr($regvara[$vvk][6], 0, $maxlen);
					$errmsga[] = ('value for "' . $vdescr. '" was too long, please review the shorter version');
				}
			}

			// check that the country is in my array -otherwise someone messed with the variables(?!)
			if (($regvara['ent_country'][6] !== false) && ($regvara['ent_country'][6] != '') &&
					!in_array($regvara['ent_country'][6], array_keys($uc_world_countries_a)))
			{
				$regvara['ent_country'][6] = ''; // also reset it
				$errmsga[] = ('value for COUNTRY is not allowed(?!)');
			}

			// check that the two email values are the same
			if ($regvara['ent_email'][6] != $regvara['ent_email_check'][6])
				{ $errmsga[] = 'mail addresses are not the same'; }

			syslog(LOG_NOTICE, 'DEBUG: passed form var check phase, error messages count: ' . count($errmsga));

			// create the random code to perform the activation of the account, which is just "new" when created
			// ...it also allows to download the SW
			if (count($errmsga) == 0)
			{
				// I want to include the current date; that will tell me if it is too late to use the code
				// IT *MUST* CONTAIN "-confreg-" or it will be rejected
				$confirmation_code = date('ymd') . '-confreg-' .
					rand(1111,9999) . '-' . rand(1111,9999) . '-' . rand(1111,9999) . '-' . rand(1111,9999) . '-' . rand(1111,9999);
			}

			if (count($errmsga) == 0)
			{
				$dbc = uc_qidportal_dbconn();
				if ($dbc === false)
				{
					$errmsga[] = '(INTERNAL!) cannot access DB';
				}
			}

			// generate EID, that must be (almost) alphanumeric, for convenience and so that I can use it for login

			if (count($errmsga) == 0)
			{
				$preset_eid = uc_qidportal_presetdata_company2eid($dbc, $regvara['ent_name'][6]);

				if ($preset_eid !== false) // the EID is pre-determined, use it
				{
					$eid = $preset_eid;
					syslog(LOG_NOTICE, 'INFO: *PRESET* EID (to be checked vs DB) found for this company: ' . $eid);
				}
				else
				{
					$eid = uc_qidspecs_name2eid($regvara['ent_name'][6], 0);
					// if the EID is among the preset ones, I cannot use it. Veeery unlikely, yet I paranoically want to check
					if (uc_qidportal_presetdata_eidexists($dbc, $eid))
					{
						syslog(LOG_NOTICE, 'WARNING: 1st candidate EID is reserved (preset), cannot use it: ' . $eid);
					}
					else
					{
						syslog(LOG_NOTICE, 'INFO: 1st candidate EID (to be checked vs DB): ' . $eid);
					}
				}

				// if EID exists, change it until there is no equal

				if (uc_qidportal_enterprisedata_exists($dbc, $eid))
				{
					syslog(LOG_NOTICE, 'WARNING: EID ' . $eid . ' already in use, entering loop to find a good one');

					$eid = false;

					for ($idx = 1; $idx < 12; $idx++)
					{
						$eid = uc_qidspecs_name2eid($regvara['ent_name'][6], $idx);

						if (uc_qidportal_presetdata_eidexists($dbc, $eid))
						{
							syslog(LOG_NOTICE, 'WARNING: skipping reserved (preset) candidate EID #' . ($idx + 1) . ' "' . $eid . '"');
							continue;
						}

						if (uc_qidportal_enterprisedata_status($dbc, $eid) === false)
						{
							syslog(LOG_NOTICE, 'INFO: EID ' . $eid . ' is OK. I pick it');
							break;
						}
						else
						{
							$eid = false;
						}
					}
				}

				if ($eid === false) // For sure, it is not user's fault if I am here, it's the code that sucks
				{
					uc_qidportal_log(true, $dbc, false, false, 'enterprise', 'N.A.', 'critical',
						'cannot gen EID for ' . $regvara['ent_name'][6], 'corporate_registration', false, false);
					$errmsga[] = 'cannot generate a valid EID for your name. Please, try a different company name';
				}
			}

			if (count($errmsga) == 0)
			{
				// must not exist in DB: company name, e-mail address

				$dataa = uc_qidportal_enterprisedata_getbyfield($dbc, 'company_name', $regvara['ent_name'][6]);
				if (is_array($dataa) && (count($dataa) != 0))
				{
					$errmsga[] = ($regvara['ent_name'][5] . ': ' . $regvara['ent_name'][6] .
						' already recorded. Are you sure that your company does not possess an account?');
				}
				unset($dataa);

				/*
				$dataa = uc_qidportal_enterprisedata_getbyfield($dbc, 'edesc', $regvara['ent_edesc'][6]);
				if (is_array($dataa) && (count($dataa) != 0))
				{
					$errmsga[] = ($regvara['ent_edesc'][5] . ': ' . $regvara['ent_edesc'][6] .
						' already recorded. Are you sure that your company does not possess an account?');
				}
				unset($dataa);
				*/

				$dataa = uc_qidportal_enterprisedata_getbyfield($dbc, 'email_main', $regvara['ent_email'][6]);
				if (is_array($dataa) && (count($dataa) != 0))
				{
					$errmsga[] = ($regvara['ent_email'][5] . ': ' . $regvara['ent_email'][6] .
						' already recorded. Are you sure that your company does not possess an account?');
				}
				unset($dataa);
			}

			if (count($errmsga) == 0) // now generate login and password
			{
				$login = $eid;
				$pwd = $eid . rand(1111111, 9999999);

				// syslog(LOG_NOTICE, "DEBUG: ***REMOVE*** $login / $pwd");
			}


			// if the customer is in the EC, it is a good idea to perform a VIES check of
			// the VAT number. The outcome is not really important because most people
			// do not record the VAT number on the VIES system and the SOAP service is not
			// very realiable (sometimes it is "BUSY")

			$vies_check_vv = 'x'; // by default, not performed
			if
			(
				($regvara['ent_country'][6] !== false) && ($regvara['ent_country'][6] != '') &&
				($regvara['ent_fiscal_code'][6] !== false) && ($regvara['ent_fiscal_code'][6] != '') &&
				in_array($regvara['ent_country'][6], array_keys($uc_ec_countries))
			)
			{
				$viesrva = uc_vies_check_vatNumber($regvara['ent_country'][6], $regvara['ent_fiscal_code'][6], 3);
				// DEBUG: print_r($viesrva);
				if ($viesrva['err'] == 0)
				{
					$vies_check_vv = 'y'; // the DB value is 'y' to say OK. It is an ENUM field
					syslog(LOG_NOTICE, 'INFO: VIES check OK for VAT number: ' .
							$regvara['ent_fiscal_code'][6] . ' from country ' . $regvara['ent_country'][6] .
							', company registered as ' . $viesrva['name']);
				}
				else
				{
					$vies_check_vv = 'n'; // the DB value is 'n' to say that the VIES check failed. It is an ENUM field
					syslog(LOG_NOTICE, 'INFO: VIES check FAILED for VAT number: ' .
							$regvara['ent_fiscal_code'][6] . ' from country ' . $regvara['ent_country'][6]);
				}
				unset($viesrva);
			}
			else
			{
				syslog(LOG_NOTICE, 'DEBUG: skipping VIES check for country ' . $regvara['ent_country'][6]);
			}


			if (count($errmsga) == 0)
			{
				// echo 'SORRY!!! TO BE IMPLEMENTED yet!!!';
				syslog(LOG_NOTICE, 'INFO: going to record enterprise, EID: ' . $eid . ', name: ' . $regvara['ent_name'][6]);

				if (!function_exists('uc_qidportal_enterprisedata_add'))
					{ $errmsga[] = 'INTERNAL!!! Required func not defined'; }
				else
				{
					// actually record the data

					$sqlrva = uc_qidportal_enterprisedata_add
					(
						11, $dbc,
						$eid, $regvara['ent_name'][6], false, $regvara['ent_fiscal_code'][6],
						$regvara['ent_address_billing'][6], $regvara['ent_zip_billing'][6], $regvara['ent_city_billing'][6],
						$regvara['ent_state'][6], $regvara['ent_country'][6],
						'new', $regvara['ent_email'][6], false,
						$regvara['ent_phone_leased'][6], $regvara['ent_phone_mobile'][6], false,
						false, $regvara['ent_referee_name'][6], $regvara['ent_referee_surname'][6],
						false, false, false,
						'a', 'n',
						$login, uc_qid_pass2dbv($pwd),
						$confirmation_code, $vies_check_vv
					);

					if ($sqlrva['err'] != 0)
					{
						syslog(LOG_NOTICE, 'ERROR: in _add, err / errmsg / sqlmsg (if any): ' .
											$sqlrva['err'] . ' / ' . $sqlrva['errmsg'] . ' / ' . $sqlrva['sqlmsg']);
						$errmsga[] = ('error in DB recording (' . $sqlrva['errmsg'] . '), please contact support!');
						// print_r($sqlrva);
					}
					else
					{
						// I do not want to re-display the form if the registration is OK but the mail could not be sent
						$prevent_redisplay = true;
					}
				}
			}

			if (count($errmsga) == 0)
			{
				uc_qidportal_log(true, $dbc, false, false, 'enterprise', $login, 'info', 'user registered, sending mail',
					'corporate_registration', false, 'mail to be sent => password not set yet, registration to be completed');

				// 'https://www.q-id.org/corporate_registration.php?oper=confirm_reg&user=' . $login . '&code=' . $confirmation_code
				// $confirmation_link = 'https://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] .
				//		'/qidportal/CORP/corporate_registration.php?oper=confirm_reg&user=' . $login . '&code=' . $confirmation_code;
				// as for dev machines, just provide a minimal effort...
				$thehn = php_uname('n');
				switch($thehn)
				{
					case 'Juppiter.gt50.org': // 42.30 dev, external IP
						$confirmation_link = 'https://188.10.35.216:44300/qidportal/CORP/corporate_registration.php';
						break;
					case 'Centauri': // suppose I am testing locally
						$confirmation_link = 'https://127.0.0.1/qidportal/CORP/corporate_registration.php';
						break;
					default: // by default, it is the production site
						$confirmation_link = 'http://www.q-id.net/CORP/corporate_registration.php';
				}
				$confirmation_link .= ('?oper=confirm_reg&user=' . $login . '&code=' . $confirmation_code);

				syslog(LOG_NOTICE, 'DEBUG: confirmation link is ' . $confirmation_link);

				$mail_body = array
				(
					'',
					'Congratulations!',
					'',
					// 'You are now now registered at the QID portal, this is your account data:',
					// 'user = ' . $login,
					// 'password = ' . $pwd,
					'You are now now registered at the QID portal, your user name is: ' . $login,
					'',
					'to confirm your registration, please click on the following link: ',
					$confirmation_link,
					'',
					'Thanks - the QID team'
				);

				syslog(LOG_NOTICE, 'INFO: account recorded, sending mail to ' .
										$regvara['ent_email'][6] . ', subject: QID portal registration');
				$mailrv = uc_send_simple_mail_sk(QID_PORTAL_MXRELAY_HOST, QID_PORTAL_MX_FROM, $regvara['ent_email'][6],
					'QID portal registration', $mail_body);
				if ($mailrv != '0|OK')
				{
					uc_qidportal_log(true, $dbc, false, $confirmation_code, 'enterprise', $login, 'error',
						'could not send mail for confirmation with code ' . $confirmation_code, $_SERVER['PHP_SELF'], false, false);
					$errmsga[] = ('error in mail delivery (' . $mailrv . '), please contact support!');
					// do I want this one???
					$errmsga[] =
					(
						'PLEASE, follow the link to complete the registration, but check your e-mail address ASAP: ' .
						'<a href="' . $confirmation_link . '">click here</a>'
					);
					$prevent_redisplay = true;
				}
				/*
				syslog(LOG_NOTICE, 'INFO: account recorded, sending mail with alternate method, subject: QID portal registration - bis');
				uc_send_simple_mail_std(QID_PORTAL_MXRELAY_HOST, QID_PORTAL_MX_FROM,
							$regvara['ent_email'][6], 'QID portal registration - bis',
					'you are now registered at tha QID portal. User = ' . $login . ' password = ' . $pwd);
				*/
			}

			if (count($errmsga) > 0)
			{
				syslog(LOG_NOTICE, 'ERROR: could not record enterprise (' . $regvara['ent_name'][6] . '), there are ' .
					count($errmsga) . ' error messages');

				// background-color:#bbbbee;
				echo '<div class="errbox">ERRORS!!!<br /><ul>' . "\n";
				foreach($errmsga as $cemsg)
				{
					echo '<li>' . $cemsg . "</li>\n";
					syslog(LOG_NOTICE, 'DEBUG: displaying error message ' . $cemsg);
				} // <br />
				if ($vies_check_vv == 'n')
				{
					echo '<li>(just a warning) cannot find your VAT number in the VIES database</li>' . "\n";
				}
				echo '</ul></div>' . "\n\n";
			}
			else
			{
				if ($vies_check_vv == 'n')
				{
					echo '<br /><font class="warning">WARNING: I cannot find your VAT number in the VIES database. This 
						is not a problem, but maybe you want to check about it</font><br />';
				}

				echo '<br /><br /><strong>OK, you have been recorded. To complete the registration, please
					follow the instructions sent via e-mail</strong><br /><br />';
			}

			syslog(LOG_NOTICE, '--- END OF ' . $oper . ' -------------------------------------------------------');

			if (isset($dbc) && ($dbc !== false))
			{
				uc_qidportal_dbclose($dbc);
			}

			if ((count($errmsga) > 0) && !$prevent_redisplay)
				{ uc_qidportal_form_entreg($regvara); }
			closelog();

			break;



		// (confirm_reg) the user clicked on the link (received via e-mail) to confirm the registration. Proceed accordingly
		// (finish_reg) the user has also filled the form to confirm the registration. The account can be activated

		case 'confirm_reg':
		case 'finish_reg':

			$errlev = 0;
			openlog('confirm-reg-enterprise', QID_PORTAL_SYSLOG_OPTION, QID_PORTAL_SYSLOG_FACILITY);

			if (!isset($_REQUEST['user']) || !isset($_REQUEST['code']))
			{
				$errlev++;
				echo '<br /><font class="problem">ERROR: link for confirmation is bad or incomplete. 
							Please check it.</font><br /><br />';
				syslog(LOG_NOTICE, 'ERROR: page called with missing or bad parameters');
			}

			// chack quality of values, this also helps against SQL injections

			if ($errlev == 0)
			{
				$username = $_REQUEST['user'];
				$confirmation_code = $_REQUEST['code'];

				$checkua = uc_string_polish($username, 'alnum', array('-', '_', '.'), '');
				$checkca = uc_string_polish($confirmation_code, 'alnum', array("'", '-', '_', '.'), '');

				if (($checkua['err'] != 0) || $checkua['changed'] || ($checkca['err'] != 0) || $checkca['changed'])
				{
					$errlev++;
					echo '<br /><font class="problem">ERROR: bad username or bad confirmation code in link.
								Is it incomplete or altered?</font><br /><br />';
					syslog(LOG_NOTICE, 'ERROR: bad username or bad confirmation code');
				}

				if (strpos($confirmation_code, '-confreg-') === false) // not a "confirm registration" password code!
				{
					$errlev++;
					echo '<br /><font class="problem">ERROR: the link code is not for this operation.
								Is it incomplete or altered?</font><br /><br />';
					syslog(LOG_NOTICE, 'ERROR: confirmation code is not for the requested operation');
				}

				unset($checkua);
				unset($checkca);
			}

			if ($errlev == 0)
			{
				$dbc = uc_qidportal_dbconn();
				if ($dbc === false)
				{
					$errlev++;
					echo '<br /><font class="problem">ERROR: cannot connect to DB(?!).
						Retry later, we are sorry for the inconvenient!</font><br /><br />';
					syslog(LOG_NOTICE, 'ERROR: cannot connect to DB(?!)');
				}
			}

			// look for the user in the DB, check about its status

			if ($errlev == 0)
			{
				$dataa = uc_qidportal_enterprisedata_getbyfield($dbc, 'login_name', $username);
				if ($dataa === false || (count($dataa) == 0))
				{
					$errlev++;
					echo '<br /><font class="problem">ERROR: no such user</font><br /><br />';
					syslog(LOG_NOTICE, 'ERROR: cannot find user ' . $username . ' in DB');
				}
				else
				{
					if ($dataa['status'] != 'new')
					{
						$errlev++;
						echo '<br /><font class="problem">ERROR: the status of the account is not suitable
								to confirm the registration. Should be "new", it is "' . $dataa['status'] . '"</font><br /><br />';
						syslog(LOG_NOTICE, 'ERROR: user ' . $username . ', status is not "new"');
					}
				}
			}

			// check about the confirmation code, also make sure that it is not too old

			if ($errlev == 0)
			{
				syslog(LOG_NOTICE, 'INFO: user ' . $username . ' is doing oper ' . $oper . ', checking the confirmation code');

				if ($dataa['confirmation_code'] != $confirmation_code)
				{
					$errlev++;
					echo '<br /><font class="problem">ERROR: wrong confirmation code.
							Did you copy the full link?</font><br /><br />';
					syslog(LOG_NOTICE, 'ERROR: confirmation code mismatch ' .
							$confirmation_code . ' (sent) vs (DB) ' . $dataa['confirmation_code']);
					// this one is worth a log, as it is unusual
					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $username,
						'error', 'confirmation code mismatch, received ' . $confirmation_code, $_SERVER['PHP_SELF'], false, false);
				}
				else
				{
					// **+** TODO TBD check about code creation time. Can we accept it? What if it is too old?
					// if (it is too old) { ...error... }
				}
			}

			// **+** TODO TBD the confirmation code must be for reg confirmation (must contain -...-)

			// if this is the first step, display form to set the password and to change the policies,
			// enter security question and answer, etc. Then leave...

			if ($oper == 'confirm_reg')
			{
				if ($errlev == 0)
				{
					syslog(LOG_NOTICE, 'INFO: user ' . $username . ' OK with oper ' . $oper . ', displaying final reg form');
					// echo '<br /><font class="problem">WHEN I GROW UP, there will be a new form here,
					//			to be filled with more company data!</font><br /><br />';

					echo '<br /><font class="msgok">To finish with your registration and activate the account,
								please fill the form</font><br /><br />';
					uc_qidportal_form_setpwd($dataa['eid'], $username, '', 'finish_reg', $confirmation_code,
						'class="infoask"', 'class="ask"', 'width="100%" cellpadding="4" cellspacing="0" border="0"', true);
				}

				// nothing more to do for this operation
				break;
			}

			// ...otherwise (if the user has also filled the confirmation form) there is more to do

			if ($errlev == 0)
			{
				if (!uc_request_isset('pwda|pwdb', true, true) || ($pwda != $pwdb))
				{
					$errlev++;
					echo '<br /><font class="problem">please, enter the same password in both fields</font><br /><br />' . "\n";
					echo 'To finish with your registration and activate the account,
							please fill the form:<br /><br />';
					uc_qidportal_form_setpwd($eid, $username, '', 'finish_reg', $confirmation_code,
						'class="infoask"', 'class="ask"', 'width="100%" cellpadding="4" cellspacing="0" border="0"', true);
				}
			}

			// make sure I can accept the password

			if ($errlev == 0)
			{
				$pwisoka = uc_string_is_valid_password($pwda, 8, 32);
				if ($pwisoka['err'] != 0)
				{
					$errlev++;
					echo '
						<br /><font class="problem">
							ERROR: the password cannot be accepted (' . $pwisoka['errmsg'] . ').<br />
								Must be 8-32 characters long; valid characters are:<br />
							' . htmlentities($pwisoka['valid_chars']) . '
						</font><br /><br />
					';
					echo 'To finish with your registration and activate the account,
							please fill the form:<br /><br />';
					uc_qidportal_form_setpwd($eid, $username, '', 'finish_reg', $confirmation_code,
						'class="infoask"', 'class="ask"', 'width="100%" cellpadding="4" cellspacing="0" border="0"', true);
				}
				unset($pwisoka);
			}

			if ($errlev == 0)
			{
				$pw_quality = uc_commons_password_strength($pwda);
				if ($pw_quality < 4)
				{
					echo '<font class="warning">
						WARNING: password quality is low. It is recommended to change it with a better one</font><br />' .
						'<script type="text/javascript">alert(\'WARNING: password quality is low. It is recommended to change it with a better one\')</script>' .
						"\n\n";
				}
			}

			// update the record, setting just the status column plus register that [s]he is in, via the session

			if ($errlev == 0)
			{
				$dbpwd = uc_qid_pass2dbv($pwda);
				unset($pwda); // flimsy security precaution
				unset($pwdb); // flimsy security precaution

				syslog(LOG_NOTICE, 'INFO: user ' . $username . ' OK with oper ' . $oper . ', performing DB update, activation');
				$sqlrva = uc_qidportal_enterprisedata_update
				(
					$dbglvl, $dbc, $dataa['eid'],
					array('status' => 'active', 'login_pwd' => $dbpwd)
				);

				if ($sqlrva['err'] != 0)
				{
					if (isset($_REQUEST['user']))
					{
						if (ctype_alnum($_REQUEST['user'])) // prevent SQL-injections
						{
							uc_qidportal_log(true, $dbc, false, false, 'enterprise', $_REQUEST['user'],
								'error', 'user failed registration', 'corporate_registration', false, false);
						}
					}

					$errlev++;
					echo '<br /><font class="problem">ERROR: could not activate registration(?!), try later, please!</font><br /><br />';
					syslog(LOG_NOTICE, 'ERROR: could not update DB with status "active" for EID ' . $dataa['eid'] .
						' err: ' . $sqlrva['err'] . ' descr: ' . $sqlrva['errmsg']);

					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $_REQUEST['user'], 'error',
						'failed to set status to "active" for EID ' . $dataa['eid'] . ', err: ' . $sqlrva['errmsg'],
						$_SERVER['PHP_SELF'], false, false);
				}
				else
				{
					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $username, 'info', 'user fully registered',
						'corporate_registration', false, false);

					// **+** TODO TBD remove confirmation code... or do it in the previous query that sets the status?

					// User is logged in if this session var is set. To logout, I will destroy the session
					$_SESSION['username'] = $username;
					echo '
						<br /><font class="msgok">OK: registration confirmed!</font><br /><br />
						<a href="corporate_ops.php">click here to start</a><br /><br />
					';
					// echo uc_qidportal_corporate_inops_menu() . "<br />\n";

					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $_REQUEST['user'], 'info',
						'recorded enterprise user, EID = ' . $dataa['eid'], $_SERVER['PHP_SELF'], false, false);
				}
			}

			syslog(LOG_NOTICE, '--- END OF ' . $oper . ' -------------------------------------------------------');

			// allow to SW download the SW

			if (isset($dataa)) unset($dataa);
			if (isset($dbc) && ($dbc !== false)) uc_qidportal_dbclose($dbc);
			closelog();

			break;


		// WARNING: login/logout case *MUST* precede the default (case) because there is no break
		// logout moved to corporate_login page, local code removed in 2015.12.02 (for cases "login_enterprise" and "logout")



		// ** ** ** WARNING: this *MUST* immediately follow the login/logout case

		default: // no oper requested, just display the form

			// echo 'DEBUG: oper ' . "$oper<br />";

			uc_qidportal_form_entreg($regvara);

			// display login facility, notice that I am not re-testing the user being already in (1st parm is false)
			$loginhtm = uc_qidportal_form_login_htm(false, 'corporate_registration.php',
						'h', 'style="width:70%;"', 'class="differ"', false, '', 'username', 'pwd', 'login_enterprise');
			if (is_string($loginhtm) && $loginhtm != '')
			{
				// echo '<div class="infoask" style="width:80%;">enter your username and password to log in</div>' . "\n";
				// no more in registration:
				// echo $loginhtm . '<br />' . "\n";
			}
	}
}

echo "\n<br />";

// close the workarea along with my central enclosing table

uc_qidportal_corporate_central_box_close($logged_in, true);

echo '
	</div>
</body>
</html>
';

