<?php

    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);      //all error but warnigns & notices

    $userCookie = $_COOKIE['userName'];                 //obtain user cookie

    if (! $userCookie)                                                      //if no username cookie
        header('Location: /~sultans/php/demo/5session/cookieLogin.php');    //redirect to login page

    if ($_POST['add'])                      //if add button is pressed
        add_to_cart();

    if ($_POST['view'])                     //if view button is pressed
        view_cart();

    display();
    
//===========================================================================================
// Add item to a shopping cart 
//===========================================================================================
function add_to_cart()
{
	global $html;

	$newItem  = $_POST['item'];                 //get all form fields
    $newValue = $_POST['value'];

	if (! $newItem)  return;                    //if none is given, return
	if (! $newValue) $newValue = 1;             //if none is given, set to 1

    $cart = get_cart('myCart');                 //get the cart from a cookie

	$cart[$newItem] = $newValue;                //add the newest item to cart    

    $expiration = time() + 7 * 24*60*60;        //7 days from now 

    set_cart($cart,'myCart',$expiration);       //save the cart in a cookie 

    $html = "<b>$newValue $newItem </b>have been added to your shopping cart";	
}

//===========================================================================================
// Display entire shopping cart 
//===========================================================================================
function view_cart()
{
	global $html;

    $cart = get_cart('myCart');				    //get the cart from a cookie

	$html  = "<table border=2 bgcolor=f0f0f0> \n";
	$html .= "<tr bgcolor=cyan><th><i>Item Name<th><i>Quantity</th> \n";

	foreach ($cart as $itemName => $itemValue)                  //for every item in the cart
    	    $html .= "<tr><td>$itemName <td>$itemValue \n";     //print the item name and value

	$html .= "<tr><td colspan=2 bgcolor=cyan><b>". count($cart) ."</b> items in cart";
	$html .= "</table>";
}

//===========================================================================================
// Get shopping cart from a cookie and build/return a cart object 
//===========================================================================================
function get_cart($cartName)
{
    $cart = Array();                            //empty cart object					

    $cart_string = $_COOKIE[$cartName];         //get shopping cart from the cooklie    
    $cart_array  = explode('|',$cart_string);   //split string cart on |

    foreach ($cart_array as $item)              //for every item in the cart array
    {
        $item = explode(':',$item);             //split each item on :
    	$itemName  = $item[0];
    	$itemValue = $item[1];

        if ($itemName)                          //if there is an item
    	    $cart[$itemName] = $itemValue;      //add it with its value to the cart object
    }    

    return($cart);					//return the shopping cart object
}	

//===========================================================================================
// Take a shopping cart object and store it in a cookie
//===========================================================================================
function set_cart($cart,$cartName,$expiration)
{
    foreach ($cart as $itemName => $itemValue)              //for every item in the cart
    {
        $cart_array[$i++] = $itemName .':'. $itemValue;     //join each item name/value with :
    }    

    $cart_string = implode('|',$cart_array);                //join all items with | 

    setcookie($cartName, $cart_string, $expiration, '/');   //save the cart in a cookie 
}	

//===========================================================================================
function display()
{
	global $html;
?>
	<html>
	<head>
	<title>Cookie Check</title>
	</head>

	<body bgcolor=lightyellow>
	<h1 align=center>Welcome to our Store <?php echo $_COOKIE['userName']?></h1>
	<h3>We Sell...</h3>
	<table cellpadding=2>
	<tr bgcolor=cccccc><td>Apples<td>Pears<td>Oranges<td>Grapes<td>Strawberries<td>Bananas<td>Apricots<td>Peaches</tr> 
	<tr bgcolor=cccccc><td>Tables<td>Chairs<td>Lamps<td>Desks<td>Wall Units<td>Chests<td>Sofas<td>Beds</tr>
	<tr bgcolor=cccccc><td>TVs<td>DVDs<td>iPhones<td>iPods<td>Computers<td>Monitors<td>Printers<td>Scanners</tr>
	</table>
	And much much more...
	<h3>Add any item to your shopping cart</h3>
	<form method=post name=frm action=<?php echo $_SERVER['PHP_SELF'] ?> >
	<table>
	<tr><td>Enter item to your cart<td> <input type=text name=item>
	<tr><td>Enter quantity<td><input type=text name=value>
	</table>
	<br>
	<input type=submit name=add  value="Add to Cart">
	<input type=submit name=view value="View Cart">
	</form>
	<hr>
<?php
	print $html;
}
?>

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