<?php
//=============================================================================================
// This php scripts allows a customer to login. (It validates against (table: customer)
// if user logs in with proper user/pswd --> redirect to shopping page 
// if user clicks on register button     --> redirect to registration page
//=============================================================================================
    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);      //all error but warnigns & notices

    global $user, $pswd, $save;

    $user  = $_POST['user'];                    #get HTML form entry fields 
    $pswd  = $_POST['pswd'];
    $save  = $_POST['save'];

    if(! $user)
    {
        $user = $_COOKIE['cust_user'];          #check to see if userid was saved in cookie
        if ($user)
            $save = 'Y'; 
    }
    
    if ($_POST)                                 #if 2nd or subsequent time
    {                                           
        $_GET = '';                             #erase any $_GET variables 

        validate_form();                        #validate entry of user & pswd  

        if (! $msg)                             #if both user & pswd were entered 
            read_pswd();                        #read and validate user pswd 

        if (! $msg)                             #if pswd matches what was entered
        {
            session_start();                    #start a session
            $_SESSION[cust_id]    = $cust_id;   #save session variables
            $_SESSION[cust_fname] = $fname;

            $expire = time()+ 7*24*60*60;                  #today + 7 days 
            if ($save)
                setcookie('cust_user',$user,$expire,'/');  #save user cookie for 7 days
            if (! $save)
                setcookie('cust_user','',-99999,'/');      #delete the user cookie
             
            if (SID)                                       #must be using URL rewrite
                $sid = "?". SID;                           #append ? and the SID           

           header("Location: shopCart.php$sid");  
                                                    #redirect to shopCart.php, with session id (if any)
        }                                           #absolute to work in PHP*Tester
    }

    if ($_GET['out'])                               #if logout was requested
    {
        session_start();                            #obtain handle to the session
        session_destroy();                          #delete session
        if (! $save)
            setcookie('cust_user','',-99999,'/');   #delete the user cookie 

        $msg = 'You have logged out successfully';
    }
    
    display();                                  #display the web page

//=============================================================================
// Validate all required input fields
//=============================================================================
    function validate_form()
    {
        global $user, $pswd, $save, $msg;   

        if (! $user or ! $pswd) {
            $msg  = 'Please enter user id and password!';     
            return;
        }
}

//=============================================================================
// Read pswd from the database
// validates to make sure user exists, and pswd is validate for user
//=============================================================================
    function read_pswd()
    {
        global $cust_id, $user, $pswd, $fname, $lname, $addr, $msg;   

        $host      = "localhost";
        $DBname    = 'demo2';
        $DBuser    = 'demo2';
        $DBpswd    = 'demo2';
 
        $connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname);   #connect to db server
 
        if (! $connect) 
            die('Could not connect: ' . mysqli_connect_error());

        $query = "SELECT cust_id, pswd, fname, lname, address 
                  FROM customer 
                  WHERE lower(user) = '$user'";                 #not case sensitive

        $cursor = mysqli_query($connect,$query);                #execute the query                      

        if (! $cursor) 
            die('Could not execute query: ' . mysqli_error($connect));
       
        $row = mysqli_fetch_array($cursor);                     #get each row as an array

        if (! $row)
            $msg  = "User $user does not exist.  Please register first";        

        if ($row && $row[pswd] != $pswd)
            $msg  = "Password is invalid for $user";            

        $cust_id = $row[cust_id];                               
        $fname   = $row[fname];
        $lname   = $row[lname];
        $addr    = $row[address];

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

//==============================================================================
// Display the HTML page  
// if there are errors, display message
//==============================================================================
    function display()
    {
        global $user, $pswd, $save, $msg; 

        $checked = ($save) ? 'checked' : '';  
?>
        <html>
        <head>
        <title>Shop.com</title>
        <style>
            a {text-decoration:none; color:brown}
        </style>
        </head>

        <body bgcolor=lightyellow>
        <h1 align=center>Shop.Com</H1>

        <form method=POST action=shop.php>
        <fieldset style="width:350;border-color:red">
        <legend align="left">Sign In</legend>
        <table>
        <tr><td>Enter your user id       <td><input type=text     name=user value=<?php print $user?> >
        <tr><td>Enter your password      <td><input type=password name=pswd value=<?php print $pswd?> >
        <tr><td align=right>Save user id <td><input type=checkbox name=save value='y' <?php print $checked?> >
        <tr><td><td><input type=submit value="         Sign In       " > 
        </table>
        </fieldset>
        <br>
        <fieldset style="width:350;border-color:red">
        <legend align="center">Register</legend>
         <input type=button value="Register  " onClick="location.href='shopProf.php'">
        If first time user, please register
        <br><br>
        </fieldset>
        </form>
        <div style="color:red;"> <?php print $msg?>   </div>
<?php
    }
//=============================================================================
?>

<hr/>
<center>
<base href=/~sultans/php/demo/5session/shop/ >
<a href=shopProf.php>   register   </a> |
<a href=shop.php?out=y> logout     </a> |
<a href=..>             exit       </a> 
</center>

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