<?php
//==================================================================================
// This php registration script can handle an insert, an update and a delete
// if a session user is not present --> must be an insert (new registration)  
// if a session user is present     --> must be an update (update/delete profile)
//==================================================================================

    include('dbIOoo.inc');

    session_start();				#get a handle to the session 
    
    $host      = "localhost";			#database connection info
    $port      = null;			
    $DBname    = 'demo2';
    $DBuser    = 'demo2';
    $DBpswd    = 'demo2';

    if (! $_SESSION[cust_id])			#if no session for customer
	$mode = 'new';				#  it must be a 'new' registration
    else { 					#otherwise
        $mode = 'upd';				#  it must be an 'update' of profile
	read_data('repopulate');		#  read from DB and populate screen
    }

    if ($_POST)       				#if 2nd & subsequent times
    {						
    	validate();				#validate form fields	

	if (! $msg)				#if all required fields are entered
	    read_data('check_unique');		#check to make sure the user is unique

	if (! $msg && $mode == 'new')		#if OK and mode=new
	    insert_data();			#  register a new customer			

	if (! $msg && $mode == 'upd')		#if OK and mode=upd
	    update_data();			#  update customer profile			
    }
    
    display();					#display the screen 

//=============================================================================
// Validate all required input fields
//=============================================================================
    function validate()
    {
	global $mode, $cust_id, $user, $pswd, $pswd2, $first, $last, $addr, $phone, $msg;   
	global $user_error,$pswd_error,$first_error,$last_error,$addr_error;
	
    	$user    = $_POST['user'];			//get HTML form entry data					
	$pswd    = $_POST['pswd'];
    	$pswd2   = $_POST['pswd2'];
    	$first   = $_POST['first']; 
    	$last    = $_POST['last'];
    	$phone   = $_POST['phone'];
    	$addr    = $_POST['addr'];

	if (! $user  || preg_match('/^\s*$/',$user) )	//if field is null or all spaces 
	      $user_error = '*';
	if (! $pswd  || preg_match('/^\s*$/',$pswd) ) 
	      $pswd_error = '*';	
	if (! $pswd2 || preg_match('/^\s*$/',$pswd2) ) 
	      $pswd_error = '*';	
	if (! $first || preg_match('/^\s*$/',$first) )			 
	      $first_error = '*';
	if (! $last  || preg_match('/^\s*$/',$last) ) 
	      $last_error = '*';	
	if (! $addr  || preg_match('/^\s*$/',$addr) ) 
	      $addr_error = '*';

	if ($first_error || $first_error || $user_error || $pswd_error || $addr_error)
	    $msg  = 'Please enter required field(s) above!';     

	if ($pswd != $pswd2) {				
	    $pswd_error = '***';
	    $msg  = 'Password confirmation does not match password!';     
	}
    }

//=============================================================================
// Read data from the database
// if purpose is to check_unique user     --> validate user uniqueness
// if purpose is to repopulate the screen --> read all, and populate screen   
//=============================================================================
    function read_data($purpose)
    {
	global $host, $port, $DBname, $DBuser, $DBpswd;   
	global $mode, $cust_id, $user, $pswd, $pswd2, $first, $last, $addr, $phone, $msg;   
 
        $io = new DBio($host,$port,$DBname,$DBuser,$DBpswd);	#create a DBio object
    
	if ($purpose == 'check_unique')				#check unique user id				
	{
	    $query = "SELECT cust_id, user  
	              FROM customer 
	              WHERE user = '$user'";
	              
            $results = $io->process($query);			#retrieve the data from database		

	    if ($results[0])							#if customer exists
	        if ($results[0][cust_id] != $_SESSION[cust_id])			#but he is not the one 
	            $msg  = "User $user is already on file, please choose another";     	
	}

	if ($purpose == 'repopulate')				#client requesting profile update
	{
	    $query = "SELECT cust_id, user, pswd, fname, lname, address, phone  
	              FROM customer 
	              WHERE cust_id = $_SESSION[cust_id]";

            $results = $io->process($query);			#retrieve the data from database		
       
    	    $user    = $results[0]['user'];			#populate the screen									
	    $pswd    = $results[0]['pswd'];			#with data from database				
    	    $pswd2   = $results[0]['pswd'];
    	    $first   = $results[0]['fname']; 
    	    $last    = $results[0]['lname'];
    	    $phone   = $results[0]['phone'];
    	    $addr    = $results[0]['address'];
    	}
    }

