<?php
/*
  osCommerce, Open Source E-Commerce Solutions 
http://www.oscommerce.com 

Copyright (c) 2003 osCommerce 

osCommRes, Services Oline 
http://www.oscommres.com 
Copyright (c) 2005 osCommRes 

Freeway eCommerce 
http://www.zac-ware.com/freeway 
Copyright (c) 2007 ZacWare 

Released under the GNU General Public License
*/ 

// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();


class shoppingCart {
	var $contents, $total, $weight, $cartID, $content_type,$mode,$messageStack;

	function shoppingCart() {
		$this->reset();
	}
	function restore_contents() { 
		//ICW replace line
		global $customer_id, $gv_id, $REMOTE_ADDR;
		$bol_insert=false;
		if (!tep_session_is_registered('customer_id')) return false;
		// insert current cart contents in database
		if (is_array($this->contents)) {
			reset($this->contents);
			
			while (list($products_id, ) = each($this->contents)) {
				
				$qty = $this->contents[$products_id]['qty'];
				// if element is event omit 'E' in products id
				$element_id=$products_id;
				
				if ($this->contents[$products_id]['element_type']=='E' || $this->contents[$products_id]['element_type']=='S') $element_id=substr($products_id,1);
				
				$product_query = tep_db_query("select products_id from " . TABLE_CUSTOMERS_BASKET . " where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($element_id) . "' and products_type='".$this->contents[$products_id]['element_type']."'");
 
 				if (tep_db_num_rows($product_query)<=0) {
				
					tep_db_query("delete from " .TABLE_CUSTOMERS_TEMP_BASKET ." where products_id='".tep_db_input($element_id)."' and products_type='".$this->contents[$products_id]['element_type']."' and customers_id='".tep_session_id()."'"); 
					if($this->contents[$products_id]['subscription_start_date']=="")$this->contents[$products_id]['subscription_start_date']='0000-00-00';
					if($this->contents[$products_id]['old_orders_id']=="")$this->contents[$products_id]['old_orders_id']=0;
					if($qty=="")$qty=0;
					if($this->contents[$products_id]['old_orders_id']=="")$this->contents[$products_id]['old_orders_id']=0;
					tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added, products_type,old_orders_id,answer_type,answer_value,forced_id,subscription_start_date,discount_id) values ('" . (int)$customer_id . "', '" . tep_db_input($element_id) . "', '" . $qty . "',now(),'" . $this->contents[$products_id]['element_type'] . 
									"','" . tep_db_input($this->contents[$products_id]['old_orders_id']) . "','" . tep_db_input($this->contents[$products_id]['answer_type']) . "','" . tep_db_input($this->contents[$products_id]['answer_value']) . "','" . tep_db_input($this->contents[$products_id]['forced_item_ids']) . "','" . tep_db_input($this->contents[$products_id]['subscription_start_date']) . "'," . (int)$this->contents[$products_id]['discount_id'] . ")");
					if (isset($this->contents[$products_id]['attributes'])) {
						tep_db_query("delete from " .TABLE_CUSTOMERS_TEMP_BASKET_ATTRIBUTES ." where products_id='".tep_db_input($element_id)."' and customers_id='".tep_session_id()."'"); 
						reset($this->contents[$products_id]['attributes']);
						while (list($option, $value) = each($this->contents[$products_id]['attributes'])) {
							tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " (customers_id, products_id, products_options_id, products_options_value_id) values ('" . (int)$customer_id . "', '" . tep_db_input($element_id) . "', '" . (int)$option . "', '" . (int)$value . "')");
						}
					}
					if ($this->contents[$products_id]['element_type']=='E'){
						$sessions=&$this->contents[$products_id]['sessions'];
						tep_db_query("delete from " .TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS ." where products_id='".tep_db_input($element_id)."' and customers_id='".tep_session_id()."'"); 
						reset($sessions);
						while(list($id,)=each($sessions)){
							tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_SESSIONS ." (customers_id, products_id, session_id, session_type, session_group,session_date) values('" . (int)$customer_id . "','" . $element_id . "','" . $id . "','" . $sessions[$id]['type'] . "','" . $sessions[$id]['group'] . "','" . $sessions[$id]['date'] . "')");
						}
					}
						if ($this->contents[$products_id]['element_type']=='V'){
						$others=&$this->contents[$products_id]['others'];
						tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_SERVICES . " (customers_id,products_id,start_date,end_date,start_time,end_time,resource_id) values(" . (int)$customer_id . ",'" . $element_id . "','" . tep_db_input($others["start_date"]) . "','" . tep_db_input($others["end_date"]) . "','" . tep_db_input($others["start_time"]) . "','" . tep_db_input($others["end_time"]) ."','".tep_db_input($others["resource_id"])."')");
					}
				} else {
					tep_db_query("delete from " .TABLE_CUSTOMERS_TEMP_BASKET ." where products_id='".tep_db_input($element_id)."' and products_type='".$this->contents[$products_id]['element_type']."' and customers_id='".tep_session_id()."'"); 
					if ($this->contents[$products_id]['element_type']=='P'){
						if($qty=="")$qty=0;
						tep_db_query("update " . TABLE_CUSTOMERS_BASKET . " set customers_basket_quantity = '" . $qty . "',discount_id='" . (int)$this->contents[$products_id]['discount_id'] . "' where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($element_id) . "'");
					} else if ($this->contents[$products_id]['element_type']=='E') {
						$sessions=&$this->contents[$products_id]['sessions'];
						reset($sessions);
						while(list($id,)=each($sessions)){
							$session_query=tep_db_query("SELECT session_id from " . TABLE_CUSTOMERS_BASKET_SESSIONS . " where session_id='" . $id . "' and products_id='" . $element_id . "' and customers_id='" . (int)$customer_id . "'");
							if (!tep_db_num_rows($session_query)){
								tep_db_query("delete from ".TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS ." where session_id='".$id ."' and products_id='".$element_id ."' and customers_id='".tep_session_id()."'") ;
								tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_SESSIONS ." (customers_id, products_id, session_id, session_type, session_group,session_date) values('" . (int)$customer_id . "','" . $element_id . "','" . $id . "','" . $sessions[$id]['type'] . "','" . $sessions[$id]['group'] . "','" . $sessions[$id]['date'] . "')");
							}
						}
					} else if ($this->contents[$products_id]['element_type']=='V') {
						$others=&$this->contents[$products_id]["others"];
						if($qty=="")$qty=0;
						tep_db_query("update " . TABLE_CUSTOMERS_BASKET . " set customers_basket_quantity = '" . $qty . "' where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($element_id) . "'");
						tep_db_query("update " . TABLE_CUSTOMERS_BASKET_SERVICES . " set start_date = '" . tep_db_input($others["start_date"]) . "',end_date = '" . tep_db_input($others["end_date"]) . "',start_time='" . tep_db_input($others["start_time"]) . "',end_time='" . tep_db_input($others["end_time"]) . "',resource_id='".tep_db_input($others["resource_id"])."' where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($element_id) . "'");
					}
				}
				if ($this->contents[$products_id]['element_type']=='E' && $this->contents[$products_id]['qty']>1 && !$bol_insert){
					$this->save_attendees();
					$bol_insert=true;
				}
        	}
			//ICW ADDDED FOR CREDIT CLASS GV - START
			if (tep_session_is_registered('gv_id')) {
				$gv_query = tep_db_query("insert into  " . TABLE_COUPON_REDEEM_TRACK . " (coupon_id, customer_id, redeem_date, redeem_ip) values ('" . $gv_id . "', '" . (int)$customer_id . "', now(),'" . $REMOTE_ADDR . "')");
				$gv_update = tep_db_query("update " . TABLE_COUPONS . " set coupon_active = 'N' where coupon_id = '" . $gv_id . "'");
				tep_gv_account_update($customer_id, $gv_id);
				tep_session_unregister('gv_id');
			}
			//ICW ADDDED FOR CREDIT CLASS GV - END
		}

		// reset per-session cart contents, but not the database contents
		$this->reset(false);
		$bol_taken=false;
		$products_query = tep_db_query("select products_id,customers_basket_quantity,products_type,old_orders_id,answer_type,answer_value,forced_id,discount_id from " . TABLE_CUSTOMERS_BASKET . " where customers_id = '" . (int)$customer_id . "'");
		while ($products = tep_db_fetch_array($products_query)) {
			if ($products['products_type']=='E'){
				$products_id='E' . $products['products_id'];
				if ($products["customers_basket_quantity"]>1) {
					if (!$bol_taken) {
						$this->get_attendees();
						$bol_taken=true;
					}
					$this->multiple_event_attendees+=1;
				}
			} else if ($products['products_type']=='S') {
				$products_id='S' . $products['products_id'];
			} else {
				$products_id=$products['products_id'];
			}
			
			//echo $products_id;
			$this->contents[$products_id] = array('qty' => $products['customers_basket_quantity'],'element_type'=>$products['products_type'],'old_orders_id'=>$products['old_orders_id'],'answer_type'=>$products['answer_type'],'answer_value'=>$products['answer_value'],'sessions'=>array(),'forced_item_ids'=>$products['forced_id'],'discount_id'=>$products['discount_id']);
			if ($products['products_type']=='E'){
				$session_query=tep_db_query("SELECT session_id,session_type,session_group,session_date from " . TABLE_CUSTOMERS_BASKET_SESSIONS . " where customers_id='" . (int)$customer_id . "' and products_id='" . (int)$products["products_id"] . "' order by session_date");
				while($result=tep_db_fetch_array($session_query)){
					$this->contents[$products_id]['sessions'][$result["session_id"]]=array(	'type'=>$result["session_type"],
																							'group'=>$result["session_group"],
																							'date'=>$result["session_date"],
																							'fees'=>0
													 										);
				}
			}	if ($products['products_type']=='V'){
				$service_query=tep_db_query("SELECT start_date,end_date,start_time,end_time,resource_id from " . TABLE_CUSTOMERS_BASKET_SERVICES . " where customers_id='" . (int)$customer_id . "' and products_id='" . tep_db_input($products['products_id']) ."'");
				$service_result=tep_db_fetch_array($service_query);
				$this->contents[$products_id]['others']=$service_result;
				if($this->contents[$products_id]['others']['resource_id']){
					 $resource_price=get_details('resource_costs',TABLE_SERVICE_RESOURCE,'resource_id='.$this->contents[$products_id]['others']['resource_id']);	
					 $this->contents[$products_id]['others']['resource_costs']=$resource_price[0]['resource_costs'];
				}
			}
			$attributes_query = tep_db_query("select products_options_id, products_options_value_id from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($products['products_id']) . "'");
			while ($attributes = tep_db_fetch_array($attributes_query)) {
				$this->contents[$products['products_id']]['attributes'][$attributes['products_options_id']] = $attributes['products_options_value_id'];
			}
		}

		$this->cleanup();
    }

