<?php
//===============================================================================
// Update/delete an 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

    $order_id = $_GET['order'];                         //get the order_id to be updated
                                                        //passed from list or search screens

//  if (!$order_id)                                     //if none is passed                                     
//      header("Location: shopDBList.php?upd=y&".SID ); //redirect to the list screen
    
    $host      = "localhost";           //database connection info
    $DBname    = 'demo2';
    $DBuser    = 'demo2';
    $DBpswd    = 'demo2';

    if (!$_POST)                        //if first time around
        read_data();                    //populated the screen with data from DB

    if ($_POST['update'])               //if update button is pressed 
    {
        validate();     
        if ($msg == '')                 //if no errors
            update_data();
    }
    
    if ($_POST['delete'])               //if delete button is pressed 
    {
        delete_data();
    } 

    display();

//===============================================================================
// Read data from database and populate the screen 
// this is done only for first time around
//===============================================================================
    function read_data()
    {
        global $host, $DBname, $DBuser, $DBpswd;   
        global $order_id,$firstname,$lastname,$address,$flavor,$topping,$creditCard;   
 
        $connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname);   #connect to db server 
        if (! $connect) 
            die('Could not connect: ' . mysqli_connect_error());

        $query = "SELECT firstname,lastname,address,flavor,topping,creditCard,order_id 
                  FROM cust_order 
                  WHERE order_id = $order_id";                  
                  
        $cursor = mysqli_query($connect,$query);        #execute the query
        if (! $cursor) 
            die('Could not execute query: ' . mysqli_error($connect));
       
        $row = mysqli_fetch_array($cursor);

        $firstname  = $row['firstname'];                 
        $lastname   = $row['lastname'];
        $address    = $row['address'];
        $flavor     = $row['flavor'];                   
        $topping    = $row['topping'];                  
        $creditCard = $row['creditCard'];

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

//=============================================================================
// Validate all required input fields
//=============================================================================
    function validate()
    {
        global $order_id,$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 with data retrieved from database 
//==============================================================================
    function display()
    {
        global $order_id,$firstname,$lastname,$address,$flavor,$topping,$creditCard;   
        global $name_error,$addr_error,$flav_error,$top_error,$cc_error,$disable,$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 " <html> 
                <head>
                <title>Process HTML form + update database</title>
                <style>
                    a {text-decoration:none; color:brown}
                </style>
                </head>
                <body bgcolor=lightyellow>
                <h1><center>The Ice Cream Shop</center></h1>
                <h2>Welcome back $_SESSION[cust_fname]</h2>
                <form method=POST action=$_SERVER[PHP_SELF]?order=$order_id>                    
                <fieldset style='width:570px; border-color:red'>        
                <legend>Update/Delete order [$order_id] </legend>       
                <table> 
                <tr>    
                <td><b>Enter First Name <font color=red> $name_error </font>    
                <td><input type=text name=firstname value='$firstname'> 
                    <b>  Last Name </b>
                    <input type=text name=lastname value='$lastname'>   
                <tr>    
                <td><b>Enter Address <font color=red> $addr_error </font>       
                <td><textarea name=address rows=4 cols=47>$address</textarea>   
                <tr>    
                <td><b>Ice Cream Flavor <font color=red> $flav_error </font>    
                <td><select name='flavor[]' SIZE='4' multiple='multiple'>       
                        <option value='vanilla'        $vanl_selected> Vanilla       </option>
                        <option value='chocolate'      $choc_selected> Chocolate     </option>  
                        <option value='strawberry'     $strw_selected> Strawberry    </option>  
                        <option value='butter-pecan'   $butr_selected> Butter Pecan  </option>  
                        <option value='rocky-road'     $rock_selected> Rocky Road    </option>  
                        <option value='french-vanilla' $fren_selected> French Vanilla</option>  
                        <option value='pistachio'      $pist_selected> Pistachio     </option>  
                </select>       
                <tr>    
                <td><b>Select Topping <font color=red> $top_error </font>       
                <td>    
                <input type='checkbox' name='topping[]' value='hotFudge'     $hotF_checked/> Hot Fudge          
                <input type='checkbox' name='topping[]' value='sprinkles'    $sprk_checked/> Sprinkles          
                <input type='checkbox' name='topping[]' value='nuts'         $nuts_checked/> Nuts               
                <input type='checkbox' name='topping[]' value='whippedCream' $whip_checked/> Whipped Cream      
                <tr>    
                <td><b>Choose Credit Card <font color=red> $cc_error </font>    
                <td>    
                <input type=radio name=creditCard value='visa'      $visa_checked/> Visa        
                <input type=radio name=creditCard value='master-card' $mc_checked/> Master Card 
                <input type=radio name=creditCard value='amex'      $amex_checked/> Amex        
                <tr>    
                <td width=150>
                <input type=submit name=update value='Update' $disable> 
                <input type=submit name=delete value='Delete' $disable> 
                </table>        
                </fieldset>             
                <br><font color=red> $msg  </font> 
                <br/>   
                </form> ";
    }
    
//=============================================================================
// Update the order
//=============================================================================
    function update_data()
    {
        global $host, $DBname, $DBuser, $DBpswd;   
        global $order_id,$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 = "UPDATE cust_order
                   SET firstname  = '$firstname2', 
                       lastname   = '$lastname2', 
                       address    = '$address2', 
                       flavor     = '$flavor', 
                       topping    = '$topping', 
                       creditCard = '$creditCard'
                   WHERE order_id = $order_id";
                    
        $result = mysqli_query($connect,$update);                #issue the update                        
        if (! $result) 
            die('Could not execute update: ' . mysqli_error($connect));
       
        mysqli_close($connect);                                 #close connection

        $msg = 'Updated successfully!!!';
    }

//=============================================================================
// Delete the order

//=============================================================================
     function delete_data()
    {

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

        $update = "DELETE FROM cust_order
                   WHERE order_id = $order_id";
            
        $result = mysqli_query($connect,$update);                #issue the delete                        
        if (! $result) 
            die('Could not execute update: ' . mysqli_error($connect));
       
        mysqli_close($connect);                                 #close connection

        $msg = 'Deleted successfully!!!';

        $order_id  = '';

        $disable = 'disabled';                                  #disable buttons
}                                                               

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

?>

<hr/>
<center>
<base href=/~sultans/php/demo/5session/shop/ >
<a href=shopCart.php>   shop          </a> |
<a href=shopDBAdd.php>  checkout      </a> | 
<a href=shopDBList.php> list orders   </a> |
<a href=shopDBSrch.php> search        </a> |
                        update order       |
<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>