<?php
//===================================================================================
// This php script can handle an insert, an update and a delete of a shopping cart
// table: cust_cart
// if a session cart is not present --> must be a new cart  
// if a session cart is present     --> must be an update (update/delete) of cart
//===================================================================================
    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);      //all error but warnigns & notices

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

    session_start();                                    #get a handle to the session 
    
    if (! $_SESSION['cust_id'])                         //if there is no session for customer                           
        header("Location: shop.php");                   //redirect to login page
        
    if (! $_POST)                                       #if first time
        read_data();                                    #read cart data from database        

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

        if (! $msg)
        {
            if (! $_SESSION['cart_id'])                 #if cart does not exist 
                insert_data();       
            elseif ($_POST[update])                     #if cart exists and update button pressed
                update_data();       
            elseif ($_POST[delete])                     #if cart exists and delete button pressed
                delete_data();       
        }
    }
    
    display();                                          #display the screen 

//=============================================================================
// Read cart data from the database
//=============================================================================
    function read_data()
    {
        global $host, $DBname, $DBuser, $DBpswd;   
        global $mode, $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());

        $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

        if (! $row)
            $msg = 'Your shopping cart is empty';
 
        mysqli_free_result($cursor);                            #free result buffer
        mysqli_close($connect);                                 #close connection

        $cart_id = $row['cart_id'];                             #populate the screen                                                                    
        $flavor  = $row['flavor'];                              #with data from database                                
        $topping = $row['topping'];
        
        $_SESSION['cart_id'] = $cart_id;                        #save cart_id in session variable
    }

//=============================================================================
// Validate all required input fields
//=============================================================================
    function validate()
    {
        global $cust_id, $cart_id, $flavor, $topping, $msg;   

        $flavor  = $_POST['ice'];                       //get HTML form entry data                                      
        $topping = $_POST['top'];

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

        if (! $flavor || ! $topping)                    //if nothing was chosen
            $msg = 'Please choose flavor(s) and topping(s) ';
    }


