<?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)
//==================================================================================
    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);      //all error but warnigns & notices

//  include('io.inc');                          		           #function to perform DB input/output
    include('/home/sultans/web/php/demo/5session/shop/io.inc');    #make it so it works in the PHP*Tester

    $host      = "localhost";                   #database connection info
    $DBname    = 'demo2';
    $DBuser    = 'demo2';
    $DBpswd    = 'demo2';

    session_start();                            #get a handle to the session 
    
    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, $phone, $email, $addr, $msg;   
        global $user_error,$pswd_error,$first_error,$last_error,$email_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'];
        $email   = $_POST['email'];
        $addr    = $_POST['addr'];

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

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

        if ($pswd != $pswd2) {                          
            $pswd_error = '<font color=red>*</font>';
            $msg  = 'Password confirmation does not match password!';     
        }
    }

//=============================================================================
// Read data from the database
// if purpose is to ensure unique user    --> validate user uniqueness
// if purpose is to repopulate the screen --> read all, and populate screen   
//=============================================================================
    function read_data($purpose)
    {
        global $host, $DBname, $DBuser, $DBpswd;   
        global $mode, $cust_id, $user, $pswd, $pswd2, $first, $last, $phone, $email, $addr, $msg;   
 
        if ($purpose == 'check_unique')                 #check unique user id                           
        {
            $sql = "SELECT cust_id, user  
                    FROM customer 
                    WHERE user = '$user'";
                      
            $result = ioProcess($host,$DBname,$DBuser,$DBpswd,$sql);
            $row    = $result[0];                       #get first row

            if ($row && $row[cust_id] != $_SESSION[cust_id])
                $msg  = "User $user is already on file, please choose another";         
        }

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

            $result = ioProcess($host,$DBname,$DBuser,$DBpswd,$sql);
            $row    = $result[0];                       #get first row

            $user    = $row['user'];                    #populate the screen                                                                    
            $pswd    = $row['pswd'];                    #with data from database                                
            $pswd2   = $row['pswd'];
            $first   = $row['fname']; 
            $last    = $row['lname'];
            $phone   = $row['phone'];
            $email   = $row['email'];
            $addr    = $row['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, $phone, $email, $addr, $msg;   
        global $first_error,$last_error,$user_error,$pswd_error,$email_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:580;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 email  
            <td><input type=text     name=email size=54 value='<?php print "$email' > $email_error "?>
       <tr><td>Enter your address    
            <td><textarea name=addr cols=53, 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" 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, $DBname, $DBuser, $DBpswd;   
        global $cust_id, $user, $pswd, $pswd2, $first, $last, $phone, $email, $addr, $msg;   
 
        $connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname);   #connect to db server 
        if (! $connect) 
            die('Could not connect: ' . mysqli_connect_error());

        $user2  = htmlentities($user);                  #replace < > ' " & characters; 
        $pswd2  = htmlentities($pswd);                  #with their html entities;              
        $first2 = htmlentities($first);                 # < > ' "e; &        
        $last2  = htmlentities($last);          
        $phone2 = htmlentities($phone);         
        $email2 = htmlentities($email);         
        $addr2  = htmlentities($addr);          

        $user2  = mysqli_real_escape_string($connect,$user2);    #escape all ' " \ newline 
        $pswd2  = mysqli_real_escape_string($connect,$pswd2);    #with another \, making them
        $first2 = mysqli_real_escape_string($connect,$first2);   # \' \" \\ \newline
        $last2  = mysqli_real_escape_string($connect,$last2);   
        $phone2 = mysqli_real_escape_string($connect,$phone2);   
        $email2 = mysqli_real_escape_string($connect,$email2);   
        $addr2  = mysqli_real_escape_string($connect,$addr2);   

        $insert = "INSERT INTO customer 
                   VALUES(0,'$user2','$pswd2','$first2','$last2','$addr2','$email2','$phone2')";

        $result = mysqli_query($connect,$insert);                #issue the update                        
        if (! $result) 
            die('Could not execute insert: ' . mysqli_error($connect));
            
        $select = "SELECT LAST_INSERT_ID() as id";              #retrieve cust_id PK 
       
        $cursor = mysqli_query($connect,$select);               #issue the query                        
        if (! $cursor) 
            die('Could not execute query: ' . mysqli_error($connect));
       
        $row = mysqli_fetch_array($cursor);                     #get row as an array

        $cust_id = $row[id];                                    

        mysqli_free_result($cursor);                            #free result buffer
        mysqli_close($connect);                                 #close connection

        $_SESSION[cust_id]    = $cust_id;                       #save session variable           
        $_SESSION[cust_fname] = $first;

        $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, $DBname, $DBuser, $DBpswd;   
        global $cust_id, $user, $pswd, $pswd2, $first, $last, $phone, $email, $addr, $msg;   

        $user2  = htmlentities($user);                  #replace < > ' " & characters; 
        $pswd2  = htmlentities($pswd);                  #with their html entities;              
        $first2 = htmlentities($first);                 # < > ' "e; &        
        $last2  = htmlentities($last);          
        $phone2 = htmlentities($phone);         
        $email2 = htmlentities($email);          
        $addr2  = htmlentities($addr);          

        $user2  = addslashes($user2);                   #escape all ' " \ newline 
        $pswd2  = addslashes($pswd2);                   #with another \, making them
        $first2 = addslashes($first2);                  # \' \" \\ \newline
        $last2  = addslashes($last2);   
        $phone2 = addslashes($phone2);   
        $email2 = addslashes($email2);   
        $addr2  = addslashes($addr2);   
 
        $sql = "UPDATE customer
                   SET user    = '$user2', 
                       pswd    = '$pswd2', 
                       fname   = '$first2', 
                       lname   = '$last2', 
                       address = '$addr2', 
                       email   = '$email2'
                       phone   = '$phone2'
                 WHERE cust_id = $_SESSION[cust_id]";   
                    
        $result = ioProcess($host,$DBname,$DBuser,$DBpswd,$sql);

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

        $_SESSION[cust_fname] = $first;                         #update session variable
    }

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

        $sql = "DELETE FROM customer
                 WHERE cust_id = $_SESSION[cust_id]";
            
        $result = ioProcess($host,$DBname,$DBuser,$DBpswd,$sql);
       
        $msg = 'Your profile has been deleted!';
        
        $user =''; $pswd=''; $pswd2='';                         #clear out the screen
        $first=''; $last=''; $phone=''; $email=''; $addr='';                                                                                                       

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

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

?>

<hr/>
<center>
<base href=/~sultans/php/demo/5session/shop/ >
                        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>