	function reset($reset_database = false) {
		global $customer_id;
		$this->contents = array();
		$this->total = 0;
		$this->weight = 0;
		$this->content_type = false;
		if (tep_session_is_registered('customer_id') && ($reset_database == true)) {
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET . " where customers_id = '" . (int)$customer_id . "'");
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where customers_id = '" . (int)$customer_id . "'");
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_SESSIONS . " where customers_id ='". (int)$customer_id . "'");
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_SERVICES . " where customers_id ='". (int)$customer_id . "'");
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTENDEES . " where customers_id ='". (int)$customer_id . "'");
		} else if (!tep_session_is_registered('customer_id') && ($reset_database == true)) {
			tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET . " where customers_id = '" . tep_session_id() . "'");
			tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET_ATTRIBUTES . " where customers_id = '" . tep_session_id() . "'");
			tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS . " where customers_id ='". tep_session_id() . "'");
		} 

		$this->multiple_event_attendees=0;
		//unset($this->attendees);
		unset($this->cartID);
		if (tep_session_is_registered('cartID')) tep_session_unregister('cartID');
	}

  function add_cart($products_id, $qty = '1', $attributes = '', $notify = true,$sessions=array(),$old_orders_id=0,$salemaker_id=0) {
  global $new_products_id_in_cart, $customer_id;
  
  $products_id_string = tep_get_uprid($products_id, $attributes);
  $products_id = tep_get_prid($products_id_string);

	$attributes_pass_check = true;
	if (is_array($attributes)) {  
		reset($attributes);  
		while (list($option, $value) = each($attributes)) {  
			if (!is_numeric($option) || !is_numeric($value)) {  
				$attributes_pass_check = false;  
				break;           
			}
		}  
	} 
  if (is_numeric($products_id) && is_numeric($qty) && ($attributes_pass_check == true)) {
    $check_product_query = tep_db_query("select products_status,product_type,products_price_break from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");//Support Packs
    $check_product = tep_db_fetch_array($check_product_query);
    if (($check_product !== false) && ($check_product['products_status'] == '1')) {
      if ($notify == true) {
        $new_products_id_in_cart = $products_id;
        tep_session_register('new_products_id_in_cart');
      }
	  	// get the forced ids from the xsell_products
		$xsell_query=tep_db_query("select xsell_id  from " . TABLE_PRODUCTS_XSELL . " where products_id='" . $products_id . "' and item_type='P' and xsell_type='F'");
		$forced_ids="";
		if (tep_db_num_rows($xsell_query)){
			while($xsell_result=tep_db_fetch_array($xsell_query)){
				$forced_ids=$xsell_result["xsell_id"] . ",";
			}
			$forced_ids=substr($forced_ids,0,-1);
		}
 
	  // get the cross product_ids
      if ($this->in_cart($products_id_string)) {
        //$this->update_quantity($products_id_string, $qty, $attributes,array());
		
		if(($check_product['products_price_break']=='Y') || (($check_product['products_price_break']=='N') && $check_product['product_type']!='S'))//Support Packs 
			$this->update_quantity($products_id_string, $qty, $attributes,array(),0,$forced_ids,$salemaker_id);
      } else {
        //$this->contents[$products_id_string] = array('qty' => $qty,'element_type'=>'P','sessions'=>array(),'old_orders_id'=>0,'answer_type'=>'','answer_value'=>'')
		$this->contents[$products_id_string] = array('qty' => $qty,'element_type'=>'P','sessions'=>array(),'old_orders_id'=>0,'answer_type'=>'','answer_value'=>'','forced_item_ids'=>$forced_ids,'discount_id'=>$salemaker_id);
       
// insert into database
		if($qty=="")$qty=0;
		if($old_orders_id=="")$old_orders_id=0;
		
        if (tep_session_is_registered('customer_id')) 
			tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id,forced_id,discount_id) values ('" . (int)$customer_id . "', '" . tep_db_input($products_id_string) . "', '" . (int)$qty . "', now(),'P', '" . $old_orders_id ."','". $forced_ids ."'," . $salemaker_id . ")");
		else
			tep_db_query("insert into " . TABLE_CUSTOMERS_TEMP_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id,forced_id) values ('" . tep_session_id() . "', '" . tep_db_input($products_id_string) . "', '" . (int)$qty . "', now(),'P', '" . $old_orders_id ."','". $forced_ids ."')");
			
        if (is_array($attributes)) {
          reset($attributes);
          while (list($option, $value) = each($attributes)) {
            $this->contents[$products_id_string]['attributes'][$option] = $value;
// insert into database
            if (tep_session_is_registered('customer_id'))
				 tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " (customers_id, products_id, products_options_id, products_options_value_id) values ('" . (int)$customer_id . "', '" . tep_db_input($products_id_string) . "', '" . (int)$option . "', '" . (int)$value . "')");
			else
				 tep_db_query("insert into " . TABLE_CUSTOMERS_TEMP_BASKET_ATTRIBUTES . " (customers_id, products_id, products_options_id, products_options_value_id) values ('" . tep_session_id() . "', '" . tep_db_input($products_id_string) . "', '" . (int)$option . "', '" . (int)$value . "')");
          }
        }
      }
 
      $this->cleanup();
 
// assign a temporary unique ID to the order contents to prevent hack attempts during the checkout procedure
      $this->cartID = $this->generate_cart_id();
	  
    }
  }
  
}

// function to add subscription to cart
function add_cart_subscription($subscription_id, $qty = '1', $attributes = '', $notify = true,$sessions=array(),$old_orders_id=0,$subscription_start_date='0000-00-00') {
  global $customer_id;
  $p_id = tep_get_prid($products_id_string);

 	$products_id="S" . $subscription_id;
	
    $check_subscription_query = tep_db_query("select subscription_status from " . TABLE_SUBSCRIPTIONS . " where subscription_id = '" . (int)$subscription_id . "'");
    $check_subscription = tep_db_fetch_array($check_subscription_query);
	
    if (($check_subscription !== false) && ($check_subscription['subscription_status'] == '1')) {
 
 	  	// get the forced ids from the xsell_subscriptions
		$xsell_query=tep_db_query("select xsell_id  from " . TABLE_PRODUCTS_XSELL . " where products_id='" . $subscription_id . "' and item_type='S' and xsell_type='F'");
		$forced_ids="";
		if (tep_db_num_rows($xsell_query)){
			while($xsell_result=tep_db_fetch_array($xsell_query)){
				$forced_ids=$xsell_result["xsell_id"] . ",";
			}
			$forced_ids=substr($forced_ids,0,-1);
		}
      if (!$this->in_cart($products_id)) {
        $this->contents[$products_id] = array('qty' => $qty,'element_type'=>'S','sessions'=>array(),'old_orders_id'=>0,'answer_type'=>'','answer_value'=>'','forced_item_ids'=>$forced_ids,'subscription_start_date'=> $subscription_start_date);
		if($subscription_start_date=="")$subscription_start_date='0000-00-00';
// insert into database
		if($qty=="")$qty=0;
        if (tep_session_is_registered('customer_id')) 
			tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id,forced_id,subscription_start_date) values ('" . (int)$customer_id . "', '" . tep_db_input($subscription_id) . "', '" . (int)$qty . "', now(),'S', '0','" . $forced_ids . "','" . $subscription_start_date . "')");
		else
			tep_db_query("insert into " . TABLE_CUSTOMERS_TEMP_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id,forced_id,subscription_start_date) values ('" . tep_session_id() . "', '" . tep_db_input($subscription_id) . "', '" . (int)$qty . "', now(),'S', '0','" . $forced_ids . "','" . $subscription_start_date . "')");
      }
 
      $this->cleanup();
 
// assign a temporary unique ID to the order contents to prevent hack attempts during the checkout procedure
      $this->cartID = $this->generate_cart_id();
    }
	
}

