<?

/*/
	oCart.phi © 2003-2004 WindshieldsToGo  /  (c) 2000 Ying Zhang (ying@zippydesign.com)
	TERMS OF USAGE:
		This file was written and developed by Ying Zhang (ying@zippydesign.com) for educational and demonstration purposes only.  You are hereby granted the rights to use,
		modify, and redistribute this file as you like.  The only requirement is that you must retain this notice, without modifications, at the top of your source code. No warranties
		or guarantees are expressed or implied. DO NOT use this code in a production environment without understanding the limitations and weaknesses pretaining to or caused
		by the use of these scripts, directly or indirectly. USE AT YOUR OWN RISK!
	MODIFICATION HISTORY:
		· 11/1/2003 - OmniOp - utilized getProdPrice()
		· 7/21/2004 - Nathan - code cleanup
		· 7/22/2004 - Nathan - modified the cart pricing & subtotal calculations
/*/

class Cart {


	var $items;  // array of items
	var $total;  // total of the cart
	var $subTotal;  // total of the cart
	var $tax = 0;  // tax from the cart
	var $discount;  // cart discount
	var $state;  // state for tax calculation
	var $shipping;  // Used for returning shiping cost
	var $orderType;  // Install or Glass-only
	var $devBypass;  // special bypass of the isDev autofill feature


//-------------------------------------------------------------------------
// constructor
//-------------------------------------------------------------------------
function Cart() {
	$this->init();
} // Cart()


//-------------------------------------------------------------------------
// init:  Called to initialize (and/or reset) a shopping cart.
//-------------------------------------------------------------------------
function init() {
	$this->items = array();
	$this->total = 0;
	$this->orderType = "";
} // init()


//-------------------------------------------------------------------------
// add:  Adds an item to the shopping cart and update the total price. "Hardware" allows the hasClips specifier.
//-------------------------------------------------------------------------
function add( &$productID, $qty, $code, $opt, $itemPrice=-.01, $hardware="", $bypassAutofill=false ) {

	//error_reporting(E_ALL);
	
	//added temp 1 item only
	if( $this->itemcount() <= 1 ) $this->init();
	if( isset($productID) ) {
		setdefault( $productID, 0 );
		/*
		if( isset($this->items[$productID]) ) {
			$qty_prev = $this->items[$productID]['QTY'];
			if( $qty_prev > 0 ) $qty += $qty_prev;
		}
		*/
		$qty = 1;  // [OmniOp] make sure the QTY never exeeds 1 for windshields
		$this->items[$productID] = array('QTY' => $qty, 'CODE' => $code, 'OPT' => $opt, 'PRICE' => $itemPrice, 'HARDWARE' => $hardware );
	}
	if( $opt=="install" ) {
		$this->orderType = "Installation";
	} else if( $opt=="molding" ) {
		$this->orderType = "Glass with molding";
	} else {
		$this->orderType = "Glass-only";
	}
	$this->devBypass = $bypassAutofill;

} // add()


//-------------------------------------------------------------------------
// set:  Update the quantity of a product in the cart to a specified value.
//-------------------------------------------------------------------------
function set(&$productID, $qty) {
	if( isset($productID) ) $this->items[$productID]['QTY'] = (int) $qty;
}


//-------------------------------------------------------------------------
// remove:  This function will remove a given product from the cart
//-------------------------------------------------------------------------
function remove(&$productID) {
	if( isset($productID) ) unset($this->items[$productID]);
}


//-------------------------------------------------------------------------
// this function will clean up the cart, removing items with invalid product id's (non-numeric ones) and products with quantities less than 1
//-------------------------------------------------------------------------
function cleanup() {

	foreach ($this->items as $productID => $v) {
		foreach ($this->items[$productID] as $key => $value) {
			if ($this->items[$productID]['QTY'] < 1) {
				unset($this->items[$productID]);
			}
		}
	}

} // cleanup()


//-------------------------------------------------------------------------
// itemcount:  Returns the number of individual items in the shopping cart (note, this takes into account the quantities of the items as well)
//-------------------------------------------------------------------------
function itemcount() {

	$count = 0;
	foreach( $this->items as $productID => $v ) {
		foreach( $this->items[$productID] as $key => $qty ) {
			if( $key == "QTY" ) {
				$count += $qty;
			}
		}
	}

	return $count;

} // itemcount()


//-------------------------------------------------------------------------
// return a comma delimited list of all the products in the cart, this will be used for queries, eg. SELECT id, price FROM products WHERE id IN ....
//-------------------------------------------------------------------------
function get_productid_list() {

	$productid_list = "";
	foreach ($this->items as $productID => $qty) {
		$productid_list .= ",'" . $productID . "'";
	}
	return substr($productid_list, 1);  // strip off the leading comma

} // get_productid_list()


//-------------------------------------------------------------------------
// recalculate the total for the shopping cart, we will also do some cleanup and remove invalid items from the cart.  we have to query the database to get the prices, so instead
// of making one query for each product in the basket, we will gather up all the ID's we are interested in and run one query to get all the products we care about (using $in_clause)
//-------------------------------------------------------------------------
function recalc_total() {

	global $CFG;
	$this->subTotal = 0;

	/// the new price location...
	foreach( $this->items as $productID => $rInfo ) {
		$this->subTotal += $rInfo['QTY'] * $rInfo['PRICE'];
	}
	$this->setSubTotal();
	$this->setTotal();

} // recalc_total()


///-------------------------------------------------------------------------
function setTax() {

	global $CFG, $g_oAffiliate, $isReferral;
	
	$this->tax = 0;
	$bInState = strpos(strtolower($_SESSION['order']->b_State), strtolower($CFG->taxState));
	if( !isset($isReferral) ) $isReferral = false;
	if( ($g_oAffiliate->isW2G || $isReferral) && $bInState >= 0 ) {
		/// Beau doesn't use this yet !
		//$this->state = "ca";
		//$this->tax = sprintf( "%.2f", $this->subTotal * $CFG->tax);
		$this->tax = 0;
	} elseif( $g_oAffiliate->settings['tax'] > 0 ) {
		$this->tax = $g_oAffiliate->settings['tax'] * $this->subTotal;
	}

} // setTax()


///-------------------------------------------------------------------------
function setTotal() {
	$this->total = sprintf( "%.2f", $this->subTotal + $this->tax + $this->shipping );
}


///-------------------------------------------------------------------------
function setSubTotal() {
	$this->subTotal = sprintf( "%.2f", $this->subTotal);	
}


///-------------------------------------------------------------------------
function setShipping(){
	global $CFG, $_SESSION;
	$this->shipping = sprintf( "%.2f", $_SESSION['order']->shipping);
}


///-------------------------------------------------------------------------
function getShipping(){
	$this->setShipping();
	return sprintf( "%.2f", $this->shipping);
}	


///-------------------------------------------------------------------------
function getTax() {
	$this->setTax();
	return $this->tax;
}


///-------------------------------------------------------------------------
function getTotal() {
	$this->setTotal();
	return $this->total;
}


///-------------------------------------------------------------------------
function getSubTotal() {
	$this->setSubTotal();
	return $this->subTotal;	
}

///-------------------------------------------------------------------------
function setAll() {
	$this->setShipping();
	$this->setSubTotal();
	$this->setTotal();
}


///-------------------------------------------------------------------------
function showNumbers() {

	global $CFG;

	echo "<pre>";
	echo "Total : " . $this->total . "\n\n";
	echo "Sub Total : " . $this->subTotal . "\n\n";
	echo "Tax : " . $this->tax . "\n\n";
	echo"</pre>";

} // showNumbers()


//-------------------------------------------------------------------------
// getCartItems:  Return a $qid of all the items in the shopping cart.
//-------------------------------------------------------------------------
function getCartItems() {

	$bDebug = false;
	$inClause = $this->get_productid_list();
	if( $bDebug ) echo "INCLAUSE: ".$inClause."<br>";
	if( empty($inClause) ) {
		return;
	}
	$newInClause = ""; 
	$theProdID = explode(",", $inClause);
	$theProdID = str_replace("'", "", $theProdID);
	$count = count($theProdID);

	for( $c=0; $c<$count; $c++ ) {
		if( $bDebug ) echo "FOR C: $c<br>";
		if( !empty($this->items[$theProdID[$c]]['CODE']) ) {
			$p = getProdPrice($theProdID[$c]);
			if ($this->items[$theProdID[$c]]['OPT'] == "install") {
				$cart[$c]['price'] = sprintf("%.2f", $p->iPrice);
			} elseif ($this->items[$theProdID[$c]]['OPT'] == "molding") {
				$cart[$c]['price'] = sprintf("%.2f", $p->mPrice); //!!!
			} else {
				$cart[$c]['price'] = sprintf("%.2f", $p->price);
			}
			$cart[$c]['id']    = $p->id;
			$cart[$c]['make']  = $p->make;
			$cart[$c]['model'] = $p->model;
			$cart[$c]['style'] = $p->style;
			$cart[$c]['year']  = $p->year;
		} else {
			$newInClause .= ",'" . $theProdID[$c] . "'";
		}
	}

	if( $newInClause != "" ) {
		if( $bDebug ) echo "NEWINCLAUSE<br>";
		$newInClause = substr($newInClause, 1);  // strip off leading comma
		$c = (count($cart) -1);
		$hData = db_query("SELECT ID, make, model, style, year, price FROM product WHERE ID IN (" .$newInClause.")");
		while( $pr = mysql_fetch_object($hData) ) {
				$cart[$c]['price'] = $pr->price;
				$cart[$c]['id']    = $pr->ID;
				$cart[$c]['make']  = $pr->make;
				$cart[$c]['model'] = $pr->model;
				$cart[$c]['style'] = $pr->style;
				$cart[$c]['year']  = $pr->year;			
			$c++;
		}
	}
	if( $bDebug ) echo "<hr noshade color=#980000>";
	return $cart;

} // getCartItems()


} // class: Cart


?>