<?php
//==================================================================================================
// Add an order to the database
// Name & address are passed to this script via session variables (from login, table: customer)
// Ice cream flavors & toppings are passed  via session variables (from shop,  table: cust_cart)
// Add to table: cust_order
//==================================================================================================
    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);      //all error but warnigns & notices

    session_start();                            //get a handle to session

    if (! $_SESSION['cust_id'])                 //if there is no session for customer                           
        header("Location: shop.php");           //redirect to login page

    if (! $_SESSION['cart_id'])                 //if there is no cart for customer                           
        header("Location: shopCart.php");       //redirect to shopping page

    $host      = "localhost";                   //database connection info
    $DBname    = 'demo2';
    $DBuser    = 'demo2';
    $DBpswd    = 'demo2';
?>

<html>
<head>
<title>Process HTML form + write to database</title>
<style>
a {text-decoration:none; color:brown}
</style>
</head>
<body bgcolor=lightyellow>
<h1><center>The Ice Cream Shop</center></h1>

<?php

    if (!$_POST)                                #if first time around
        read_data();        					#populate screen from database

    if ($_POST)                                 #if subsequent time
    {                                           
        validate();     

        if ($msg == '')                         #if no errors
        {
            write_data();                       #insert a new order
            delete_cart();                      #delete shopping cart
        }
    }
    
    display();

//=============================================================================
// Validate all required input fields
//=============================================================================
    function validate()
    {
        global $firstname, $lastname, $address, $flavor, $topping, $creditCard;   
        global $name_error,$addr_error,$flav_error,$top_error,$cc_error,$msg;   

        $firstname  = $_POST['firstname'];              #get HTML form entry fields 
        $lastname   = $_POST['lastname'];
        $address    = $_POST['address'];
        $flavor     = $_POST['flavor'];                 #select list --> array
        $topping    = $_POST['topping'];                #checkboxes --> array
        $creditCard = $_POST['creditCard'];

        $msg;
        $name_error;
        $addr_error;
        $flav_error;
        $top_error;
        $cc_error;

        if (is_array($flavor))                          
            $flavor  = implode(',' , $flavor);          #flatten out the array          
        if (is_array($topping))                         
            $topping = implode(',' , $topping);         #flatten out the array          

        if ($firstname == '' or $lastname == '') {
            $msg        = 'error';     
            $name_error = '*';
        }
        if ($address == '') {
            $msg        = 'error';     
            $addr_error = '*';
        }
        if ($flavor == '') {
            $msg        = 'error';     
            $flav_error = '*';
        }
        if ($topping == '') {
            $msg       = 'error';     
            $top_error = '*';
        }
        if ($creditCard[0] == '') {
            $msg      = 'error';     
            $cc_error = '*';
        }
        if ($msg == 'error')
            $msg  = 'Please enter required field(s) above!';     
    }

//==============================================================================
// Display the HTML page
// repopulate the screen with previous entry data  
// if there are errors, highlight those with an error message
//==============================================================================
    function display()
    {
        global $firstname, $lastname, $address, $flavor, $topping, $creditCard;   
        global $name_error,$addr_error,$flav_error,$top_error,$cc_error,$msg;   

        if ($creditCard == 'visa')        $visa_checked  = 'CHECKED';
        if ($creditCard == 'master-card') $mc_checked    = 'CHECKED';
        if ($creditCard == 'amex')        $amex_checked  = 'CHECKED';

        if (strpos($flavor,'vanilla')        !== false)  $vanl_selected = 'SELECTED';
        if (strpos($flavor,'chocolate')      !== false)  $choc_selected = 'SELECTED';
        if (strpos($flavor,'strawberry')     !== false)  $strw_selected = 'SELECTED';
        if (strpos($flavor,'butter-pecan')   !== false)  $butr_selected = 'SELECTED';
        if (strpos($flavor,'rocky-road')     !== false)  $rock_selected = 'SELECTED';
        if (strpos($flavor,'french-vanilla') !== false)  $fren_selected = 'SELECTED';
        if (strpos($flavor,'pistachio')      !== false)  $pist_selected = 'SELECTED';

        if (strpos($topping,'hotFudge')      !== false)  $hotF_checked = 'CHECKED';
        if (strpos($topping,'sprinkles')     !== false)  $sprk_checked = 'CHECKED';
        if (strpos($topping,'nuts')          !== false)  $nuts_checked = 'CHECKED';
        if (strpos($topping,'whippedCream')  !== false)  $whip_checked = 'CHECKED';

        print "<h2>$_SESSION[cust_fname] complete your order below</h2>";
        print "<form method=POST action=$_SERVER[PHP_SELF]> \n";                          
        print "<fieldset style='width:560px;border-color:red'> \n";
        print "<legend>Enter Fields Below</legend> \n";
        print "<table> \n";
        print "<tr>";
        print "<td><b>Enter First Name <font color=red> $name_error </font>";
        print "<td><input type=text size=15 name=firstname value='$firstname'> \n";
        print "    <b>  Last Name </b>";
        print "    <input type=text size=15 name=lastname value='$lastname'>   \n";
        print "<tr>";
        print "<td><b>Enter Address <font color=red> $addr_error </font>";
        print "<td><textarea name=address rows=4 cols=50>$address</textarea> \n";
        print "<tr>";
        print "<td><b>Ice Cream Flavor <font color=red> $flav_error </font> \n";
        print "<td><select name='flavor[]' SIZE='4' multiple='multiple'>    \n";
        print "    <option value='vanilla'        $vanl_selected> Vanilla</option>        \n";
        print "    <option value='chocolate'      $choc_selected> Chocolate</option>      \n";
        print "    <option value='strawberry'     $strw_selected> Strawberry</option>     \n";
        print "    <option value='butter-pecan'   $butr_selected> Butter Pecan</option>   \n";
        print "    <option value='rocky-road'     $rock_selected> Rocky Road</option>     \n";
        print "    <option value='french-vanilla' $fren_selected> French Vanilla</option> \n";
        print "    <option value='pistachio'      $pist_selected> Pistachio</option>      \n";
        print "</select> \n";
        print "<tr>";
        print "<td><b>Select Topping <font color=red> $top_error </font> \n";
        print "<td>";
        print "<input type='checkbox' name='topping[]' value='hotFudge'     $hotF_checked/> Hot Fudge     \n";
        print "<input type='checkbox' name='topping[]' value='sprinkles'    $sprk_checked/> Sprinkles     \n";
        print "<input type='checkbox' name='topping[]' value='nuts'         $nuts_checked/> Nuts          \n";
        print "<input type='checkbox' name='topping[]' value='whippedCream' $whip_checked/> Whipped Cream \n";
        print "<tr>";
        print "<td><b>Choose Credit Card <font color=red> $cc_error </font> \n";
        print "<td>";
        print "<input type=radio name=creditCard value='visa'      $visa_checked/> Visa        \n";
        print "<input type=radio name=creditCard value='master-card' $mc_checked/> Master Card \n";
        print "<input type=radio name=creditCard value='amex'      $amex_checked/> Amex        \n";
        print "<tr>";
        print "<td width=150>";
        print "<input type=submit value='   Place Order   '>";
        print "<td><input type=reset value=Cancel>        \n";
        print "</table>    \n";
        print "</fieldset> \n";
        print "<br><font color=red> $msg  </font>";
        print "<br/>";
        print "</form> \n";
    }