//function to add service to cart
function add_cart_service($service_id, $qty = '1', $attributes = '', $notify = true,$others="") {
  global $new_products_id_in_cart, $customer_id;
  $res=array(); 
  $resource_id=(($others["resource_id"])?$res[1]=$others["resource_id"]:$res[1]=0);
  //$service_id_string = tep_get_service_uprid($service_id,$res);
  $service_id_string = tep_get_service_uprid($service_id,$attributes);
  if(tep_db_input($others["start_date"])) $start_date_string=strtotime(tep_db_input($others["start_date"]));
  if(tep_db_input($others["start_time"])) $start_time_string=strtotime(tep_db_input($others["start_time"]));
  if(tep_db_input($others["end_date"])) $end_date_string=strtotime(tep_db_input($others["end_date"]));
  if(tep_db_input($others["end_time"])) $end_time_string=strtotime(tep_db_input($others["end_time"]));
  $time_string=$start_date_string+$end_date_string+$start_time_string+$end_time_string;
  $service_id_string.="-".$time_string;
  if($others["resource_id"]) $service_id_string.='-'.$others["resource_id"];
  //$service_id = tep_get_service_prid($service_id_string); 
  //echo $service_id .'-'.$qty.'-'.$service_id_string;
  if (is_numeric($service_id) && is_numeric($qty)) { 
    $check_service_query = tep_db_query("select service_status from " . TABLE_SERVICES . " where service_id = '" . (int)$service_id . "'");
    $check_service = tep_db_fetch_array($check_service_query);
	if (($check_service !== false) && ($check_service['service_status'] == '1')) {
      if ($notify == true) {
        $new_products_id_in_cart = $service_id;
        tep_session_register('new_session_id_in_cart');
      }
 	  if ($this->in_cart($service_id_string)) {	 		 
	  	//$this->update_quantity($service_id_string, $qty, $attributes,array(),0,$forced_ids);
	  	$this->contents[$service_id_string]['qty']=$qty;
		$this->contents[$service_id_string]['others']=$others;
		if (is_array($attributes)) {
          reset($attributes);
          while (list($option, $value) = each($attributes)) {
            $this->contents[$service_id_string]['attributes'][$option] = $value;
          }
		}
		if (tep_session_is_registered('customer_id')) {
			tep_db_query("update " . TABLE_CUSTOMERS_BASKET_SERVICES . " set start_date = '" . tep_db_input($others["start_date"]) . "',end_date = '" . tep_db_input($others["end_date"]) . "',start_time='" . tep_db_input($others["start_time"]) . "',end_time='" . tep_db_input($others["end_time"]) . "',resource_id='". tep_db_input($others["resource_id"])."' where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($service_id_string) . "'");
			tep_db_query("update " . TABLE_CUSTOMERS_BASKET . " set customers_id='".(int)$customer_id."', products_id='".tep_db_input($service_id_string)."', customers_basket_quantity='".(int)$qty."', customers_basket_date_added=now(),products_type='V',old_orders_id='".(int)$old_orders_id."' where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($service_id_string) . "'");
		}else tep_db_query("update " . TABLE_CUSTOMERS_TEMP_BASKET. " set customers_id='".tep_session_id()."', products_id='".tep_db_input($service_id_string)."', customers_basket_quantity='".(int)$qty."', customers_basket_date_added=now(),products_type='V',old_orders_id='".(int)$old_orders_id."' where products_id = '" . tep_db_input($service_id_string) . "'");
      } else {
      
      $this->contents[$service_id_string] = array('qty' => $qty,'element_type'=>'V','sessions'=>array(),'old_orders_id'=>0,'answer_type'=>'','answer_value'=>'','others'=>$others);
	  // insert into database
	  if($qty=="")$qty=0;
	  if($old_orders_id=="")$old_orders_id=0;
      if (tep_session_is_registered('customer_id')) tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id) values ('" . (int)$customer_id . "', '" . tep_db_input($service_id_string) . "', '" . (int)$qty . "', now(),'V', '" . (int)$old_orders_id . "')");
 	  else tep_db_query("insert into " . TABLE_CUSTOMERS_TEMP_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id) values ('" . tep_session_id() . "', '" . tep_db_input($service_id_string) . "', '" . (int)$qty . "', now(),'V', '" . (int)$old_orders_id . "')");
      if (is_array($attributes)) {
          reset($attributes);
          while (list($option, $value) = each($attributes)) {
            $this->contents[$service_id_string]['attributes'][$option] = $value;
      // insert into database
            if (tep_session_is_registered('customer_id')) tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " (customers_id, products_id, products_options_id, products_options_value_id,products_type) values ('" . (int)$customer_id . "', '" . tep_db_input($service_id_string) . "', '" . (int)$option . "', '" . (int)$value . "','V')");
          }
        }
		 if (tep_session_is_registered('customer_id')) {
		 	tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_SERVICES . "(customers_id,products_id,start_date,end_date,start_time,end_time,resource_id) values (" . (int)$customer_id . ",'" . $service_id_string . "','" . $others["start_date"] . "','"  . $others["end_date"] . "','" . $others["start_time"] . "','" . $others["end_time"] . "','".$others["resource_id"]."')");
		 } 
      }
      $this->cleanup();
 
// assign a temporary unique ID to the order contents to prevent hack attempts during the checkout procedure
      $this->cartID = $this->generate_cart_id();
    }
  }
  
}


	//updated function to add event to cart

	function add_cart_event($events_id, $sessions=array(),$old_orders_id,$answer_type,$answer_value,$no_attendees) {
		global $new_products_id_in_cart, $customer_id;
		//$qty=sizeof($sessions);
		//add 'E' to id to avoid conflict with products
		$products_id='E' . $events_id;

		if ($this->in_cart($products_id)){
			$this->check_sessions($products_id,$sessions);
			ksort($this->contents[$products_id]['sessions']);
			$this->contents[$products_id]['answer_type']=$answer_type;
			$this->contents[$products_id]['answer_value']=$answer_value;
			//update question answer value
			if (tep_session_is_registered('customer_id')){
				tep_db_query("UPDATE " . TABLE_CUSTOMERS_BASKET . " set answer_value='" . tep_db_input($answer_value) . "' where customers_id='" . (int)$customer_id . "' and products_id='" . (int)$events_id . "'");
				tep_db_query("DELETE from " . TABLE_CUSTOMERS_BASKET_SESSIONS . " where customers_id='" . (int)$customer_id . "' and products_id='" . (int)$events_id . "'");
			} else 	{
				tep_db_query("UPDATE " . TABLE_CUSTOMERS_TEMP_BASKET . " set answer_value='" . tep_db_input($answer_value) . "' where customers_id='" . tep_session_id() . "' and products_id='" . (int)$events_id . "'");
				tep_db_query("DELETE from " . TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS . " where customers_id='" . tep_session_id() . "' and products_id='" . (int)$events_id . "'");
			}
		} else {
			$this->contents[$products_id] = array(
													'qty' =>$no_attendees,
													'element_type'=>'E',
													'sessions'=>$sessions,
													'old_orders_id'=>$old_orders_id,
													'answer_type'=>$answer_type,
													'answer_value'=>$answer_value,
													);
			if (tep_session_is_registered('customer_id')){
				//add to cart
				if($no_attendees=="")$no_attendees=0;
				if($old_orders_id=="")$old_orders_id=0;
				tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id,answer_type,answer_value) values ('" . (int)$customer_id . "', '" . tep_db_input($events_id) . "', '" . $no_attendees . "', now(),'E','" . 
						$old_orders_id . "','" . $answer_type . "','" . $answer_value . "')");
			}else {
				tep_db_query("insert into " . TABLE_CUSTOMERS_TEMP_BASKET . " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id,answer_type,answer_value) values ('" . tep_session_id() . "', '" . tep_db_input($events_id) . "', '" . $no_attendees . "', now(),'E','" . 
						$old_orders_id . "','" . $answer_type . "','" . $answer_value . "')");
			}
			if ($no_attendees>1){
				$this->multiple_event_attendees+=1;
			}
		}
		//add to sessios_cart
		if (tep_session_is_registered('customer_id')){
			reset($this->contents[$products_id]['sessions']);
			$temp=&$this->contents[$products_id]['sessions'];
			while(list($id,)=each($temp)){
				tep_db_query("insert into " . TABLE_CUSTOMERS_BASKET_SESSIONS . " (customers_id,products_id,session_id,session_type,session_group,session_date) values ('" . $customer_id . "','" . $events_id . "','" . $id . "','" . $temp[$id]['type'] . "','" . $temp[$id]['group'] . "','" . $temp[$id]['date'] . "')");
			}
		}
		else {
			reset($this->contents[$products_id]['sessions']);
			$temp=&$this->contents[$products_id]['sessions'];
			while(list($id,)=each($temp)){
				tep_db_query("insert into " . TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS . " (customers_id,products_id,session_id,session_type,session_group,session_date) values ('" . tep_session_id() . "','" . $events_id . "','" . $id . "','" . $temp[$id]['type'] . "','" . $temp[$id]['group'] . "','" . $temp[$id]['date'] . "')");
			}
		}
		
		$this->cleanup();
		// assign a temporary unique ID to the order contents to prevent hack attempts during the checkout procedure
		$this->cartID = $this->generate_cart_id();
	
	}    

	function check_sessions($products_id,$new_sessions){
		$sessions=&$this->contents[$products_id]['sessions'];
	
		reset($new_sessions);
		while(list($id,)=each($new_sessions)){
			if (!isset($sessions[$id])) $sessions[$id]=$new_sessions[$id];
		}
		//$this->contents[$products_id]['qty']=sizeof($sessions);
	}

	function update_quantity($products_id, $quantity = '', $attributes = '',$sessions=array(),$old_orders_id=0,$forced_ids="",$salemaker_id=0) {
		global $customer_id;
		 
		if (empty($quantity)) return true; // nothing needs to be updated if theres no quantity, so we return true..
	
		if ($this->contents[products_id]['element_type']=='E') return;

		$products_id_string = tep_get_uprid($products_id, $attributes);
		$products_id = tep_get_prid($products_id_string);
	 
		$attributes_pass_check = true;
		if (is_array($attributes)) {  
			reset($attributes);  
			while (list($option, $value) = each($attributes)) {  
				if (!is_numeric($option) || !is_numeric($value)) {  
					$attributes_pass_check = false;  
					break;           
				}
			}  
		} 
		if (is_numeric($products_id) && isset($this->contents[$products_id_string]) && is_numeric($quantity)  && ($attributes_pass_check == true)) {
			$this->contents[$products_id_string] = array('qty' => $quantity,'element_type'=>'P','sessions'=>$sessions,'old_orders_id'=>$old_orders_id,'answer_type'=>'','answer_value'=>'','forced_item_ids'=>$forced_ids,'discount_id'=>$salemaker_id);
			// update database
			if($quantity=="")$quantity=0;
			if (tep_session_is_registered('customer_id')) {
				tep_db_query("update " . TABLE_CUSTOMERS_BASKET . " set customers_basket_quantity = '" . $quantity . "',discount_id='" . $salemaker_id . "' where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($products_id_string) . "'");
			} else
				tep_db_query("update " . TABLE_CUSTOMERS_TEMP_BASKET . " set customers_basket_quantity = '" . $quantity . "' where customers_id = '" . tep_session_id() . "' and products_id = '" . tep_db_input($products_id_string) . "'");
			if (is_array($attributes)) {
				reset($attributes);
				while (list($option, $value) = each($attributes)) {
					$this->contents[$products_id_string]['attributes'][$option] = $value;
					// update database
					if (tep_session_is_registered('customer_id')) 
						tep_db_query("update " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " set products_options_value_id = '" . (int)$value . "' where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($products_id_string) . "' and products_options_id = '" . (int)$option . "'");
					else
						tep_db_query("update " . TABLE_CUSTOMERS_TEMP_BASKET_ATTRIBUTES . " set products_options_value_id = '" . (int)$value . "' where customers_id = '" . tep_session_id() . "' and products_id = '" . tep_db_input($products_id_string) . "' and products_options_id = '" . (int)$option . "'");
				}
			}
		}
	}

	function cleanup() {
		global $customer_id;
	
		reset($this->contents);
		while (list($key,) = each($this->contents)) {
			if ($this->contents[$key]['qty'] < 1) {
			unset($this->contents[$key]);
			// remove from database
			if (tep_session_is_registered('customer_id')) {
				tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET . " where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($key) . "'");
				tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($key) . "'");
					if ($this->contents[$key]['element_type']=='E'){
						tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_SESSIONS . " where customers_id ='" . (int)$customer_id . "' and products_id= '" . tep_db_input(substr($key,1)) . "'");
						if ($this->contents[$key]['qty']>1){
							$events_fd=false;
							while(list($kkey,)=each($this->contents)){
								if($this->contents[$kkey]['element_type']=='E')
								$events_fd=true;
							}	
						 tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTENDEES . " where customers_id ='" . (int)$customer_id . "'");
						}
					}
				} else {
				tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET . " where customers_id = '" . tep_session_id() . "' and products_id = '" . tep_db_input($key) . "'");
				tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET_ATTRIBUTES . " where customers_id = '" . tep_session_id() . "' and products_id = '" . tep_db_input($key) . "'");
				if ($this->contents[$key]['element_type']=='E')
					tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS . " where customers_id ='" . tep_session_id() . "' and products_id= '" . tep_db_input(substr($key,1)) . "'");
				if ($this->contents[$key]['element_type']=='V')
					tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_SERVICES . " where customers_id ='" . (int)$customer_id . "' and products_id= '" . tep_db_input($key) . "'");

				}
				
			}
		}
	}

	function count_contents() {  // get total number of items in cart 
	//print_r($this->contents);
		$total_items = 0;
		if (is_array($this->contents)) {
			reset($this->contents);
			while (list($products_id, ) = each($this->contents)) {
				$total_items += $this->get_quantity($products_id);
			}
		}
		return $total_items;
	}

	function get_quantity($products_id_string) {
		if (isset($this->contents[$products_id_string])) {
			return $this->contents[$products_id_string]['qty'];
		} else {
			return 0;
		}
	}
	function is_price_break($products_id){
		$query=tep_db_query("SELECT products_price_break from " . TABLE_PRODUCTS . " where products_id=" .$products_id);
		$result=tep_db_fetch_array($query);
		if ($result["products_price_break"]=="Y") return true;
		else return false;
	}

	function in_cart($products_id_string) {
		if (isset($this->contents[$products_id_string])) {
			return true;
		} else {
			return false;
		}
	}

	function remove($products_id,$query_count='0') {
		global $customer_id,$messageStack,$err;
		$err= "";
		
		
		$link_sub_count = 0;
		if($this->contents[$products_id]['element_type']=='S'){
			$element_id=substr($products_id,1);
			$link_sub_query = tep_db_query("select * from " . TABLE_PRODUCTS_TO_SUBSCRIPTION . " where subscription_id = '" . $element_id . "' ");
			//echo "select * from " . TABLE_PRODUCTS_TO_SUBSCRIPTION . " where subscription_id = '" . $element_id . "' ";
			$p_array=array();
			$cnt=0;
			while($link_check_sub = tep_db_fetch_array($link_sub_query)){
			//$link_sub_id=$link_check_sub['products_id'];
			$p_array[$cnt]=array("products_id"=>$link_check_sub["products_id"]);
			$cnt++;
			}
			$link_sub_count = tep_db_num_rows($link_sub_query);
			//echo $link_sub_count;
			//Added line 574-582 by sobi

			$get_member_subscription=tep_db_query("select subscription_id from " . TABLE_SUBSCRIPTIONS . " where subscription_type='M'  ");
			if(tep_db_num_rows($get_member_subscription)>0 && $query_count=='0'){ //remove Store subscription
				$member=tep_db_fetch_array($get_member_subscription);
				$subscription_id = 'S'.$member['subscription_id'];
				if($products_id==$subscription_id ) {
					$order_query=tep_db_query("select o.orders_id from " .TABLE_ORDERS_PRODUCTS ." op," . TABLE_ORDERS . " o where op.orders_id=o.orders_id and o.customers_id='" . $customer_id . "' and  op.products_id='" . $member['subscription_id'] ."' and op.products_type='S'");
					if(tep_db_num_rows($order_query)<=0) {
					  $messageStack->add_session("shopping_cart",'Store Member Subscriptions  linked  are not removed Seperately',"simple");
					  $query_count=1;
					}  
				 }
			}
		}

		
		// remove from database
		if ($this->contents[$products_id]['element_type']=='E' || $this->contents[$products_id]['element_type']=='S') {
			$element_id=substr($products_id,1);
		} else {
			$element_id=$products_id;
		}//echo "cart contents";
		//print_r ($this->contents);
		if (tep_session_is_registered('customer_id')) {
		//print_r ($p_array);
		for($i=0;$i<sizeof($p_array);$i++){
		$query=tep_db_query("select * from ". TABLE_CUSTOMERS_BASKET . " as tcb where tcb.customers_id = '" . (int)$customer_id . "' and if(instr(tcb.products_id,'{')>0,substring(tcb.products_id,1,instr(tcb.products_id,'{')-1),tcb.products_id)='" .$p_array[$i]['products_id'] ."' and  products_type='P' ");
		$query_count = tep_db_num_rows($query);
		//echo $query_count;
		if($query_count>0 ) break;
		}
		if($link_sub_count > 0  && $query_count>0 ){
			//return "linked";
			$messageStack->add_session("shopping_cart",'Subscriptions  linked with products are not removed Seperately',"simple");
		}else{
		tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET . " where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($element_id) . "' and products_type='".$this->contents[$products_id]['element_type']."'");
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where customers_id = '" . (int)$customer_id . "' and products_id = '" . tep_db_input($element_id) . "'");
			}
			if ($this->contents[$products_id]['element_type']=='E'){
				tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_SESSIONS . " where customers_id ='" . (int)$customer_id . "' and products_id= '" . $element_id . "'");
				if ($this->contents[$products_id][qty]>1 && $this->multiple_event_attendees>=1){
					$events_fd=false;
					while(list($key,)=each($this->contents)){
						if($this->contents[$key]['element_type']=='E')
						  $events_fd=true;
					}
					if($events_fd){
						tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTENDEES . " where customers_id ='" . (int)$customer_id . "'");
						$this->multiple_event_attendees=0;
					}
				} else if ($this->contents[$products_id][qty]>1){
					$this->multiple_event_attendees-=1;
				}
				$this->attendees=array();
			}
			if ($this->contents[$products_id]['element_type']=='V')
				tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_SERVICES . " where customers_id ='" . (int)$customer_id . "' and products_id= '" . $element_id . "'");

		}else{
		
		//
		for($i=0;$i<sizeof($p_array);$i++){
			$query=tep_db_query("select * from ". TABLE_CUSTOMERS_TEMP_BASKET . " as tcb where tcb.customers_id = '" .  tep_session_id(). "' and if(instr(tcb.products_id,'{')>0,substring(tcb.products_id,1,instr(tcb.products_id,'{')-1),tcb.products_id)='" .$p_array[$i]['products_id'] ."' and  products_type='P' ");
			//$query=tep_db_query("select * from ". TABLE_CUSTOMERS_TEMP_BASKET . " where customers_id = '" . tep_session_id() . "' and products_id='" .$p_array[$i]['products_id'] ."' and  products_type='P' ");
			//echo "select * from ". TABLE_CUSTOMERS_TEMP_BASKET . " where customers_id = '" . tep_session_id() . "' and products_id='" .$p_array[$i]['products_id'] ."' and  products_type='P' ";
			$query_count = tep_db_num_rows($query);
			if($query_count>0 ) break;
			}
			if($link_sub_count > 0 && $query_count>0){
			$messageStack->add_session("shopping_cart",'Subscriptions  linked with products are not removed Seperately',"simple");
			}else{
				tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET . " where customers_id = '" . tep_session_id() . "' and products_id = '" . tep_db_input($element_id) . "' and products_type='".$this->contents[$products_id]['element_type']."'");
				tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET_ATTRIBUTES . " where customers_id = '" . tep_session_id() . "' and products_id = '" . tep_db_input($element_id) . "'");
				}
				if ($this->contents[$products_id]['element_type']=='E'){
					tep_db_query("delete from " . TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS . " where customers_id ='" . tep_session_id() . "' and products_id= '" . $element_id . "'");
					$this->attendees=array();
				}
			 if ($this->contents[$products_id]['element_type']=='V')
					tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_SERVICES . " where customers_id ='" . tep_session_id() . "' and products_id= '" . $element_id . "'");
	
			}
			//echo $link_sub_count  .'qq'. $query_count;// if product linked with subscription deleted automatically subscription also deleted with product
			if ($this->contents[$products_id]['element_type']=='P') {
				$element_id=$products_id;
				$sub_query = tep_db_query("select * from " . TABLE_PRODUCTS_TO_SUBSCRIPTION . " where products_id = '" . $element_id . "' ");
				
				if(tep_db_num_rows($sub_query) > 0){
					$check_sub = tep_db_fetch_array($sub_query);
					$sub_id= $check_sub['subscription_id'];
					$this->remove("S".$sub_id);
				}
			}
			//if service or event deleted, Member subscription also deleted automatically, if exists	 Added line 663- 673 by sobi	
			if ($this->contents[$products_id]['element_type']=='E' || $this->contents[$products_id]['element_type']=='V') { 
				$item_exist=false;
				reset($this->contents);
				while(list($key,)=each($this->contents)){
					if(($this->contents[$key]['element_type']=='E' || $this->contents[$key]['element_type']=='V') && $key!=$products_id) {
						
						$item_exist=true;
					}	
				}
				if(!$item_exist) {
					$get_member_subs_query=tep_db_query("select subscription_id from " . TABLE_SUBSCRIPTIONS . " where subscription_type='M'  ");
					if(tep_db_num_rows($get_member_subs_query)>0){
					   $member_subscription=tep_db_fetch_array($get_member_subs_query);
					   $subscription_id = $member_subscription['subscription_id'];
					   $this->remove("S".$subscription_id,'');
					} 
				}
			}	
			if($query_count<=0)
			unset($this->contents[$products_id]);
			// assign a temporary unique ID to the order contents to prevent hack attempts during the checkout procedure
			$this->cartID = $this->generate_cart_id();
	}

	function remove_all() {
		$this->reset();
	}

	function get_product_id_list($only_product_ids=true) {
		$product_id_list = '';
		if (is_array($this->contents)) {
			reset($this->contents);
			while (list($products_id, ) = each($this->contents)) {
				if ($this->contents[$products_id]['element_type']=='E' || $this->contents[$products_id]['element_type']=='S' || $this->contents[$products_id]['element_type']=='V')
					$product_id_list .= ',' . substr($products_id,1);
				else
					$product_id_list .= ($only_product_ids?',' . tep_get_prid($products_id):',' . $products_id);
			}
		}
		return substr($product_id_list, 1);
	}

	function calculate() {
		global $dates;
		$this->total_virtual = 0; // ICW Gift Voucher System
		$this->total = 0;
		$this->weight = 0;
		$this->stored_total = 0;
		if (!is_array($this->contents)) return 0;
	
		$owd_costs=0;
		reset($this->contents);
		$this->mode="";
		while (list($products_id, ) = each($this->contents)) {
			$qty = $this->contents[$products_id]['qty'];
			if ($this->contents[$products_id]['element_type']=='P')
			{
				$owd_costs+=tep_owd_costs('quantity',$this->contents[$products_id]['qty']);
				// products price
				$this->mode=($this->mode=="" || $this->mode=="P"?"P":"M");
				$product_query = tep_db_query("select products_id, products_price,products_price_break,products_tax_class_id, products_weight from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
				if ($product = tep_db_fetch_array($product_query)) {
					// ICW ORDER TOTAL CREDIT CLASS Start Amendment
					$no_count = 1;
					$gv_query = tep_db_query("select products_model from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
					$gv_result = tep_db_fetch_array($gv_query);
					if (ereg('^GIFT', $gv_result['products_model'])) {
						$no_count = 0;
					}
					// ICW ORDER TOTAL  CREDIT CLASS End Amendment
					$prid = $product['products_id'];
					$products_tax = tep_get_tax_rate($product['products_tax_class_id']);
					$products_price = $product['products_price'];
					$products_weight = $product['products_weight'];

					$products_price=$this->get_product_price($products_id,$product,0);
					if ($this->contents[$products_id]['discount_id']>0) {

						$product_to_categories_query = tep_db_query("select categories_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . (int)$prid . "'");
						$product_to_categories = tep_db_fetch_array($product_to_categories_query);
						$category = $product_to_categories['categories_id'];

						$sale_option=" sale_id=" . $this->contents[$products_id]['discount_id'] .' and ' ;
						$sDate=getServerDate();
						$sale_query = tep_db_query("select sale_specials_condition, sale_deduction_value, sale_deduction_type,sale_id,sale_discount_type from " . TABLE_SALEMAKER_SALES . " where " . $sale_option . " ((sale_categories_all='' and sale_products_selected='') or sale_categories_all like '%," . $category . ",%' or sale_products_selected like '%," . (int)$prid .",%') and sale_status = '1' and (sale_date_start <= '" . $sDate. "' or sale_date_start = '0000-00-00') and (sale_date_end >= '" . $sDate . "' or sale_date_end = '0000-00-00') and (sale_pricerange_from <= '" . $product["products_price"] . "' or sale_pricerange_from = '0') and (sale_pricerange_to >= '" . $product["products_price"] . "' or sale_pricerange_to = '0')");
						if (tep_db_num_rows($sale_query)>0){
							$sale=tep_db_fetch_array($sale_query);
							$products_price=tep_get_salemaker_price($this->contents[$products_id]['special_price'],$products_price,$sale);
						}
					}
							
					$this->weight_virtual += ($qty * $products_weight) * $no_count;// ICW CREDIT CLASS;
					$this->weight += ($qty * $products_weight);
				}
				 if (isset($this->contents[$products_id]['attributes'])) {
					reset($this->contents[$products_id]['attributes']);
					while (list($option, $value) = each($this->contents[$products_id]['attributes'])) {
						$attribute_price_query = tep_db_query("select options_values_price, price_prefix, products_attributes_weight
						from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$prid . "' and options_id = '" . (int)$option . "' and options_values_id = '" . (int)$value . "'");
						$attribute_price = tep_db_fetch_array($attribute_price_query);
						if ($attribute_price['price_prefix'] == '-') {
							$products_price -= $attribute_price['options_values_price'];
						} else {
							$products_price += $attribute_price['options_values_price'];
						}
						$this->weight += ($qty*$attribute_price['products_attributes_weight']);
						$this->weight_virtual += ($qty * $attribute_price['products_attributes_weight']) * $no_count;// ICW CREDIT CLASS;
					}
				}
				$this->total_virtual += tep_add_tax($products_price, $products_tax) * $qty * $no_count;// ICW CREDIT CLASS;
				$this->total += tep_add_tax($products_price, $products_tax) * $qty;
		  } elseif ($this->contents[$products_id]['element_type']=='S'){
				$this->mode=($this->mode=="" || $this->mode=="S"?"S":"M");
				// subscription price
				$subscription_query = tep_db_query("select subscription_id, subscription_costs,subscription_type subscription_tax_class_id from " . TABLE_SUBSCRIPTIONS . " where subscription_id = '" . (int)substr($products_id,1) . "'");
				if ($subscription = tep_db_fetch_array($subscription_query)) {
					$suid = $subscription['subscription_id'];
					// for stored membership
					if($subscription['subscription_type']!='M')
					$subscription_tax = tep_get_tax_rate($subscription['subscription_tax_class_id']);
					$subscription_costs = $this->get_subscription_price($suid,$subscription['subscription_costs']);
					$subscription_costs = $subscription_costs - subscription_discount($suid,$this->contents[$products_id]['subscription_start_date'],$subscription['subscription_costs']);
					$subscription_weight = $subscription['subscription_weight'];

					$this->total_virtual += tep_add_tax($subscription_costs, $subscription_tax);
					$this->total += tep_add_tax($subscription_costs, $subscription_tax) * $qty;
				}
	      } else if ($this->contents[$products_id]['element_type']=='V'){
				// service price
				$this->mode=($this->mode=="" || $this->mode=="V"?"V":"M");
				$prid=tep_get_service_prid($products_id);
				$services_query = tep_db_query("select service_id, service_costs,include_resource_price, service_tax_class_id,service_total_time,booking_type from " . TABLE_SERVICES . " where service_id = '" . $prid . "'");
				if ($services = tep_db_fetch_array($services_query)) {
					$service_tax_id=$services["service_tax_class_id"];					
					if($this->contents[$products_id]['others']['resource_id'] && $services['include_resource_price']=='Y' && $this->contents[$products_id]['others']['resource_costs'])
						$service_tax_id=tep_get_resource('resource_tax_class_id',$this->contents[$products_id]['others']['resource_id'],$languages_id);					
					$service_tax=tep_get_tax_rate($service_tax_id);		
					//service discounts start
					$dates['start_date']=$this->contents[$products_id]['others']['start_date'];
					$dates['end_date']=$this->contents[$products_id]['others']['end_date'];
					$dates['start_time']=$this->contents[$products_id]['others']['start_time'];
					$dates['end_time']=$this->contents[$products_id]['others']['end_time'];					
					$dates['service_costs']=$this->get_service_price($products_id,$services,$service_tax);
					$service_price=$this->get_service_price($products_id,$services,$service_tax)-services_discount($prid);
					//end
					//$service_price=$this->get_service_price($products_id,$services,$service_tax);									
					$this->total_virtual += tep_add_tax($service_price*$qty,$service_tax) * $no_count;// ICW CREDIT CLASS;
					$this->total += tep_add_tax($service_price*$qty,$service_tax);
				}
			}elseif ($this->contents[$products_id]['element_type']=='E') {
				$this->mode=($this->mode=="" || $this->mode=="E"?"E":"M");
				$result_query = tep_db_query("select events_id,events_fees,session_style,waitfee_vip,waitfee_custom,waitfee_firstcome,events_tax_class_id from " . TABLE_EVENTS . " where events_id='" . (int)substr($products_id,1) . "'");
				$result = tep_db_fetch_array($result_query);				
				$events_tax = tep_get_tax_rate($result['events_tax_class_id']);
				$total_fees=$this->get_event_price($products_id,$result,$events_tax);
				$this->total_virtual += tep_add_tax($total_fees*$qty,$events_tax);
				$this->total += tep_add_tax($total_fees*$qty,$events_tax);
				
				
			}	
    }
		if ($owd_costs>0){
			$owd_costs+=tep_owd_costs('packing',$this->weight);
			$owd_costs+=tep_owd_costs('order');
			$owd_costs+=tep_owd_costs('overweight',$this->weight);
			$this->total+=$owd_costs;
			$this->total_virtual+=$owd_costs;
			$this->stored_total+=$owd_costs;
		}
   }
	function attributes_price($products_id) {
		$attributes_price = 0;
		if (isset($this->contents[$products_id]['attributes'])) {
			if ($this->contents[$products_id]['element_type']=="V"){
				$prid=tep_get_service_prid($products_id);
				// get the service details
				reset($this->contents[$products_id]['attributes']);
				while (list($option, $value) = each($this->contents[$products_id]['attributes'])) {
					$attribute_price_query = tep_db_query("select options_values_price, price_prefix 
					from " . TABLE_SERVICES_ATTRIBUTES . " where service_id = '" . $prid . "' and options_id = '" . (int)$option . "' and options_values_id = '" . (int)$value . "'");

					$attribute_price = tep_db_fetch_array($attribute_price_query);
					if ($attribute_price['price_prefix'] == '-') {
						$attributes_price -= $attribute_price['options_values_price'];
					} else {
						$attributes_price += $attribute_price['options_values_price'];
					}
				}
			} else {
				reset($this->contents[$products_id]['attributes']);
				while (list($option, $value) = each($this->contents[$products_id]['attributes'])) {
					$attribute_price_query = tep_db_query("select options_values_price, price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$products_id . "' and options_id = '" . (int)$option . "' and options_values_id = '" . (int)$value . "'");
					$attribute_price = tep_db_fetch_array($attribute_price_query);
					//DiscountSpecials start
					  global $customer_id;
/*					  $query = tep_db_query("select g.customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " g inner join  " . TABLE_CUSTOMERS  . " c on g.customers_groups_id = c.customers_groups_id and c.customers_id = '" . $customer_id . "'");
					  $query_result = tep_db_fetch_array($query);
					  $customers_groups_discount = $query_result['customers_groups_discount'];
					  $query = tep_db_query("select customers_discount from " . TABLE_CUSTOMERS . " where customers_id =  '" . $customer_id . "'");
					  $query_result = tep_db_fetch_array($query);
					  $customer_discount = $query_result['customers_discount'];
					  $customer_discount = $customer_discount + $customers_groups_discount;
					  if ($customer_discount >= 0) {
						 $attribute_price['options_values_price'] = $attribute_price['options_values_price'] + $attribute_price['options_values_price'] * abs($customer_discount) / 100;
					  } else {
						 $attribute_price['options_values_price'] = $attribute_price['options_values_price'] - $attribute_price['options_values_price'] * abs($customer_discount) / 100;
					  }
*/				   //DiscountSpecials end
					if ($attribute_price['price_prefix'] == '-') {
						$attributes_price -= $attribute_price['options_values_price'];
					} else {
						$attributes_price += $attribute_price['options_values_price'];
					}
				}
			} // products_type
		}
		return $attributes_price;
	}

    function get_products() {
		global $languages_id,$dates,$currencies;
		if (!is_array($this->contents)) return false;
		$products_array = array();
		reset($this->contents);
		while (list($products_id, ) = each($this->contents)) {
			if ($this->contents[$products_id]['element_type']=='P')
       		{
				$products_query = tep_db_query("select p.products_id, p.products_price_break,p.product_type,pd.products_name, p.products_model, p.products_image_1,p.products_title_1,p.products_price, p.products_weight, p.products_tax_class_id,p.products_sku , cd.categories_name,cd.categories_id from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES_DESCRIPTION ." cd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pc where p.products_id = '" . (int)$products_id . "' and pc.products_id = p.products_id and pc.categories_id = cd.categories_id and pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "' and cd.language_id='" . (int)$languages_id . "'");
				if ($products = tep_db_fetch_array($products_query)) {
					$prid = $products['products_id'];
					//$original_price=$products["products_price"];
					$original_price=$products_price = $this->get_product_price($products_id,$products,0);
				   $products_tax=tep_get_tax_rate($products['products_tax_class_id']);
				     $price_breaks=false;
					 $discount_text='';
					 $discount_whole_text='';
					 if ($products["products_price_break"]=="Y") {
					 	$price_breaks=tep_get_products_price_breaks($prid);
					 } else{
					 	// for salemaker display
						$sale_discount_type=$this->contents[$products_id]['special_price']?'S':'';
						if ($this->contents[$products_id]['discount_id']>0) {
							$sale_option=" sale_id=" . $this->contents[$products_id]['discount_id'] . " and ";
							$sDate=getServerDate();
							$sale_query = tep_db_query("select sale_specials_condition, sale_deduction_value, sale_deduction_type,sale_id,sale_discount_type,choice_text from " . TABLE_SALEMAKER_SALES . " where " . $sale_option . " ((sale_categories_all='' and sale_products_selected='') or sale_categories_all like '%," . $products["categories_id"] . ",%' or sale_products_selected like '%," . (int)$prid .",%') and sale_status = '1' and (sale_date_start <= '" . $sDate. "' or sale_date_start = '0000-00-00') and (sale_date_end >= '" . $sDate . "' or sale_date_end = '0000-00-00') and (sale_pricerange_from <= '" . $products["products_price"] . "' or sale_pricerange_from = '0') and (sale_pricerange_to >= '" . $products["products_price"] . "' or sale_pricerange_to = '0')");
							if (tep_db_num_rows($sale_query)>0){
								$sale=tep_db_fetch_array($sale_query);
								$products_price=tep_get_salemaker_price($this->contents[$products_id]['special_price'],$products_price,$sale);
								$sale_discount_type=$sale['sale_discount_type'];

								//if ($special_price && $sale['sale_specials_condition']==2) $original_price=$special_price;
								switch($sale['sale_deduction_type']){
									case 1:
										$discount_text=$sale["choice_text"] . " (" . number_format($sale["sale_deduction_value"],2). "%)";
										break;
									case 2:
										$discount_text=$sale["choice_text"] . " (<s><font color='red'>" . $currencies->format($original_price) . "</font></s>&nbsp;" . $currencies->format($sale["sale_deduction_value"]) . ")";
										break;
									default:
										$discount_text=$sale["choice_text"] . " (" . $currencies->format($sale["sale_deduction_value"]). ")";
										break;
									
								}
								$discount_whole_text=TEXT_DISCOUNT_APPLIED . '&nbsp;' . $discount_text .'<br>' . TEXT_ORIGINAL_AMOUNT . '&nbsp;' . $currencies->format(tep_add_tax($original_price,$products_tax)*$this->contents[$products_id]['qty']) . '<br>' . TEXT_DISCOUNT . '&nbsp;' .$currencies->format(tep_add_tax($original_price-$products_price,$products_tax)*$this->contents[$products_id]['qty']) . '<br>';
							}
						}
					 }
                    //DiscountSpecials end
					$products_array[] = array(	'element_type'=>$this->contents[$products_id]['element_type'],
												'old_orders_id'=>$this->contents[$products_id]['old_orders_id'],
												'answer_type'=>$this->contents[$products_id]['answer_type'],
												'answer_value'=>$this->contents[$products_id]['answer_value'],
												'id' => $prid,
												'sh_id'=>$products_id,
												'sessions'=>array(),
												'forced_item_ids'=>$this->contents[$products_id]['forced_item_ids'],
												'name' => $products['products_name'],
												'model' => $products['products_model'],
												'image' => $products['products_image_1'],
												'price' => ($original_price+ $this->attributes_price($products_id)),
												'quantity' => $this->contents[$products_id]['qty'],
												'weight' => $products['products_weight'],
												'final_price' => ($products_price + $this->attributes_price($products_id)),
												'tax_class_id' => $products['products_tax_class_id'],
												'attributes' => (isset($this->contents[$products_id]['attributes']) ? $this->contents[$products_id]['attributes'] : ''),
												'sku'=>$products["products_sku"],
												'category_name' => $products['categories_name'],
												'price_breaks'=>$price_breaks,
												'product_type'=>$products['product_type'],//Support Packs
												'discount_id'=>$this->contents[$products_id]['discount_id'],
												'discount_text'=>$discount_text,
												'discount_whole_text'=>$discount_whole_text,
												'discount_type'=>$sale_discount_type
												);
				}
        	} else if ($this->contents[$products_id]['element_type']=='S'){
					$subscription_query = tep_db_query("select su.subscription_id, sud.subscription_name, su.subscription_image, su.subscription_costs, su.subscription_tax_class_id,su.subscription_type, scd.subscription_categories_name from " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud," . TABLE_SUBSCRIPTION_CATEGORIES . " sc," . TABLE_SUBSCRIPTION_CATEGORIES_DESCRIPTION . " scd," . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " ssc where su.subscription_id = '" . (int)substr($products_id,1) . "' and sc.subscription_categories_id=scd.subscription_categories_id and sc.subscription_categories_id=ssc.subscription_categories_id and ssc.subscription_id='" . (int)substr($products_id,1) . "' and sud.subscription_id = su.subscription_id and sud.language_id = '" . (int)$languages_id . "' and scd.language_id='" . (int)$languages_id . "'");
					//echo 'hi';
					//$subscription_query = tep_db_query("select su.subscription_id, sud.subscription_name, su.subscription_image, su.subscription_costs, su.subscription_tax_class_id,su.subscription_type from " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id = '" . (int)substr($products_id,1) . "' and sud.subscription_id = su.subscription_id and sud.language_id = '" . (int)$languages_id . "'");
					if ($subscription = tep_db_fetch_array($subscription_query)) {
						$prid = $subscription['subscription_id'];
						$subscription_costs = $this->get_subscription_price($prid,$subscription['subscription_costs']);
						//subscription discount start
						$subscription_costs = $subscription_costs - subscription_discount($prid,$this->contents[$products_id]['subscription_start_date'],$subscription['subscription_costs']);
						//end
						$subscription_tax=tep_get_tax_rate($subscription['subscription_tax_class_id']);
						$subs_model="";
						if($subscription['subscription_type']=='C') $subs_model='Casual';
						else if($subscription['subscription_type']=='S') $subs_model='Seasonal';
						else if($subscription['subscription_type']=='B') $subs_model='Basic';
						$products_array[] = array(	'element_type'=>$this->contents[$products_id]['element_type'],
													'old_orders_id'=>$this->contents[$products_id]['old_orders_id'],
													'answer_type'=>$this->contents[$products_id]['answer_type'],
													'answer_value'=>$this->contents[$products_id]['answer_value'],
													'id' => substr($products_id,1),
													'sh_id'=>$products_id,
													'sessions'=>array(),
													'subscription_start_date'=>$this->contents[$products_id]['subscription_start_date'],
													'forced_item_ids'=>$this->contents[$products_id]['forced_item_ids'],
													'name' => $subscription['subscription_name'],
													'model' => $subs_model,
													'image' => $subscription['subscription_image'],
													'price' => $subscription_costs,
													'quantity' =>1,
													'weight'=>1,
													'final_price' => $subscription_costs,
													'subscription_type'=>$subscription["subscription_type"],
													'tax_class_id' => $subscription['subscription_tax_class_id'],
													'sku'=>'',
													'category_name' => $subscription['subscription_categories_name'],
													'attributes' =>'');
					}
			} else if ($this->contents[$products_id]['element_type']=='V'){
				// service price   
				$prid=tep_get_service_prid($products_id);
				$services_query = tep_db_query("select se.service_id, sed.service_name,se.service_image,se.service_costs, se.include_resource_price,se.service_tax_class_id,se.service_total_time,se.booking_type,scd.services_categories_name from " . TABLE_SERVICES . " se, " . TABLE_SERVICES_DESCRIPTION . " sed," . TABLE_SERVICES_CATEGORIES . " sc," . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " scd," . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " ssc where se.service_id = '" . $prid . "' and ssc.service_id='" . $prid . "' and se.service_id=sed.service_id and sc.services_categories_id=scd.services_categories_id and sc.services_categories_id=ssc.services_categories_id and sed.language_id='" . $languages_id ."' and scd.language_id='" . (int)$languages_id . "'");
				//$services_query = tep_db_query("select se.service_id, sed.service_name,se.service_image, se.service_costs, se.include_resource_price,se.service_tax_class_id,se.service_total_time,se.booking_type from " . TABLE_SERVICES . " se, " . TABLE_SERVICES_DESCRIPTION . " sed where se.service_id = '" . $prid . "' and se.service_id=sed.service_id and sed.language_id='" . $languages_id ."'");
				if ($services = tep_db_fetch_array($services_query)) {
					$service_tax_id=$services["service_tax_class_id"];				
					$price=$services["service_costs"];	
					if($services['include_resource_price']=='Y' && $this->contents[$products_id]['others']['resource_id'])	{
						$service_tax_id=tep_get_resource('resource_tax_class_id',$this->contents[$products_id]['others']['resource_id'],$languages_id);
						$price=tep_get_resource('resource_costs',$this->contents[$products_id]['others']['resource_id'],$languages_id);
							
					}		
					//service discount start 
										
					$dates['start_date']=$this->contents[$products_id]['others']['start_date'];
					$dates['end_date']=$this->contents[$products_id]['others']['end_date'];
					$dates['start_time']=$this->contents[$products_id]['others']['start_time'];
					$dates['end_time']=$this->contents[$products_id]['others']['end_time'];
					$service_tax=tep_get_tax_rate($service_tax_id);
					$dates['service_costs']=$this->get_service_price($products_id,$services,$service_tax);
					$service_price=$this->get_service_price($products_id,$services,$service_tax)-services_discount($prid);
					//end										
					//$service_price=$this->get_service_price($products_id,$services,$service_tax);														
					$products_array[] = array(	'element_type'=>$this->contents[$products_id]['element_type'],
												'old_orders_id'=>$this->contents[$products_id]['old_orders_id'],
												'id' =>$prid,
												'sh_id'=>$products_id,
												'name' => $services['service_name'],
												'image' => $services['service_image'],
												'price' => $price,
												'others'=> $this->contents[$products_id]['others'],
												'quantity' =>$this->contents[$products_id]['qty'],
												'final_price' => $service_price,
												'tax_class_id' => $service_tax_id,
												'sku'=>'',
												'category_name' => $services['services_categories_name'],
												'attributes'=>$this->contents[$products_id]['attributes']
												);
				}
				
			}elseif ($this->contents[$products_id]['element_type']=='E'){
				$result_query = tep_db_query("select e.events_id,ed.events_name,e.session_style,e.events_image,e.events_fees,e.waitfee_vip,e.waitfee_firstcome,e.waitfee_custom,e.events_tax_class_id,ecd.events_categories_name from events e, events_description ed,events_categories ec,events_categories_description ecd,events_to_events_categories eec where e.events_id='" . (int)substr($products_id,1) . "' and eec.events_id='" . (int)substr($products_id,1) . "' and ec.events_categories_id=ecd.events_categories_id and ec.events_categories_id=eec.events_categories_id and e.events_id=ed.events_id and ed.language_id='" . (int)$languages_id . "' and ecd.language_id='" . (int)$languages_id . "'");
				//$result_query = tep_db_query("select e.events_id,ed.events_name,e.session_style,e.events_image,e.events_fees,e.waitfee_vip,e.waitfee_firstcome,e.waitfee_custom,e.events_tax_class_id from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . " ed where e.events_id='" . (int)substr($products_id,1) . "' and e.events_id=ed.events_id and ed.language_id='" . (int)$languages_id . "'");

				$result = tep_db_fetch_array($result_query);
				
				$events_tax = tep_get_tax_rate($result['events_tax_class_id']);
		
				$total_fees=$this->get_event_price($products_id,$result,$events_tax);

				$products_array[] = array(	'element_type'=>$this->contents[$products_id]['element_type'],
											'answer_type'=>$this->contents[$products_id]['answer_type'],
											'answer_value'=>$this->contents[$products_id]['answer_value'],
											'id' => substr($products_id,1),
											'sh_id'=>$products_id,
											'sessions'=>$this->contents[$products_id]['sessions'],
											'forced_item_ids'=>$this->contents[$products_id]['forced_item_ids'],
											'name' => $result['events_name'],
											'model' => '',
											'image' => $result['events_image'],
											'price' =>  $total_fees,
											'quantity' => $this->contents[$products_id]['qty'],
											'weight' => '1',
											'final_price' => $total_fees,
											'tax_class_id' => $result['events_tax_class_id'],
											'old_orders_id'=>$this->contents[$products_id]['old_orders_id'],
											'sku'=>'',
											'category_name' => $result['events_categories_name'],
											'attributes' => (isset($this->contents[$products_id]['attributes']) ? $this->contents[$products_id]['attributes'] : ''));
			}
		}
//		print_r($products_array);
	return $products_array;
	}

	function get_product_price($products_id,$product,$salemaker_id=0){
	  global $customer_id;
		$products_price=$product["products_price"];
		if ($product["products_price_break"]=="Y"){
			$breaks_query=tep_db_query("SELECT discount_per_item from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" . $product["products_id"] . " and quantity=" . (int)$this->contents[$products_id]["qty"]);
			if (tep_db_num_rows($breaks_query)>0){
				$break_result=tep_db_fetch_array($breaks_query);
				$products_price-=$break_result["discount_per_item"];
				return $products_price;
			}
		}
		$query = tep_db_query("select g.customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " g inner join  " . TABLE_CUSTOMERS  . " c on g.customers_groups_id = c.customers_groups_id and c.customers_id = '" . $customer_id . "'");
		$query_result = tep_db_fetch_array($query);
		$customers_groups_discount = $query_result['customers_groups_discount'];
		$query = tep_db_query("select customers_discount from " . TABLE_CUSTOMERS . " where customers_id =  '" . $customer_id . "'");
		$query_result = tep_db_fetch_array($query);
		$customer_discount = $query_result['customers_discount'];
		$customer_discount = $customer_discount + $customers_groups_discount;
		if ($customer_discount >= 0) {
		 $products_price = $products_price + $products_price * abs($customer_discount) / 100;
		} else {
		 $products_price = $products_price - $products_price * abs($customer_discount) / 100;
		}
		$this->contents[$products_id]['special_price']=false;
		if ($special_price = tep_get_products_special_price($products_id,$salemaker_id,$products_id)) {
			$this->contents[$products_id]['special_price']=$special_price;
			$products_price = $special_price;
		}
		return $products_price;
	}

	function get_subscription_price($subscription_id,$subscription_price){
	  global $customer_id;
		$query = tep_db_query("select g.customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " g inner join  " . TABLE_CUSTOMERS  . " c on g.customers_groups_id = c.customers_groups_id and c.customers_id = '" . $customer_id . "'");
		$query_result = tep_db_fetch_array($query);
		$customers_groups_discount = $query_result['customers_groups_discount'];
		$query = tep_db_query("select customers_discount from " . TABLE_CUSTOMERS . " where customers_id =  '" . $customer_id . "'");
		$query_result = tep_db_fetch_array($query);
		$customer_discount = $query_result['customers_discount'];
		$customer_discount = $customer_discount + $customers_groups_discount;
		if ($customer_discount >= 0) {
		 $subscription_price = $subscription_price + $subscription_price * abs($customer_discount) / 100;
		} else {
		 $subscription_price = $subscription_price - $subscription_price * abs($customer_discount) / 100;
		}
		return $subscription_price;
	}

	function get_event_price($events_id,$event,&$events_tax){
		$sessions=&$this->contents[$events_id]['sessions'];
		
		reset($sessions);
		$total_fees=0;
		$waitlist_stored=false;
		$reminder_amount=false;
		while(list($id,)=each($sessions)){
			$events_fees=0;
			if ($sessions[$id]['type']=='R'){ 					//reserved user
				//$days_differ=tep_count_days(date('Y-m-d'),$sessions[$id]['date']);
				$events_fees=$event['events_fees']-tep_get_discount_price($event["events_id"],$event['events_fees'],$sessions[$id]['date']);
				$this->contents[$evetns_id]['sessions'][$id]['events_fees']=$events_fees;
			} else if ($sessions[$id]['type']=='W'){				//waitlist user
				if (!$waitlist_stored){
					switch($sessions[$id]['group']){
						case 'V':
							$events_fees=$event['waitfee_vip'];	//vip group
							break;
						case 'F':
							$events_fees=$event['waitfee_firstcome']; //firstcome group
							break;
						case 'C':
							$events_fees=$event['waitfee_custom'];	//custome group
					}
					if ($event['session_style']=='E') $waitlist_stored=true;
				}
				$this->contents[$events_id]['sessions'][$id]['events_fees']=$event['events_fees'];
			} else {
				if (!$reminder_amount){
					$events_fees=tep_get_orders_reminder_details($this->contents[$events_id]['old_orders_id'],$event["events_id"],$result["session_style"]);
					$events_tax=$amount_details['tax'];
					$events_fees=$amount_details['amount'];
					$reminder_amount=true;
				}
				$this->contents[$events_id]['sessions'][$id]['events_fees']=$event['events_fees'];
			}
			if ($sessions[$id]['type']!='U') $this->contents[$events_id]['sessions'][$id]['fees']=$events_fees;
			else $this->contents[$events_id]['sessions'][$id]['fees']=0;
			$total_fees+=$events_fees;
		}
		return $total_fees;
	}
	
	function get_service_price($service_id,$services,&$service_tax_id){
		global $start_date,$end_date;
		$total=0;
		$others=$this->contents[$service_id]["others"];
				//print_r($this->contents);
		$option_price="";
		$start_date=$others['start_date'];
		$end_date=$others['end_date'];
		$loading_price_dates=get_loading_array((int)$services["service_id"]); 
	   
	  if($this->contents[$service_id]['attributes']){
		$attrib_list=$this->contents[$service_id]['attributes'];
		while (list($option, $value) = each($attrib_list)) {
			$attribute_price_query = tep_db_query("select options_values_price, price_prefix
			from " . TABLE_SERVICES_ATTRIBUTES . " where service_id = '" . (int)$services["service_id"] . "' and options_id = '" . (int)$option . "' and options_values_id = '" . (int)$value . "'");
			$attribute_price = tep_db_fetch_array($attribute_price_query);
			$option_price+=($attribute_price['price_prefix'].$attribute_price['options_values_price']);
		}
	  } 
	  if($services['include_resource_price']=='Y'){
			$resource_query=tep_db_query("select resource_costs,resource_tax_class_id from ".TABLE_SERVICE_RESOURCE ." where resource_id='".$others["resource_id"]."'");
			if($resources = tep_db_fetch_array($resource_query)){
				$loading_dates=array('loading_price_dates'=>$loading_price_dates,'start_date'=>$others["start_date"],'end_date'=>$others["end_date"],'start_time'=>$others["start_time"],'end_time'=>$others["end_time"]);
				$final_price=tep_calc_service_option_cost($services,$others["start_date"] . " " . $others["start_time"],$others["end_date"] . " " . ($others["end_time"]),$option_price,$resources["resource_costs"],$loading_dates);
				$total=$final_price;
			}
		}else{			
			$loading_dates=array('loading_price_dates'=>$loading_price_dates,'start_date'=>$others["start_date"],'end_date'=>$others["end_date"],'start_time'=>$others["start_time"],'end_time'=>$others["end_time"]);
			$final_price=tep_calc_service_cost($services,$others["start_date"] . " " . $others["start_time"],$others["end_date"] . " " . ($others["end_time"]),$option_price,$loading_dates,$qty);
			$total=$final_price;
		 }  
		 //if($service_tax && $total) $total=tep_add_tax($final_price,$service_tax);		  
		return $total;
	}
    function show_total() {
      $this->calculate();
      return $this->total;
    }
	function is_free_checkout(){
		// calcuate total amount
		$this->calculate();
		// if the total is zero and only event is added to cart 
		if ($this->total<=0 && ($this->mode=='E' || $this->mode=='V')){
			return true;
		} else {
			return false;
		}
	}

    function show_weight() {
      $this->calculate();

      return $this->weight;
    }

    function generate_cart_id($length = 5) {
      return tep_create_random_value($length, 'digits');
    }

    /*function get_content_type() { 
      $this->content_type = false;

	if ( (DOWNLOAD_ENABLED == 'true') && ($this->count_contents() > 0) ) {
    	reset($this->contents);
		while (list($products_id, ) = each($this->contents)) {  
			if (isset($this->contents[$products_id]['attributes'])) {
				reset($this->contents[$products_id]['attributes']);
				while (list($key, $value) = each($this->contents[$products_id]['attributes'])) {
					if($this->contents[$products_id]['element_type']=='V')
						$virtual_check_query = tep_db_query("select count(*) as total from " . TABLE_SERVICES_ATTRIBUTES . " where service_id = '" . tep_get_service_prid($products_id) . "' and options_id = '" . (int)$key . "' and options_values_id = '" . (int)$value . "'");
					else				 
						$virtual_check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad where pa.products_id = '" . (int)$products_id . "' and pa.options_values_id = '" . (int)$value . "' and pa.products_attributes_id = pad.products_attributes_id");
						
					$virtual_check = tep_db_fetch_array($virtual_check_query);

					if ($virtual_check['total'] > 0) {
						switch ($this->content_type) {
							case 'physical':
								$this->content_type = 'mixed';
								return $this->content_type;
								break;
							default:
								$this->content_type = 'virtual';
								break;
						}
					} else {
						if($this->contents[$products_id]['element_type']=='V') {
							$this->content_type = 'virtual';
						} else { 
							switch ($this->content_type) {
								case 'virtual':
									$this->content_type = 'mixed';
									return $this->content_type;
									break;
								default:
									$this->content_type = 'physical';
									break;
							}
						}
					}
				}
// ICW ADDED CREDIT CLASS - Begin
       		} elseif ($this->show_weight() == 0) {
           		reset($this->contents);
	            while (list($products_id, ) = each($this->contents)) {
					  $virtual_check['products_weight']=0;
					  if ($this->contents[$products_id]['element_type']=='P'){
	    		          $virtual_check_query = tep_db_query("select products_weight from " . TABLE_PRODUCTS . " where products_id = '" . $products_id . "'");
    	        		  $virtual_check = tep_db_fetch_array($virtual_check_query);
					  }
		              if ($virtual_check['products_weight'] == 0) {
							switch ($this->content_type) {
								case 'physical':
									$this->content_type = 'mixed';
									return $this->content_type;
									break;
								default:
									if ($this->contents[$products_id]['element_type']=='E' && ($this->content_type=='' || $this->content_type=='virtual')){
										$this->content_type='virtual';
									} else if ($this->contents[$products_id]['element_type']=='S' && ($this->content_type=='' || $this->content_type=='virtual')){
										$this->content_type='virtual';
									}else if ($this->contents[$products_id]['element_type']=='V' && ($this->content_type=='' || $this->content_type=='virtual')){
										$this->content_type='virtual';	
									}else {
										$this->content_type = 'virtual_weight';
									}
									break;
							}
		              } else {
							switch ($this->content_type) {
							  case 'virtual':
								$this->content_type = 'mixed';
								return $this->content_type;
								break;
							  default:
								$this->content_type = 'physical';
								break;
							}
					}
	 			}
// ICW ADDED CREDIT CLASS - End
          } else {
				switch ($this->content_type) {
					case 'virtual':
						$this->content_type = 'mixed';
						return $this->content_type;
						break;
					default:
						$this->content_type = 'physical';
						break;
				}
          }
        }
    } else {
		reset($this->contents);
		while (list($products_id, ) = each($this->contents)) {
			if ($this->contents[$products_id]['element_type']=='E' && ($this->content_type=='' || $this->content_type=='virtual')){
				$this->content_type='virtual';
			} else if ($this->contents[$products_id]['element_type']=='S' && ($this->content_type=='' || $this->content_type=='virtual')){
				$this->content_type='virtual';
			}else if ($this->contents[$products_id]['element_type']=='V' && ($this->content_type=='' || $this->content_type=='virtual')){
				$this->content_type='virtual';	
			}else if (($this->contents[$products_id]['element_type']=='P' && $this->content_type=='') || $this->content_type=='physical'){
				$this->content_type = 'physical';
			} else {
				$this->content_type = 'mixed';
			}
		}
    }
     return $this->content_type;
    }*/
	
	function  get_content_type(){
		$weight=$this->show_weight();
		$this->content_type=false;
		reset($this->contents);
		while (list($products_id, ) = each($this->contents)) {
			if ($this->content_type=='mixed') break;
			switch($this->contents[$products_id]['element_type']){
				case 'E':
				case 'S':
				case 'V':
					if ($this->content_type=='physical') $this->content_type='mixed';
					else $this->content_type ='virtual';
					break;
				default:
					if ($weight==0) $this->content_type='virtual';
					else if ($this->content_type && $this->content_type=='virtual') $this->content_type='mixed';
					else $this->content_type='physical';
			}
		}
		return $this->content_type;
	}

    function unserialize($broken) {
      for(reset($broken);$kv=each($broken);) {
        $key=$kv['key'];
        if (gettype($this->$key)!="user function")
        $this->$key=$kv['value'];
      }
    }
	
   // ------------------------ ICWILSON CREDIT CLASS Gift Voucher Addittion-------------------------------Start
   // amend count_contents to show nil contents for shipping
   // as we don't want to quote for 'virtual' item
   // GLOBAL CONSTANTS if NO_COUNT_ZERO_WEIGHT is true then we don't count any product with a weight
   // which is less than or equal to MINIMUM_WEIGHT
   // otherwise we just don't count gift certificates

    function count_contents_virtual() {  // get total number of items in cart disregard gift vouchers
      $total_items = 0;
      if (is_array($this->contents)) {
        reset($this->contents);
        while (list($products_id, ) = each($this->contents)) {
          $no_count = false;
          $gv_query = tep_db_query("select products_model from " . TABLE_PRODUCTS . " where products_id = '" . $products_id . "'");
          $gv_result = tep_db_fetch_array($gv_query);
          if (ereg('^GIFT', $gv_result['products_model'])) {
            $no_count=true;
          }
          if (NO_COUNT_ZERO_WEIGHT == 1) {
            $gv_query = tep_db_query("select products_weight from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($products_id) . "'");
            $gv_result=tep_db_fetch_array($gv_query);
            if ($gv_result['products_weight']<=MINIMUM_WEIGHT) {
              $no_count=true;
            }
          }
          if (!$no_count) $total_items += $this->get_quantity($products_id);
        }
      }
      return $total_items;
    }
// ------------------------ ICWILSON CREDIT CLASS Gift Voucher Addittion-------------------------------End

	function check_orders_id($orders_id,$events_id){
    	global $cart;
        if ($cart->count_contents()<=0) return false;
        
		reset($cart->contents);
		$found=false;
        while (list($products_id, ) = each($cart->contents)) {
			if ($products_id==$events_id && $cart->contents[$products_id]['old_orders_id']==$orders_id){
	     		$found=true;
	     		break;
	  		}
		}
		return $found;
	}
	function check_forced_items_purchased()
	{
		global $cart;
		
		if($cart->count_contents()<=0) return false;
		$product_id_list=$cart->get_check_id_list();
		$product_id_list=',' . $product_id_list		 . ',';
		$missed_items=false;
		reset($this->contents);
		while (list($products_id, ) = each($this->contents)) {
			$forced_ids=$this->contents[$products_id]["forced_item_ids"];
			if ($forced_ids!=""){
				$prefix=$this->contents[$products_id]["element_type"];
				$forced_item_array=array($forced_ids);
				
				for ($icnt=0;$icnt<count($forced_item_array);$icnt++){
					if(strpos($product_id_list, "," . $prefix . $forced_item_array[$icnt] . ",")===false){
						$missed_items=true;
						break 2;
					}
				}
			}
		}
		return $missed_items;
	}
	
	function check_stored_subscription_purchased() //added by sobi
	{
		global $cart,$customer_id;
		
		if($cart->count_contents()<=0) return 0;
		$also_purchased=0;
		 $subs_query=tep_db_query("select sc.subscription_categories_id as cat_id,s.subscription_id as id from " .TABLE_SUBSCRIPTIONS ." s," . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " sc where s.subscription_id=sc.subscription_id and  s.subscription_type='M'");
		if(tep_db_num_rows($subs_query)>0)
		{
				$row=tep_db_fetch_array($subs_query);
				$subscription_id=$row['id'];
 				if(tep_session_is_registered('customer_id'))
					 {
					 	$order_query=tep_db_query("select o.orders_id from " .TABLE_ORDERS_PRODUCTS ." op," . TABLE_ORDERS . " o where op.orders_id=o.orders_id and o.customers_id='" . $customer_id . "' and  op.products_id='" . $subscription_id."' and op.products_type='S'");
						if(tep_db_num_rows($order_query)>0)  //already purchase the stored subscription
							$also_purchased=1;//already purchased
					}
				
				reset($this->contents);
				$item_exists=false;
				while (list($products_id, ) = each($this->contents)) {
					if($this->contents[$products_id]['element_type']=='V' || $this->contents[$products_id]['element_type']=='E')
						$item_exists=true;
					$item_id=str_replace("S",'',$products_id);
					if($this->contents[$products_id]["element_type"]=='S' && $item_id==$subscription_id) //purchased
					{
						if($also_purchased==1)
							$also_purchased=3;//already purchased & available in cart
						else	
							$also_purchased=2;//available in cart 
					}
				}
				if($also_purchased==0 && $item_exists)
					$also_purchased=4;// not yet purchased stored subscription
		}//echo $also_purchased;
		return $also_purchased;
	}

	function get_check_id_list() {
		$product_id_list = '';
		if (is_array($this->contents)) {
			reset($this->contents);
			while (list($products_id, ) = each($this->contents)) {
				if ($this->contents[$products_id]['element_type']=='E')
					$product_id_list .= ',P' . substr($products_id,1);
				else if ( $this->contents[$products_id]['element_type']=='S')
					$product_id_list .= ',S' . substr($products_id,1);
				else if ( $this->contents[$products_id]['element_type']=='V')
					$product_id_list .= ',V' . tep_get_service_prid($products_id);
				else
					$product_id_list .= ',P' . tep_get_prid($products_id);
			}
		}
		return substr($product_id_list, 1);
	}
	// multiple attendees
	function get_max_attendees(){
		if (is_array($this->contents)) {
		 reset($this->contents);
			while (list($products_id, ) = each($this->contents)) {
				if ($this->contents[$products_id]["element_type"]=="E" && $this->contents[$products_id]["qty"]>1)
					return $this->contents[$products_id]["qty"];
			}
		}
		return -1;
	}
	function set_attendees($attendees){
		$this->attendees=$attendees;
		if (tep_session_is_registered("customer_id")){
			$this->save_attendees();
		}
	}
	function save_attendees(){
		global $customer_id,$HTTP_SESSION_VARS;
		$attendees=$this->attendees;
		
		tep_db_query("DELETE from " . TABLE_CUSTOMERS_BASKET_ATTENDEES . " where customers_id='" .  (int)$customer_id . "'");
		
		if($HTTP_SESSION_VARS['not_customer']){
				$customer_attendee_query=tep_db_query("select  c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_email_address,a.entry_postcode,a.entry_street_address,a.entry_city,a.entry_zone_id,a.entry_country_id from ".TABLE_CUSTOMERS ." c, ". TABLE_ADDRESS_BOOK ." a  where c.customers_id='" . (int)$customer_id ."' and c.customers_id=a.customers_id");
			if(tep_db_num_rows($customer_attendee_query)){
				$customer_attendee = tep_db_fetch_array($customer_attendee_query);
				$attendees[0]=array(
								"first_name"=>$customer_attendee['customers_firstname'],
								"last_name"=>$customer_attendee['customers_lastname'],
								"email_address"=>$customer_attendee['customers_email_address'],
								"street_address"=>$customer_attendee['entry_street_address'],
								"city"=>$customer_attendee['entry_city'],
								"postcode"=>$customer_attendee['entry_postcode'],
								"state"=>tep_get_zone_name($customer_attendee['entry_country_id'],$customer_attendee['entry_zone_id'],STORE_ZONE),
								"country"=>$customer_attendee['entry_country_id'],
								"attendee" =>0);
			}
			$HTTP_SESSION_VARS['not_customer']=false;
			tep_session_unregister('not_customer');
		}
		for ($icnt=0;$icnt<count($attendees);$icnt++){ 
				$attendees[$icnt]["customers_id"]=$customer_id;
				tep_db_perform(TABLE_CUSTOMERS_BASKET_ATTENDEES,$attendees[$icnt]);
			}
		
	}
	function get_attendees(){
		global $customer_id;
		$query=tep_db_query("SELECT * from " . TABLE_CUSTOMERS_BASKET_ATTENDEES . " where customers_id='" .  (int)$customer_id . "'");
		$attendees=array();
		if (tep_db_num_rows($query)>0){
			while($result=tep_db_fetch_array($query)){
				$attendees[]=$result;
			}
			$this->attendees=$attendees;
		}
	}
	function get_attendee_names($break='<br>'){
		$result="";
		$attendees=$this->attendees;
		for ($icnt=0;$icnt<count($attendees);$icnt++){
			$result.=$attendees[$icnt]["first_name"] . ' ' . $attendees[$icnt]["last_name"] . $break;
		}
		return $result;
	}
	// multiple attendees
}
?>
