<?php
//==========================================================================================
// Shopping cart Object, to store and retrieve a shopping cart in 
//                       either a session variable, or in a database table
// the shoping cart name will be the same as the session variable name or the DB table name
// ** This shopping cart is object oriented
// author: Sam Sultan
//==========================================================================================
// Methods:
// --------
//   __construct(cartName,type,host,DBname,DBuser,DBpswd,PK) - constructor
//   viewCart()                               - retrieve cart content for display
//   addToCart(itemName,value1,...,value9)    - add an item to the cart
//   deleteFromCart(itemName)		      - detete an item from the cart
//   clearCart()                              - clear entire cart
//   getCart(),          getCartDB()	      - get shooping cart from session or database    
//   saveCart(cartData), saveCartDB(cartData) - save shopping cart to a session or database        
//   deleteCart(),       deleteCartDB()       - detete shopping cart
//   __toString()                             - a string representation of the cart
//===========================================================================================
    include_once('dbIOoo.inc');			//include the IO object

    session_start();				//start a session
    error_reporting(E_STRICT);			//do not show warnings
    
class Cart
{
    private $cartName;		//the name of the cart
    private $cartType;		//the type of cart = session or database
    private $host;		//server host  
    private $port;		//server port  
    private $DBname;		//database name
    private $DBuser;		//user id
    private $DBpswd;		//user pswd
    private $PK;		//customer id for customer who owns the cart
    private $cartData;		//the cart content as an associative array 				
				//[item1]==>(value1,value2,...), [item2]=>(value1,value2,...)
    
//-------------------------------------------------------------------------------
// Cart:     A Constructor to create a new shopping cart object 
//     args: cartName    - the name of the shopping cart
//           type        - session or database shopping cart
//           host,port   - server name and port number
//           DBname,DBuser,DBpswd - database credentials
//           PK          - the primary key of the customer   
//------------------------------------------------------------------------------- 
function __construct($cartName,$type,$host,$port,$DBname,$DBuser,$DBpswd,$PK)                               
{
    if (!$cartName)				//if no cart name
         $cartName = 'shopcart';		
    if (!$type)					//if no cart type 
         $type     = 'session';		

    $this->cartName  = $cartName;		//shopping cart name
    $this->type	     = $type;			//value = session or database      
    $this->host      = $host;		        //host info
    $this->port      = $port;		        //port info
    $this->DBname    = $DBname;			//database info  		
    $this->DBuser    = $DBuser;  		
    $this->DBpswd    = $DBpswd;  		
    $this->PK        = $PK;			//customer id (owner of shopping cart)  		
    $this->cartData  = array();  		//create associate array to hold cart items	
}
//------------------------------------------------------------------------------------------
// getters and setters
//     will be used if the properties are private
//------------------------------------------------------------------------------------------ 
function __get($name)			//will automatically be used if property is private
{
    return($this->$name);		//return the value of the property					
}

function __set($name, $value)		//will automatically be used if property is private
{
    if ($name == 'type')
        if ($value != 'session' && $value != 'database')		//validate attribute values
	    die("error - $name cannot be set. $value is invalid <br>");

    $this->$name = $value;		//set the value of the property
}   
//---------------------------------------------------------------------------------------------
// viewCart: retrieve a shopping cart for display
//     args: none 
//   return: none
//--------------------------------------------------------------------------------------------- 
function viewCart()
{
    $cartData = $this->getCart();   		//retrieve cart items 

    $this->cartData = $cartData;        	//save cart items in this object property
}
//---------------------------------------------------------------------------------------------
// addToCart: add an item to a shopping cart
//      args: itemName - the name of the item
//            value1   - the first value for the item
//            value2   - the second value for the item
//            valueX   - the third-nineth values for the item
//    return: none
//--------------------------------------------------------------------------------------------- 
function addToCart($itemName,$v1,$v2,$v3,$v4,$v5,$v6,$v7,$v8,$v9)
{
    $cartData = $this->getCart();   		//retrieve cart items 

    $values = array();				//create an index array
    if ($v1) $values[0] = $v1;			//if there is data store in array
    if ($v2) $values[1] = $v2;
    if ($v3) $values[2] = $v3;
    if ($v4) $values[3] = $v4;
    if ($v5) $values[4] = $v5;
    if ($v6) $values[5] = $v6;
    if ($v7) $values[6] = $v7;
    if ($v8) $values[7] = $v8;
    if ($v9) $values[8] = $v9;

    $cartData[$itemName] = $values;		//add or change a cart item

    $this->cartData = $cartData;        	//save cart items in this object property
    $this->saveCart();            		//save cart in DB or in session variable
}
//---------------------------------------------------------------------------------------------
// deleteFromCart: delete an item from a shopping cart
//           args: itemName - the name of the item
//         return: none
//--------------------------------------------------------------------------------------------- 
function deleteFromCart($itemName) {
 
    $cartData = $this->getCart();   		//retrieve cart items 

    foreach($cartData as $item=>$values) 	//loop thru all items in the cart
    {
        if ($item == $itemName)			//if the item is the one to delete
            unset($cartData[$item]);         	//delete the item from the cart
    }

    $this->cartData = $cartData;        	//save cart in this object property
    $this->saveCart();            		//save cart in DB or in session variable

    if (count($cartData) == 0) 			//if cart is empty
        $this->deleteCart();			//delete entire shopping cart
}
//---------------------------------------------------------------------------------------------
// clearCart: clear a cart, by simply calling deleteCart()
//      args: none 
//    return: none
//--------------------------------------------------------------------------------------------- 
function clearCart()
{
    $this->deleteCart();   			//delete cart items 
}
//------------------------------------------------------------------------------------------
// getCart: retrieve a shopping cart from either a session variable or a database table
//	    as a string format:  item1:value1,value2,...|item2:value1,value2,...| 
//          and build a cart associative array
//          in the format of:  [itemName] => values_array
//    args: none   
//  return: the content of the cart in an associtive array
//------------------------------------------------------------------------------------------- 
private function getCart() {                               

    if ($this->type == 'session')			//if cart type is session
        $cartString = $_SESSION[$this->cartName];	//get cart from session variable
    else						//otherwise
	$cartString = $this->getCartDB();    		//read cart from database

    $cartData   = array();				//associative array to contain the cart

    if ($cartString) 					//if there is content in cart
    {							//explode into associative array
        $itemValues = explode("|",$cartString);		//separate entire string on |
        for ($i=0; $i<count($itemValues)-1; $i++) 	//for as many pieces       
	{						//    except last piece which is '|'
            $itemValue = explode(":",$itemValues[$i]);	//separate each piece on :
            $item      = $itemValue[0];			//the item name
            $value     = $itemValue[1];			//all the values as a string
            $values    = explode(",",$value);		//split the string to an array
            $cartData[$item] = $values;			//store the array for each item
        }
    }
    return($cartData);	
}
//---------------------------------------------------------------------------------------
// getCartDB: get a shopping cart content from a database table
//      args: none
//    return: the shopping cart content as a string  
//            format: item1:value1,value2,...|item2:value1,value2,...|
//--------------------------------------------------------------------------------------- 
private function getCartDB() {                               

    $io = new DBio($this->host,$this->port,$this->DBname,$this->DBuser,$this->DBpswd);
    
    $sql = "select * from $this->cartName where owner = '$this->PK' ";

    $result = $io->process($sql);		//retrieve the data from database		

    $cartString = $result[0][content];		//row 0 column content

    return($cartString);
}
//--------------------------------------------------------------------------------------------------
// saveCart: flatten out an associative array shopping cart
//                  in the format: [itemName] => values_array
//                  and save in either a session variable or a database
//                  in the format: item1:value1,value2,...|item2:value1,value2,...| 
//     args: cartData - the shopping cart content as an associative array  
//   return: none    
//-------------------------------------------------------------------------------------------------- 
private function saveCart($cartData) {                               
         
    $cartString = '';    
    $cartData   = $this->cartData;
    
    foreach ($cartData as $item => $values) 		//for as many properties in array                                     
    {
        $value       = implode(',',$values);       	//flatten the array to a string
        $cartString .= $item . ":" . $value . "|";   	//append content to a string
    } 

    if ($this->type == 'session')			//if cart type is session
	$_SESSION[$this->cartName] = $cartString;	//save cart in session variable
    else						//otherwise
	$this->saveCartDB($cartString); 		//save cart in database
}
//---------------------------------------------------------------------------------------
// saveCartDB: save cart content in a database
//       args: cartString - the shopping cart content as a string  
//                          format: item1:value1,value2,...|item2:value1,value2,...|
//   return: none    
//--------------------------------------------------------------------------------------- 
private function saveCartDB($cartString) {                               

    $io = new DBio($this->host,$this->port,$this->DBname,$this->DBuser,$this->DBpswd);

    $sql = "replace into $this->cartName values('$this->PK', '$cartString') ";

    $result = $io->process($sql);	
}
//---------------------------------------------------------------------------------------------
// deleteCart: delete an entire shopping cart
//       args: none
//     return: none
//--------------------------------------------------------------------------------------------- 
private function deleteCart() {

    if ($this->type == 'session')			//if cart type is session
	unset($_SESSION[$this->cartName]);		//delete cart from session variable
    else						//otherwise
	$this->deleteCartDB();	 			//delete cart from database

    $this->cartName = '';				//clear name from the object
    $this->cartData = '';				//clear content from the object
}
//---------------------------------------------------------------------------------------
// deleteCartDB: delete a shopping cart from a database table
//         args: none
//       return: none
//--------------------------------------------------------------------------------------- 
private function deleteCartDB() {                               

    $io = new DBio($this->host,$this->port,$this->DBname,$this->DBuser,$this->DBpswd);
    
    $sql = "delete from $this->cartName where owner = '$this->PK' ";

    $result = $io->process($sql);	
}
//---------------------------------------------------------------------------------------------
// toString: return entire shopping cart as an HTML string
//     args: none
//   return: an HTML string representing entire shopping cart
//--------------------------------------------------------------------------------------------- 
function __toString() {

    $string = '';

    if ($this->cartData)
    {
    	$string .= "<table border=1 width=280> \n";
	$string .= "<tr><th colspan=2 bgcolor=gold>$this->cartName \n";			

        foreach ($this->cartData as $item=>$values) 	//for as many items in shopping cart       
	{
	    $valueStr = implode(', ', $values);		//string out the values array 
            $string     .= "<tr><th>$item<td>$valueStr \n";
	}
        $string .= "</table> \n";
    }
    return($string);
}
//-------------------------------------------------------------------------------------- 
}	//end of class - Do not delete this line
//-------------------------------------------------------------------------------------- 
?>