//=============================================================================
// Read cart data from the database
//=============================================================================
    function read_data()
    {
        global $host, $DBname, $DBuser, $DBpswd;   
        global $firstname, $lastname, $address, $cart_id, $flavor, $topping, $msg;   
 
        $connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname);   #connect to db server
 
        if (! $connect) 
            die('Could not connect: ' . mysqli_connect_error());

        $query = "SELECT cust_id, fname, lname, address  
                  FROM customer
                  WHERE cust_id = $_SESSION[cust_id]";

        $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

		$firstname = $row['fname'];  
		$lastname  = $row['lname'];  
		$address   = $row['address'];  
 
        $query = "SELECT cart_id, flavor, topping, cust_id 
                  FROM cust_cart
                  WHERE cust_id = $_SESSION[cust_id]";

        $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

		$flavor  = $row['flavor'];  
		$topping = $row['topping'];  
   
        mysqli_free_result($cursor);                            #free result buffer
        mysqli_close($connect);                                 #close connection
    }
    
//=============================================================================
// Write data - insert a new order in the database
//=============================================================================
    function write_data()
    {
        global $host, $DBname, $DBuser, $DBpswd;   
        global $firstname, $lastname, $address, $flavor, $topping, $creditCard, $msg;   
 
        $connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname);   #connect to db server 
        if (! $connect) 
            die('Could not connect: ' . mysqli_connect_error());

        $firstname2 = htmlentities($firstname);                 #replace < > ' " & characters;
        $lastname2  = htmlentities($lastname);                  #with their html entities;
        $address2   = htmlentities($address );                  # < > ' "e; &

        $firstname2 = mysqli_real_escape_string($connect,$firstname2);  #escape all ' " \ newline 
        $lastname2  = mysqli_real_escape_string($connect,$lastname2);   #with another \, making them
        $address2   = mysqli_real_escape_string($connect,$address2);    # \' \" \\ \newline

        $update = "INSERT INTO cust_order 
                   VALUES(0,'$firstname2','$lastname2','$address2',
                            '$flavor', '$topping', '$creditCard', $_SESSION[cust_id])";

        $result = mysqli_query($connect,$update);                #issue the update                        

        if (! $result) 
            die('Could not execute insert: ' . mysqli_error($connect));
       
        mysqli_close($connect);                                 #close connection

        $msg = 'Order processed successfully!!!';
    }

//=============================================================================
// Delete data from the database
//=============================================================================
    function delete_cart()
    {
        global $host, $DBname, $DBuser, $DBpswd;   
        global $cust_id, $cart_id, $flavor, $topping, $msg;   

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

        $delete = "DELETE FROM cust_cart
                   WHERE cart_id = $_SESSION[cart_id]";
            
        $result = mysqli_query($connect,$delete);                #issue the delete                        
        if (! $result) 
            die('Could not delete cart: ' . mysqli_error($connect));
       
        mysqli_close($connect);                                 #close connection

        $msg = 'Order processed successfully!!!';
                
        $flavor  ='';                                           #clear out the screen
        $topping = '';                                                                                                  

        unset($_SESSION[cart_id]);                              #delete cart_id session variable           
    }

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

?>

<hr/>
<center>
<base href=/~sultans/php/demo/5session/shop/ >
<a href=shopCart.php>   shop         </a> |
                        checkout          | 
<a href=shopDBList.php> list orders  </a> |
<a href=shopDBSrch.php> search       </a> |
                        update order </a> |
<a href=shopProf.php>   profile      </a> |
<a href=shop.php?out=y> logout       </a>
</center>

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