<?php

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/countries-data.utf8.php');
include_once(dirname(__FILE__) . '/UbiLib/funcs_countries.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_controller_license.php');
include_once(dirname(__FILE__) . '/Lib/funcs_data_log.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_qid_specs.php');
include_once(dirname(__FILE__) . '/Lib/funcs_forms.php');


// always come first!
session_start();

openlog('edit-enterprise', QID_PORTAL_SYSLOG_OPTION, QID_PORTAL_SYSLOG_FACILITY);

// see regvara-related comments in corporate_registration.php

$globshowa = array
(
	'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, 'fiscal code',       ''),
	'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, 'email',             ''),
	// 'ent_email_check'     => array('ent_email_check',     false,             true,  'email',           40, 'email (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)',    '')
);



/**
	check the new values for the enterprise table (before they go into the DB)
	If a [required] value is missing, it is not an error.
	If a required variable is blank, it is an error!
	vala keys are DB column names (for table "enterprise") and
		must be present in the glbshowa array, otherwise they are ignored
*/

function uc_qidportal_enterprise_checkdata($dolog, $doprint, $vala)
{
	global $globshowa;

	$rva = array('err' => 0, 'errmsg' => '', 'displaymsg' => '');

	foreach ($globshowa as $vvk => $vva)
	{
		$dbcol = $vva[1];
		$isrequired = $vva[2];
		$vdescr = $vva[5];

		if (isset($vala[$dbcol]))
		{
			$vcontent = $vala[$dbcol];

			// syslog(LOG_NOTICE, "DEBUG: _enterprise_checkdata vs $dbcol -> $vcontent");

			if ($isrequired && (($vcontent === false) || ($vcontent == '')))
			{
				$rva['err'] = 1;
				$rva['errmsg'] .= ('cannot be empty: ' . $dbcol);
				$rva['displaymsg'] .= ('cannot be empty: ' . $vdescr . '<br />');
				if ($dolog) syslog(LOG_NOTICE, 'ERROR: form var for ' . $dbcol . ' cannot be empty');
				if ($doprint) echo '<font class="problem">ERROR: ' . $vdescr . ' cannot be empty</font><br />';
				continue; // I want to check the other ones, too
			}

			$maxlen = $vva[4];
			$vformat = $vva[3];

			// syslog(LOG_NOTICE, "DEBUG: _enterprise_checkdata, checking vs len $maxlen, format $vformat");

			// now check that it is well-formed (the new way... the old way to do this is in code before 2015.01.20)

			$polisheda = uc_string_polish($vcontent, $vformat, array(), '');
			if ($polisheda['err'] != 0)
			{
				if ($dolog) syslog(LOG_NOTICE, 'ERROR: form var for ' . $dbcol . ', error is: ' . $polisheda['errmsg']);
				if ($doprint) echo '<font class="problem">ERROR: for ' . $vdescr . ': ' . $polisheda['errmsg'] . '</font><br />';
				$rva['errmsg'] .= ('bad characters in field "' . $vdescr);
				$rva['displaymsg'] .= ('bad characters in field "' . $vdescr . '", please edit it<br />');
				$globshowa[$vvk][6] = $vcontent = $polisheda['newstr'];
			}
			else
			{
				if ($polisheda['changed'])
				{
					$rva['err'] = 2;
					$globshowa[$vvk][6] = $vcontent = $polisheda['newstr'];
					$rva['displaymsg'] .= ('field "' . $vdescr . '" modified to make it acceptable, please review the changes<br />');
					if ($dolog)
						{ syslog(LOG_NOTICE, 'ERROR: form var for ' . $dbcol . ', error is: ' . $polisheda['errmsg']); }
					if ($doprint)
						{ echo '<font class="problem">' . $vdescr . ' reviewed, please check the changes</font><br />'; }
				}
			}
			unset($polisheda);

			// now check the length

			if (strlen($vcontent) > $maxlen)
			{
				$globshowa[$vvk][6] = $vcontent = substr($vcontent, 0, $maxlen);
				$rva['errmsg'] .= ('content too long for field: "' . $dbcol . '"');
				$rva['displaymsg'] .= ('value for "' . $vdescr. '" was too long, please review the shorter version<br />');
				if ($dolog)
					{ syslog(LOG_NOTICE, 'ERROR: content too long for field: ' . $dbcol); }
				if ($doprint)
					{ echo '<font class="problem">' . $vdescr. ' was too long, please review the shorter version</font><br />'; }
			}

			// indeed, this must be done... always??? **+** TODO TBD check
			$globshowa[$vvk][6] = $vcontent;
			// if ($dbglvl > 20) syslog(LOG_NOTICE, "DEBUG: checking form var '$vname' ($vdescr), maxlen $maxlen, format $vformat");
		}

		/* NOT MY BUSINESS HERE:
		else
		{
			if ($isrequired)
			{
				// **+** append ERROR...
				$rva['errmsg'] .= ('value is empty for required field "' . $vdescr);
				$rva['displaymsg'] .= ('value cannot be empty for required field "' . $vdescr . '"<br />');
				continue; // I want to check the other ones, too
			}
		}
		*/
	}

	return $rva;
}


