#!/usr/bin/perl -Tw -I. -I/usr/local/positive/Perl

#
# This software is copyright (c) 2001-2002 Positive Networks, Inc.  All rights reserved.
# 
# This software is the proprietary and confidential property of Positive Networks, Inc.
# Possession, transmission, publication, or use of this software is prohibited except by prior written consent.
#  

# reg.pl - handles the user registration proces

use strict;
use Pos::Webtop::Web::ModuleLoader;
use Pos::Webtop::Web::OEMLoader;
use Digest::MD5;

my $tb = Pos::Webtop::Toolbox->new();
my $client = $tb->getClient();
my $cgi = $tb->getCgi();

$client->checkSession(ignoreAuxAuth=> 1);
$client->repersistValues(values=>['startUrl']);

my $authdb = $tb->getPolicyDb();
my ($authType) = $authdb->query(sql =>  "select auth_type_id from user_auth_types where user_id = '" . $client->getUserId() . "'");

if ($cgi->param('primaryEmail')) 
{
	my $db = $tb->getPolicyDb();
	my $workEmail = $cgi->param('workEmail');
	my $homeEmail = $cgi->param('homeEmail');
	my $primaryEmail = $cgi->param('primaryEmail');
	my $workPhone = $cgi->param('workPhone');
	my $homePhone = $cgi->param('homePhone');
	my $firstName = $cgi->param('fname');
	my $middleName = $cgi->param('mname');
	my $lastName = $cgi->param('lname');
	my $recieveServiceHome = $cgi->param('recieveServiceHome');
	my $recieveServiceWork = $cgi->param('recieveServiceWork');
	my $errorValue;
	my $errorTypeValue;

	# First set the primary e-mail

	if ($primaryEmail eq 'home' and $homeEmail)
	{
		$primaryEmail = 2;
	}
	else
	{
		$primaryEmail = 1;
	}

	my $sql = "	UPDATE users 
					SET primary_user_email_id = '" . $db->oracle_escape(dirty=>$primaryEmail) . "', modified_date = " . $db->getCurrentDateString() . " 
					WHERE user_id = '" . $client->getUserId() . "'
				";

	$db->do(sql=>$sql);

	# Now start going down the list of settable things

	if (!$firstName)
	{
		$errorTypeValue .= '1';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'First Name was Invalid';
		}
	}
	else
	{
		$sql = "	UPDATE users 
					SET first_name='" . $db->oracle_escape(dirty=>$firstName) . "', 
						primary_user_email_id = '" . $db->oracle_escape(dirty=>$primaryEmail) . "', 
						modified_date = " . $db->getCurrentDateString() . " 
					WHERE user_id = '" . $client->getUserId() . "'
				";

		$db->do(sql=>$sql);
	}

	if(!$lastName)
	{
		$errorTypeValue .= '2';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Last Name was Invalid';
		}
	}
	else
	{
		$sql = "	UPDATE users 
					SET last_name='" . $db->oracle_escape(dirty=>$lastName) . "'
					WHERE user_id = '" . $client->getUserId() . "'
				";

		$db->do(sql=>$sql);
	}

	if ($middleName and $middleName !~ /[A-Za-z]/)
	{
		$errorTypeValue .='9';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Middle Initial must only be a Letter [A-Z]';
		}
	}
	else
	{
		$sql = "	UPDATE users 
					SET middle_name='" . $db->oracle_escape(dirty=>$middleName) . "'
					WHERE user_id = '" . $client->getUserId() . "'
				";

		$db->do(sql=>$sql);
	}

	if ($workEmail !~ /.+\@.+\..+/) 
	{
		$errorTypeValue .= '3';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Please enter a valid Work Email address';
		}
	}
	else
	{
		$db->do(sql=>"	
							DELETE FROM user_email_addresses 
							WHERE user_id = '" . $client->getUserId() . "'
							AND user_email_id ='1'
						");

		$db->do(sql=>"	
							INSERT INTO user_email_addresses(user_id, user_email_id, email_address, email_type_id)
							VALUES('" . $client->getUserId() .  "', '1', '" . $db->oracle_escape(dirty=>$workEmail) . "', '1')
						");
	}

	if ($homeEmail and $homeEmail !~ /^\w+\@.*\.\w+$/) 
	{
		$errorTypeValue .= '4';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Please enter a valid Home Email address';
		}
	}
	else
	{
		$db->do(sql=>"	
							DELETE FROM user_email_addresses 
							WHERE user_id = '" . $client->getUserId() . "'
                     AND user_email_id ='2'
						");

		$db->do(sql=>"
							INSERT INTO user_email_addresses(user_id, user_email_id, email_address, email_type_id)
							VALUES( '" . $client->getUserId() . "', '2', '" . $db->oracle_escape(dirty=>$homeEmail) . "', '2')
						");
	}

	if(not ( defined $workPhone and length $workPhone ) )
	{
		$errorTypeValue .= '5';

		if($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Work Phone is required';
		}

		$db->do(sql=>"
							UPDATE user_phone_numbers
							SET phone_number =''
							WHERE user_id = '" . $client->getUserId() . "'
							AND user_phone_number_id = '1'
						");
	}
	else
	{
#		my $workPhoneCheck = $workPhone;
#		$workPhoneCheck =~ s/\D//g;
#
#		if (length $workPhoneCheck ne 10)
#		{
#			$errorTypeValue .= '5';
#
#			if($errorValue)
#			{
#				$errorValue = 'Multiple Invalid Fields';
#			}
#			else
#			{
#				$errorValue = 'Please enter a valid Work Phone (xxx-xxx-xxxx)';
#			}
#
#			$db->do(sql=>"
#								UPDATE user_phone_numbers
#								SET phone_number =''
#								WHERE user_id = '" . $client->getUserId() . "'
#								AND user_phone_number_id = '1'
#							");
#		}
#		else
#		{
#			my ($area, $exchange, $number) = (substr($workPhoneCheck, 0, 3), substr($workPhoneCheck, 3, 3), substr($workPhoneCheck, 6));
#			$workPhone = $area . '-' . $exchange . '-' . $number;
#			$db->do(sql=>"
#								DELETE FROM user_phone_numbers 
#								WHERE user_id = '" . $client->getUserId() . "'
#								AND user_phone_number_id ='1'
#							");
#
#			$db->do(sql=>"
#								INSERT INTO user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id)
#								VALUES( '" . $db->oracle_escape(dirty=>$workPhone) . "', '" . $client->getUserId() . "', '1', '1')
#							");
#		}

		$workPhone = substr($workPhone,0,30);
		$db->do(sql=>"
							DELETE FROM user_phone_numbers 
							WHERE user_id = '" . $client->getUserId() . "'
							AND user_phone_number_id ='1'
						");

		$db->do(sql=>"
							INSERT INTO user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id)
							VALUES( '" . $db->oracle_escape(dirty=>$workPhone) . "', '" . $client->getUserId() . "', '1', '1')
						");
	}

	if( defined $homePhone and length $homePhone )
	{
#		my $homePhoneCheck = $homePhone;
#		$homePhoneCheck =~ s/\D//g;
#
#		if (length $homePhoneCheck ne 10)
#		{
#			$errorTypeValue .= '6';
#
#			if($errorValue)
#			{
#				$errorValue = 'Multiple Invalid Fields';
#			}
#			else
#			{
#				$errorValue = 'Please enter a valid Home Phone (xxx-xxx-xxxx)';
#			}
#		}
#		else
#		{
#			my ($area, $exchange, $number) = (substr($homePhoneCheck, 0, 3), substr($homePhoneCheck, 3, 3), substr($homePhoneCheck, 6));
#			$homePhone = $area . '-' . $exchange . '-' . $number;
#			$db->do(sql=>"
#								DELETE FROM user_phone_numbers 
#								WHERE user_id = '" . $client->getUserId() . "'
#								AND user_phone_number_id ='2'
#							");
#
#			$db->do(sql=>"
#								INSERT into user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id)
#								VALUES( '" . $db->oracle_escape(dirty=>$homePhone) . "', '" . $client->getUserId() . "', '2', '2')
#							");
#		}
		
		$homePhone = substr($homePhone,0,30);
		$db->do(sql=>"
							DELETE FROM user_phone_numbers 
							WHERE user_id = '" . $client->getUserId() . "'
							AND user_phone_number_id ='2'
						");

		$db->do(sql=>"
							INSERT into user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id)
							VALUES( '" . $db->oracle_escape(dirty=>$homePhone) . "', '" . $client->getUserId() . "', '2', '2')
						");

	}
	else
	{
		$db->do(sql=>"
							UPDATE user_phone_numbers
							SET phone_number =''
							WHERE user_id = '" . $client->getUserId() . "'
							AND user_phone_number_id = '2'
						");
	}

	$db->commit();

	if ($errorTypeValue)
	{
		verifyUserInfo(authType=> $authType, errorType=>$errorTypeValue, errorValue=>$errorValue, tb=>$tb);
		exit;
	}
	else
	{

		my $refreshModule = $client->getPersistedValue( name => "refreshModule" );

	 #  print "Content-type: text/html\n\n
	 #        <html>
	 #        <head>
	 #        <META HTTP-EQUIV=REFRESH CONTENT='0; URL='>
	 #        </head></html>
	 #           ";

		print "Content-type: text/html\n\n
			
			<HTML>
			<BODY>
			<form method='POST' action='main.pl' name='refreshForm'>
			<input type='hidden' name='module' value='$refreshModule'/>

		";
					
		print $client->getFormInputs();

		print "
			</form>

			<script language='JavaScript1.2' type='text/javascript'>

				document.refreshForm.submit();

			</script>

			</BODY>
			</HTML>
		";
	}
}
else
{
	verifyUserInfo(authType=> $authType, tb=>$tb);
}
sub getUserInfo 
{
	my $tb = @{{@_}}{qw/tb/};
	my $db = $tb->getPolicyDb();
	my $client = $tb->getClient();
	my $userId = $client->getUserId();

	my $sql = "	SELECT a.last_name, a.first_name, a.middle_name, a.primary_user_email_id,
						(
							SELECT u.email_address
							FROM user_email_addresses u
							WHERE email_type_id ='1'
							AND u.user_id = '$userId'
						) as Primary_Email,
						(
							SELECT u.email_address
							FROM user_email_addresses u
							WHERE email_type_id ='2'
							AND u.user_id = '$userId'
						) as Secondary_Email,
						(
							SELECT p.phone_number
							FROM user_phone_numbers p
							WHERE p.phone_number_type_id = '1'
							AND p.user_id = '$userId'
						) as Primary_Phone,
						(
							SELECT p.phone_number from user_phone_numbers p
  							WHERE p.phone_number_type_id = '2'
							AND p.user_id = '$userId'
						) as Secondary_Phone
					FROM users a
					WHERE user_id = '$userId'
				";

	my @userInfo = $db->query(sql=>$sql);
	return @userInfo;
}

sub verifyUserInfo 
{
	my ($tb, $errorType, $errorValue, $authType) = @{{@_}}{qw/tb errorType errorValue authType/};

	my $db = $tb->getPolicyDb();
	my $client = $tb->getClient();
	my $cgi = $tb->getCgi();

	my @customerInfo = getUserInfo(tb => $tb);
	my ($lname, $fname, $mname, $primaryEmail, $workEmail, $homeEmail, $workPhone, $homePhone) = @{$customerInfo[0]};
	my $minit = substr($mname, 0, 1);

	my $error='';

	$errorType = "" unless defined($errorType);

	if ($errorType =~ /1/ or $errorType =~ /2/ or $errorType =~ /9/)
	{
		$error = $errorValue;
	}

	my $oem = $tb->getOem;

	$oem->printHtmlHeader(title => "Registration");
	$oem->printBodyHeader();

	$lname = "" unless defined($lname);
	$fname = "" unless defined($fname);
	$mname = "" unless defined($mname);
	$primaryEmail = "" unless defined($primaryEmail);
	$workEmail = "" unless defined($workEmail);
	$homeEmail = "" unless defined($homeEmail);
	$workPhone = "" unless defined($workPhone);
	$homePhone = "" unless defined($homePhone);

	my $numSteps;
	$numSteps = 2 if $authType == 3;
	$numSteps = 3 if $authType == 2;

	print "
			
			
			 <form method='POST' action='main.pl' name='refreshForm'>
			          ";

         my $refreshModule = $client->getPersistedValue( name => "refreshModule" );
           print"


                    <input type='hidden' name='module' value='$refreshModule'/>
																											                                 ";
                               print  $client->getFormInputs();

                    print "
             </form>
																																																																																		
			
			
			<br><br>
			<form method='POST' action='reg2.pl' name='finishForm'>	
				<center>
				<table align='center' border='0' cellspacing='0' cellpadding='2' width='500'>
					<tr>
						<td align='center' class='BOXTD1'>
							<i class='DEF'>
							Please note that all fields marked with an asterisk (<font color='red'>*</font>) are required fields
							</i>
						</td>
					</tr>	
				</table>
				<table border='0' cellspacing='1' cellpadding='0' bgcolor='#000000' width='500'>
				<tr><td>
				<table border='0' cellspacing='0' cellpadding='2' width='100%'>
					<tr>
						<td class='title' align='left' width='20%'>&nbsp;Name:</td>
						<td class='title' align='center' width='80%'>
			";

	if ($error)
	{
		print "
						<span style=\"background-color: #FFFFC0; font-weight: normal; color: red\">
						&nbsp;Error: $error&nbsp;</span>
				";
	}

	print "
						</td>
					</tr>
				</table>
				<table border='0' cellspacing='0' cellpadding='2' width='500'>
					<tr>
						<td class='BOXTD1' bgcolor='#FFFFFF' align='left'>
			";

	if ($errorType =~ /1/)
	{
		print "<font color=red><b>&nbsp;First*</b></font>";
	} else {
		print "&nbsp;<b>First:</b><font color='red'>*</font>";
	}

		print "
							<input type='text' name='fname' value='$fname' maxlength='49' id='firstName'>
						</td>
						<td align='left' bgcolor='#FFFFFF' class='BOXTD1'>
				";

	if ($errorType =~ /9/)
	{
		print "<font color='red'><b>MI:</b></font>";
	} else {
		print "<b>MI:</b>";
	}

		print "
							<input type='text' size='1' name='mname' value='$minit' maxlength='1'>
						</td>
						<td align='left' bgcolor='#FFFFFF' class='BOXTD1'>
				";

	if ($errorType =~ /2/)
	{
		print "<font color='red'><b>Last:*</b></font>";
	} else {
		print "<b>Last:</b><font color='red'>*</font>";
	}

		print "
							<input type='text' name='lname' value='$lname' maxlength='49'>
						</td>
				";

	if ($errorType !~ /2/ and $errorType !~ /1/ and $errorType !~ /9/)
	{
		$error = $errorValue;
	}
	else
	{
		$error = '';
	}

	print "
				</tr>
			</table>
			<table border='0' cellspacing='0' cellpadding='2' width='500'>
				<tr>
					<td class='title' align='left' width='30%'>&nbsp;Email and Phone:</td>
					<td class='title' align='center' width='70%' colspan='2'>
			";

	if ($error)
	{
		print "
					<span style=\"background-color: #FFFFC0; color: red\"> <b>&nbsp;Error: $error </b></span>
				";
	}

	print "
					</td>
				</tr>
			</table>
			<table border='0' cellspacing='0' cellpadding='2' width='500'>
				<tr>
					<td class='bgfill' bgcolor='#FFFFFF'></td>
					<td bgcolor='#FFFFFF' class='bgfill'></td>
					<td align='left' bgcolor='#FFFFFF' class='BOXTD1'> Primary:</td>
				</tr>
				<tr>
					<td class='bgfill' bgcolor='#FFFFFF' align='left' width='85'>
	";

	if($errorType =~ /3/)
	{
		print "
					<font color=red><b>&nbsp;Work Email</b></font>:<font color='red'>*</font>
				";
	} else {
		print "
					&nbsp;<b>Work Email:</b><font color='red'>*</font>
				";
	}

	print "
					</td>
					<td bgcolor='#FFFFFF' class='bgfill'><input type ='text' name='workEmail' size='50' value='$workEmail' maxlength='254'></td>
			";

	if ($primaryEmail ne '2')
	{
		print " 
					<td bgcolor='#FFFFFF' class='bgfill' align='center'><input type ='radio' checked name='primaryEmail' value='work'></td>
				";
	}
	else
	{
		print " 
					<td bgcolor='#FFFFFF' align='center' class='bgfill'><input type ='radio' name='primaryEmail' value='work'></td>
				";
	}

	print "
				</tr>
				<tr>
					<td class='bgfill' bgcolor='#FFFFFF' align='left' width='100'>
			";

	if($errorType =~ /4/)
	{
		print " 
					&nbsp;<font color=red><b>Alternate Email</b>:</font>
				";
	} else {
		print " 
					&nbsp;<b>Alternate Email</b>:
				";
	}

	print "
					</td>
					<td bgcolor='#FFFFFF' class='bgfill'><input type ='text' name='homeEmail' size='50' value='$homeEmail' maxlength='254'></td>
			";

	if ($primaryEmail == '2')
	{
		print "
					<td bgcolor='#FFFFFF' align='center' class='bgfill'><input type ='radio' checked name='primaryEmail' value='home'></td>
				";
	}
	else
	{
		print " 
					<td bgcolor='#FFFFFF' align='center' class='bgfill'><input type ='radio' name='primaryEmail' value='home'></td>
				";
	}

	print	"
				</tr>
			</table>
			<table border='0' cellspacing='0' cellpadding='2' width='500'>
				<tr>
					<td class='bgfill' bgcolor='#FFFFFF' align='left' width='85'>
			";

	if($errorType =~ /5/)
	{
		print	"
					&nbsp;<font color='red'><b>Work Phone</b>:*</font>
				";
	}
	else
	{
		print "
					&nbsp;<b>Work Phone:</b><font color='red'>*</font>
				";
	}

	print " 
					</td>
					<td bgcolor='#FFFFFF' class='bgfill'><input type='text' size='20' maxlength='30' name='workPhone' value='$workPhone'></td>
			";

	if($errorType =~ /6/)
	{
		print "
					<td bgcolor='#FFFFFF' class='BOXTD1'><font color=red><b>Alternate Phone</b></font>:</td>
				";
	}
	else
	{
		print "
					<td bgcolor='#FFFFFF' class='BOXTD1'><b>Alternate Phone:</b></td>
				";
	}

	print "
					<td bgcolor='#FFFFFF' class='bgfill'><input type='text' size='20' maxlength='30' name='homePhone' value='$homePhone'></td>
				</tr>
				<tr>
					<td bgcolor='#FFFFFF' class='bgfill' align='center' colspan='4'>
			";
   $client->repersistValues( values=> [ "refreshModule" ] );
	
		
	print $client->getFormInputs();
	print "
					</td>
				</tr>
			</table>
			</td></tr>
			</table><br/>
			<table align='center' border='0' cellspacing='10' style='height: 32px'>
				<tr>
					<td><input type=submit value='Continue'></td>
					<td><input type=button value='Cancel' onClick='javascript:document.refreshForm.submit();'></td>
				</tr>
			</table>
		</form>
		</center>

		<script language='JavaScript1.3' TYPE='text/javascript'>
			document.getElementById('firstName').focus();
		</script>
		";


	$oem->printBodyFooter();
	$oem->printHtmlFooter();

}