//==============================================================================
// Display the HTML page  
// if there are errors, highlight those with an error message
//==============================================================================
    function display()
    {
	global $cust_id, $user, $pswd, $pswd2, $first, $last, $addr, $phone, $msg;   
	global $first_error,$last_error,$user_error,$pswd_error,$addr_error; 

	if (!$_SESSION[cust_id]) $button_name  = 'Register';	//if new registration  
	if ( $_SESSION[cust_id]) $button_name  = 'Update';	//if update profile    
	if (!$_SESSION[cust_id]) $del_disabled = 'disabled';	//if new registration  
?>
	<html>
	<head>
	<title>Process HTML form + write to database</title>
	<style>
	    a {text-decoration:none; color:brown}
	</style>
	</head>
	<body bgcolor=lightyellow>
	<h1><center>Registration Profile</center></h1>
	<form method=POST>
	<fieldset style="width:530;border-color:red">
	<legend align="left">User Registration Profile <?php print "[$_SESSION[cust_id]]"?></legend>
	<table>
	<tr><td>Enter a user id       
	    <td><input type=text     name=user  size=54 value=<?php print "$user  > $user_error " ?>
	<tr><td>Enter a password      
	    <td><input type=password name=pswd  size=20 value=<?php print "$pswd  >              "?>
	        Confirm                   
	        <input type=password name=pswd2 size=20 value=<?php print "$pswd2 >  $pswd_error "?>
	<tr><td>Enter first name      
	    <td><input type=text     name=first size=54 value=<?php print "$first >  $first_error"?>
	<tr><td>Enter last name       
	    <td><input type=text     name=last  size=54 value=<?php print "$last  >  $last_error "?>
	<tr><td>Enter your telephone  
	    <td><input type=text     name=phone size=54 value=<?php print "$phone >              "?>
	<tr><td>Enter your address    
	    <td><textarea name=addr cols=41, rows=4><?php print $addr?></textarea> <?php print $addr_error?>
	<tr><td><td><input type=submit name=update value=<?php print $button_name?> > 
	            <input type=submit name=delete value="Delete" <?php print $del_disabled?> > 
	</table>
	</fieldset>
	</form>
	<div id=msg style="color:red;"> <?php print $msg?>   </div>
<?php
    }

//=============================================================================
// Insert data in the database - for new registration
// retrieve the customer id PK generation by the auto_increment
// save session variables 
//=============================================================================
    function insert_data()
    {
	global $host, $port, $DBname, $DBuser, $DBpswd;   
	global $cust_id, $user, $pswd, $pswd2, $first, $last, $addr, $phone, $msg;   
 
        $user  = str_replace("<", "", $user);			#eliminate < (if any) 
        $pswd  = str_replace("<", "", $pswd);		
        $first = str_replace("<", "", $first);	
        $last  = str_replace("<", "", $last);		
        $addr  = str_replace("<", "", $addr);		
        $phone = str_replace("<", "", $phone);		

        $io = new DBio($host,$port,$DBname,$DBuser,$DBpswd);	#create a DBio object

	$insert = "INSERT INTO customer 
	           VALUES(0,'$user','$pswd','$first','$last','$addr','$phone')";

        $result = $io->process($insert);			#insert data into database		
            
        $select = "SELECT LAST_INSERT_ID() as id";		#retrieve cust_id PK 
       
        $results = $io->process($select);			#issue the query		
       
	$cust_id = $results[0][id];					

	$_SESSION[cust_id] = $cust_id;				#save session variable           
	$_SESSION[fname]   = $first;
	$_SESSION[lname]   = $last;
	$_SESSION[addr]    = $addr;

	$msg = 'Registration successful!';
    }

//=============================================================================
// Determine whether update or delete is requested
//=============================================================================
    function update_data()
    {
	if (! $_SESSION[cust_id]) return;

	if ($_POST[update])				#update button is pressed
	    update();

	if ($_POST[delete])				#delete button is pressed
	    delete();
    }

//=============================================================================
// Update data in the database - for profile update
//=============================================================================
    function update()
    {
	global $host, $port, $DBname, $DBuser, $DBpswd;   
	global $cust_id, $user, $pswd, $pswd2, $first, $last, $addr, $phone, $msg;   

        $user  = str_replace("<", "", $user);			#eliminate < (if any)  
        $pswd  = str_replace("<", "", $pswd);		
        $first = str_replace("<", "", $first);	
        $last  = str_replace("<", "", $last);		
        $addr  = str_replace("<", "", $addr);		
        $phone = str_replace("<", "", $phone);		

        $io = new DBio($host,$port,$DBname,$DBuser,$DBpswd);	#create a DBio object

	$update = "UPDATE customer
		     SET user    = '$user', 
		         pswd    = '$pswd', 
		         fname   = '$first', 
		         lname   = '$last', 
		         address = '$addr', 
		         phone   = '$phone'
		   WHERE cust_id = $_SESSION[cust_id]";	
		    
        $result = $io->process($update);			#update data in database		

	$msg = 'Your profile has been updated!';

	$_SESSION[fname] = $first;				#update session variables
	$_SESSION[lname] = $last;
	$_SESSION[addr]  = $addr;
    }

//=============================================================================
// Delete data from the database - profile delete
//=============================================================================
    function delete()
    {
	global $host, $port, $DBname, $DBuser, $DBpswd;   
	global $cust_id, $user, $pswd, $pswd2, $first, $last, $addr, $phone, $msg;   

        $io = new DBio($host,$port,$DBname,$DBuser,$DBpswd);	#create a DBio object

	$delete = "DELETE FROM customer
		   WHERE cust_id = $_SESSION[cust_id]";
	    
        $result = $io->process($delete);			#update data in database		

	$msg = 'Your profile has been deleted!';
	
    	$user =''; $pswd=''; $pswd2='';				#clear out the screen
    	$first=''; $last=''; $phone=''; $addr='';													

	unset($_SESSION[cust_id]);				#clear out session variable           
    }

//===============================================================================

?>

<hr/>
<center>
<a href=shop.php>       login    </a> |
                        register      | 
<a href=shopCart.php>   shop     </a> |
<a href=shop.php?out=y> logout   </a>
</center>

<?php include "../include.php"; ?>		<!-- hyperlink to see the code -->
</body>
</html>