function uc_qidportal_form_edit_ent_data
(
	$dbc, $eid, $use_showa,
	$targetpage,
	$divattrs, $tblattrs, $rowattrs, $namecellattrs, $cellattrs, $inputattrs
)
{
	global $globshowa;
	global $uc_world_countries_a;

	// DEBUG: echo '<pre>'; print_r($globshowa); echo '</pre><br />';

	$edata = uc_qidportal_enterprisedata_get($dbc, $eid);
	if (!is_array($edata)) return false; // ?!

	echo '
		<div ' . $divattrs . '>
			<form action="' . $targetpage . '" method="post">
			<input type="hidden" name="oper" value="change_enterprise_data" />
			<table ' . $tblattrs . '>
	';

	foreach($globshowa as $fkk => $theva)
	{
		$fname   = $theva[0];
		$dbname  = $theva[1];
		$emptyok = $theva[2];
		$size    = $theva[4];
		$tagname = $theva[5];

		// If we come from form input, the REQUEST is set for every variable, so if use_showa is set,
		//		I do not have to fish from the DB at all (even if the var is empty). Period.
		if ($use_showa)
			{ $showv   = $theva[6]; }
		else
			{ $showv   = $edata[$dbname]; }

		// country is a special case, because it requires a select

		if ($fkk == 'ent_country')
		{
			// it would be much more efficient just to echo each one after having printed the select tag, instead
			// of creating a very big string, but I like it this way... for future extensions
			$countryopts = '';
			foreach($uc_world_countries_a as $cid => $cname)
			{
				if ($cid == $showv)
					{ $countryopts .= ('<option value="' . $cid . '" selected>' . $cname . '</option>' . "\n"); }
				else
					{ $countryopts .= ('<option value="' . $cid . '">' . $cname . '</option>' . "\n"); }
			}

			echo '
				<tr ' . $rowattrs . '>
					<td ' . $namecellattrs . '>' . $tagname . '</td>
					<td ' . $cellattrs . '>
						<select id="ent_country" name="ent_country" ' . $inputattrs . '>
						' . $countryopts . '
						</select>
					</td>
				</tr>
			';

			unset($countryopts);
			continue;
		}

		echo '
				<tr ' . $rowattrs . '>
					<td ' . $namecellattrs . '>' . $tagname . '</td>
					<td ' . $cellattrs . '>
						<input id="' . $fname . '" type="text"
							name="' . $fname . '" value="' . $showv . '" ' . ($emptyok ? '' : 'required') . '
							size="' . $size . '" maxlength="' . $size . '" ' . $inputattrs . '/>
					</td>
				</tr>
		';
	}

	echo '
				<tr ' . $rowattrs . '>
					<td></td>
					<td ' . $cellattrs . '>
						<input type="submit" name="goop" value="Change company data" ' .
							uc_js_clickopt('confirm changes?') . '/>
					</td>
				</tr>
			</table>
			</form>
		</div>
	';

	unset($licaa);
}



// -------------------------------------------------------------------------------------------------------------



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'];

echo '<!DOCTYPE html>
<html lang="en">
';

// produce standard HTML head tag and content

uc_qidportal_corporate_htm_head('Q-ID : Corporate : Edit Company Data', '');

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_edit_data.php', 'Edit company data');