//==============================================================================
// Display the HTML page  
//==============================================================================
    function display()
    {
        global $cust_id, $cart_id, $flavor, $topping, $msg;   

        if (strpos($flavor,'vanilla')        !== false)  $vanl_checked = 'CHECKED';
        if (strpos($flavor,'chocolate')      !== false)  $choc_checked = 'CHECKED';
        if (strpos($flavor,'strawberry')     !== false)  $strw_checked = 'CHECKED';
        if (strpos($flavor,'butter-pecan')   !== false)  $butr_checked = 'CHECKED';
        if (strpos($flavor,'rocky-road')     !== false)  $rock_checked = 'CHECKED';
        if (strpos($flavor,'french-vanilla') !== false)  $fren_checked = 'CHECKED';
        if (strpos($flavor,'pistachio')      !== false)  $pist_checked = 'CHECKED';

        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';
        
        if (! $_SESSION['cart_id'])						#if no cart_id session variable
            $disabled = 'disabled';						#disable 'clear cart' button

        print "
                <html>
                <head>
                <title>Add to Shopping Cart</title>
                <style>
                    a    {text-decoration:none; color:brown}
                    td   {font-weight:bold}
                    td i {font-weight:normal}
                </style>
                </head>
                <body bgcolor=lightyellow>
                <h1 align=center>The Ice Cream Shop</h1>
                <h2>$_SESSION[cust_fname], your shopping cart includes...</h2>         
                <form method=post name=frm>
                <fieldset style='width:800;border-color:red'>
                <legend> Flavors </legend>
                <table width=800>
                <tr><td width=33%><input type=checkbox name=ice[] value=vanilla        $vanl_checked> Vanilla
                    <td width=33%><input type=checkbox name=ice[] value=chocolate      $choc_checked> Chocolate
                    <td width=33%><input type=checkbox name=ice[] value=strawberry     $strw_checked> Strawberry
                <tr><td>          <input type=checkbox name=ice[] value=butter-pecan   $butr_checked> Butter Pecan
                    <td>          <input type=checkbox name=ice[] value=rocky-road     $rock_checked> Rocky Road
                    <td>          <input type=checkbox name=ice[] value=french-vanilla $fren_checked> French Vanilla
                <tr><td>          <input type=checkbox name=ice[] value=pistachio      $pist_checked> Pistachio
                    <td>          <input type=checkbox name=ice[] value=chocolate-chip     disabled > Chocolate Chip   <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=cookie-cream       disabled > Cookies 'n Cream <i>(out of stock)
                <tr><td>          <input type=checkbox name=ice[] value=pralines           disabled > Pralines         <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=double-chocolate   disabled > Double Chocolate <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=chocolate-fudge    disabled > Chocolate Fudge  <i>(out of stock)
                <tr><td>          <input type=checkbox name=ice[] value=coffee             disabled > Coffee           <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=jamoca             disabled > Jamoca           <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=cherries-jubilee   disabled > Cherries Jubilee <i>(out of stock)
                <tr><td>          <input type=checkbox name=ice[] value=almond-fudge       disabled > Almond Fudge     <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=peanut-butter      disabled > Peanut Butter    <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=nutty-coconut      disabled > Nutty Coconut    <i>(out of stock)
                <tr><td>          <input type=checkbox name=ice[] value=orange-sherbet     disabled > Orange Sherbet   <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=lemon-sherbet      disabled > lemon Sherbet    <i>(out of stock)
                    <td>          <input type=checkbox name=ice[] value=rainbow-sherbet    disabled > Rainbow Sherbet  <i>(out of stock)
                </table>
                </fieldset>
                <br><br>
                <fieldset style='width:800;border-color:red'>
                <legend> Topping </legend>
                <table width=800>
                <tr><td width=33%><input type=checkbox name=top[] value=hotFudge     $hotF_checked> Hot Fudge
                    <td width=33%><input type=checkbox name=top[] value=sprinkles    $sprk_checked> Sprinkles
                    <td width=33%><input type=checkbox name=top[] value=nuts         $nuts_checked> Nuts
                <tr><td>          <input type=checkbox name=top[] value=whippedCream $whip_checked> Whipped Cream
                    <td>          <input type=checkbox name=top[] value=almonds          disabled > Almonds      <i>(out of stock)
                    <td>          <input type=checkbox name=top[] value=cherry           disabled > Cherry       <i>(out of stock)
                </table>
                </fieldset>
                <br><font color=red> $msg   </font>
                <br><br>
                <input type=submit name=update value='Add to Cart' onClick='return pre_validate()'>
                <input type=submit name=delete value='Clear Cart'  $disabled >
                <input type=button name=order  value='Checkout'    onClick=location.href='shopDBAdd.php?".SID."'>
                </form>

                <script>
                function pre_validate()                                 //--- optional JavaScript validation 
                {
                    chosen = '';                                        //--- validate entry of flavors
                    for (i = 0; i < document.frm.elements.length; i++)
                    {
                        name    = document.frm.elements[i].name;
                        value   = document.frm.elements[i].value;
                        checked = document.frm.elements[i].checked; 

                        if (name == 'ice[]' && checked)
                            chosen += value + ' ';
                    }
                    if (chosen == '')                                   //--- if nothing was chosen
                    {
                        alert('Please choose one or more ice cream flavors !!!');
                        return false;
                    }
                }
                </script>
        ";
}

//=============================================================================
// Insert data in the database - for new cart
//=============================================================================
    function insert_data()
    {

        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());

        $insert = "INSERT INTO cust_cart 
                   VALUES(0,'$flavor','$topping',$_SESSION[cust_id])";

        $result = mysqli_query($connect,$insert);                #issue the query                        
        if (! $result) 
            die('Could not execute insert: ' . mysqli_error($connect));
            
        $select = "SELECT LAST_INSERT_ID() as id";              #retrieve cart_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 first row as an array
        $cart_id = $row[id];                                    

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

        $msg = 'Item(s) added to your cart!';

        $_SESSION['cart_id'] = $cart_id;                        #save cart_id in session variable
    }

//=============================================================================
// Update cart data in the database 
//=============================================================================
    function update_data()
    {
        global $host_port, $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());

        $update = "UPDATE cust_cart
                     SET flavor  = '$flavor', 
                         topping = '$topping' 
                   WHERE cart_id = $_SESSION[cart_id]";    
                    
        $result = mysqli_query($connect,$update);                #issue the query                        
        if (! $result) 
            die('Could not execute update: ' . mysqli_error($connect));
       
        mysqli_close($connect);                                 #close connection

        $msg = 'Your cart has been updated!';
     }

//=============================================================================
// Delete cart data from the database
// this function uses the older ext/mysql instead of the mysqli
//=============================================================================
    function delete_data()
    {
        global $host_port, $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 execute update: ' . mysqli_error($connect));
       
        mysqli_close($connect);                                 #close connection

        $msg = 'Your cart has been cleared!';
                
        $flavor  ='';                                           #clear out the screen
        $topping = '';
        
        unset($_SESSION['cart_id']);                            #delete cart_id from session variable                                                                                                  
    }

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

?>

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