if ($logged_in)
{
	// echo '<div style="text-align:right;font-size:10px;">USER: ' . $_SESSION['username'] .
	//	' :: <a href="corporate_login.php?oper=logout">LOGOUT</a>&nbsp; &nbsp;</div><br />';

	$dbc = uc_qidportal_dbconn();
	$trid   = date('YmdHis') . '-' . mt_rand(1000, 9999);
	$enta = uc_qidportal_enterprisedata_getbyfield($dbc, 'login_name', $_SESSION['username']);
	$eid = $enta['eid'];

	switch($oper)
	{
		case 'change_enterprise_data':

			$errlev = 0;
			syslog(LOG_NOTICE, 'DEBUG: user ' . $_SESSION['username'] . ' requested update of company data');

			$valua = array();
			foreach($globshowa as $dbk => $fva)
			{
				// debug
				// echo '<font class="msgok">' . $dbk . ': ' . (isset($_REQUEST[$dbk]) ? $_REQUEST[$dbk] : '[ NOT SET ]') . "</font><br />\n";
				$fname   = $fva[0];
				$dbname  = $fva[1];
				$valua[$dbname] = $_REQUEST[$fname];
			}
			$checkrva = uc_qidportal_enterprise_checkdata(true, true, $valua);

			// check that the country is in my array -otherwise someone messed with the variables(?!)
			if (isset($_REQUEST['ent_country']) && ($_REQUEST['ent_country'] != '') &&
					!in_array($_REQUEST['ent_country'], array_keys($uc_world_countries_a)))
			{
				$errlev++;
				// I just raise the error flag in the array that I already have
				$checkrva['err'] = 5;
				echo '<font class="problem">ERROR: value for "country" is unknown(?!)<br />' . "\n\n";
				unset($_REQUEST['ent_country']); // I want to remove a potential attack mean... can I do this?
			}

			if ($checkrva['err'] != 0)
			{
				$errlev++;
				// echo '<font class="problem">Cannot accept input, there are errors (review values, re-enter data):<br />' .
				//		$checkrva['displaymsg'] . "</font><br />\n";
				// as I have parametrized uc_qidportal_enterprise_checkdata to display errors, I am not doing it twice:
				echo '<font class="problem">Cannot accept input, there are errors (review values, re-enter data)<br />' . "\n\n";

				// debug
				// echo '<pre>'; print_r($checkrva); echo '</pre><br />';
			}

			// actually update the data

			if ($errlev == 0)
			{
				syslog(LOG_NOTICE, 'INFO: user ' . $_SESSION['username'] . ' OK with oper ' . $oper . ', performing DB update');
				// SQL-injection prevention is done inside uc_qidportal_enterprisedata_update
				$sqlrva = uc_qidportal_enterprisedata_update(11, $dbc, $eid, $valua);

				if ($sqlrva['err'] != 0)
				{
					$errlev++;
					echo '<br /><font class="problem">ERROR: could not record your data(?!), try later, please!</font><br /><br />';
					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $_SESSION['username'],
								'error', 'user failed company data update: ' . $sqlrva['errmsg'],
								$_SERVER['PHP_SELF'], false, false);
					syslog(LOG_NOTICE, 'ERROR: could not update company data for EID ' . $eid .
						' (user ' . $_SESSION['username'] . '), err: ' . $sqlrva['err'] . ' descr: ' . $sqlrva['errmsg']);
				}
				else
				{
					echo '<br /><font class="msgok">OK: your company data has been updated.</font><br /><br />';
					syslog(LOG_NOTICE, 'INFO: EID ' . $eid . ' (user ' . $_SESSION['username'] . ') changed company data');
					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $_SESSION['username'],
						'info', 'user changed company data', $_SERVER['PHP_SELF'], false, false);

					// send e-mail to the user here (confirm that data has changed),
					// but do not check for the return. Give for granted that it is delivered
					$mailrv = uc_send_simple_mail_sk(QID_PORTAL_MXRELAY_HOST, QID_PORTAL_MX_FROM, $valua['email_main'],
						'QID portal warning: company data changed',
						array('Information: company data was changed by user ' . $_SESSION['username'],
								'The company data has been changed on www.q-id.org by user ' . $_SESSION['username'],
								'Please, contact us if you think that this operation was not performed by your company personnel.',
								'Thanks - the QID team')
					);
				}
			}

			unset($valua);

			if ($errlev != 0)
			{
				// redisplay the form, but using the data in array showa
				/*
				uc_qidportal_form_edit_ent_data($dbc, $eid, true, 'corporate_edit_data.php',
					'style="width:92%; font-size:14px"', 'class="tblbase tonered" style="width:100%"',
					'', 'style="border-bottom: 1px solid #ff5555;"', 'style="border-bottom: 1px solid #ff5555;"', '');
				*/
				// last params: $divattrs, $tblattrs, $rowattrs, $namecellattrs, $cellattrs, $inputattrs
				uc_qidportal_form_edit_ent_data($dbc, $eid, true, 'corporate_edit_data.php',
					'style="width:92%; font-size:14px"', 'class="tblbase" style="width:100%"',
					'', 'class="nxd_label"', 'style="width:200px;"', 'class="nxd_reg_input"');
			}
			break;



		case 'change_pass':

			$errlev = 0;

			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\n";
				}
			}

			// make sure password is acceptable

			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 />
					';
				}
				unset($pwisoka);
			}

			// tell about password quality

			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 />' . "\n";
					echo '
						<script type="text/javascript">
							alert(\'WARNING: password quality is low. It is recommended to change it with a better one\')
						</script>
					';
				}
			}

			if ($errlev == 0)
			{
				$dbpwd = uc_qid_pass2dbv($pwda);
				unset($pwda); // flimsy security precaution
				unset($pwdb); // flimsy security precaution

				syslog(LOG_NOTICE, 'INFO: user ' . $_SESSION['username'] .
							' OK with oper ' . $oper . ', performing DB update for password');
				// SQL-injection prevention is done inside uc_qidportal_enterprisedata_update
				$sqlrva = uc_qidportal_enterprisedata_update(11, $dbc, $eid, array('login_pwd' => $dbpwd));

				if ($sqlrva['err'] != 0)
				{
					$errlev++;
					echo '<br /><font class="problem">ERROR: could not change your password(?!), try later, please!</font><br /><br />';
					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $_SESSION['username'],
							'error', 'user failed password change: ' . $sqlrva['errmsg'],
							$_SERVER['PHP_SELF'], false, false);
					syslog(LOG_NOTICE, 'ERROR: could not change password for EID ' . $eid .
						' (user ' . $_SESSION['username'] . '), err: ' . $sqlrva['err'] . ' descr: ' . $sqlrva['errmsg']);
				}
				else
				{
					echo '<br /><font class="msgok">OK: password changed!</font><br /><br />';
					syslog(LOG_NOTICE, 'INFO: EID ' . $eid . ' (user ' . $_SESSION['username'] . ') changed password');
					uc_qidportal_log(true, $dbc, false, false, 'enterprise', $_SESSION['username'], 'info', 'user changed password',
						$_SERVER['PHP_SELF'], false, false);

					// send e-mail to the user here (confirm that password has changed),
					// but do not check for the return. Give for granted that it is delivered
					$mailrv = uc_send_simple_mail_sk(QID_PORTAL_MXRELAY_HOST, QID_PORTAL_MX_FROM, $enta['email'],
						'QID portal warning: password change',
						array('Information: password change for user ' . $_SESSION['username'],
								'the password has been changed on www.q-id.org by user ' . $_SESSION['username'],
								'Please, contact us if you think that this operation was not performed by your company personnel.',
								'Thanks - the QID team')
					);
				}
			}

			if ($errlev != 0)
			{
				uc_qidportal_form_setpwd($eid, $_SESSION['username'], '', 'change_pass', 'not_important',
						'class="infoask"', 'class="ask"', 'width="100%" cellpadding="4" cellspacing="0" border="0"', 'SET PASSWORD');
			}

			break;



		default: // no oper requested, just display the forms to edit the company data

			// syslog(LOG_NOTICE, 'DEBUG: eid is ' . $eid);
			/*
			uc_qidportal_form_edit_ent_data($dbc, $eid, false, 'corporate_edit_data.php',
				'style="width:92%; font-size:14px"', 'class="tblbase tonered" style="width:100%"',
				'', 'style="border-bottom: 1px solid #ff5555;"', 'style="border-bottom: 1px solid #ff5555;"', '');
			*/
			// last params: $divattrs, $tblattrs, $rowattrs, $namecellattrs, $cellattrs, $inputattrs

			echo '
				<table cellpadding="5" border="0" style="b">
					<tr><td style="width:480px;vertical-align:top;border-right: 1px dotted #222222;">';

			uc_qidportal_form_edit_ent_data($dbc, $eid, false, 'corporate_edit_data.php',
				'style="width:92%; font-size:14px"', 'class="tblbase" style="width:100%"',
				'', 'class="nxd_label"', 'style="width:200px;"', 'class="nxd_reg_input"');

			// echo '<br /><br />';

			echo '</td><td style="vertical-align:top;">';

			uc_qidportal_form_setpwd($eid, $_SESSION['username'], '', 'change_pass', 'not_important',
						'class="infoask"', 'class="ask"', 'width="100%" cellpadding="4" cellspacing="0" border="0"', 'SET PASSWORD');

			echo '</td></tr></table>';
			echo '<br /><br />';
	}

	uc_close_conn($dbc);

	// echo uc_qidportal_corporate_inops_menu() . "<br />\n";
}
else
{
	echo '
		<br /><br /><br /><font class="problem">ERROR: you are not logged in. Please,
			<a href="corporate_login.php">authenticate</a> or <a href="corporate_register.php">register</a>.
		</font><br /><br />
	';
}

// close the workarea alog with my central enclosing table

uc_qidportal_corporate_central_box_close($logged_in);

echo '
	</div>  <!-- end of divMain, unless HTML is messed up -->
</body>
</html>
';

closelog();

