<?php
class Cart {

        public function getGiftsSettings($group, $store_id) {
          $data = array(); 

          $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `group` = '" . $this->db->escape($group) . "'");

          foreach ($query->rows as $result) {
              if (!$result['serialized']) {
                $data[$result['key']] = $result['value'];
              } else {
                $data[$result['key']] = unserialize($result['value']);
              }
          }

          return $data;
        }

        public function restartGifts() {
          unset($this->session->data['gift_teaser_exclude']);
		  unset($this->session->data['gift_teaser_success']);
          $this->updateGifts();
        }

        public function updateGifts() {
          $setting = $this->getGiftsSettings('giftTeaser', $this->config->get('store_id'));

          if (empty($setting['giftTeaser']['Enabled']) || $setting['giftTeaser']['Enabled'] == 'no') return;

          $this->removeGifts();

          $gifts = $this->getAllGifts();
          $cart_products = array_map(create_function('$a', 'return $a["product_id"];'), $this->getProducts());

          if (empty($cart_products)) return;

          $eligible_gifts = array();
 		  $products = $this->getProducts();
		  
          foreach ($gifts as $gift) {
            $properties = unserialize($gift['condition_properties']);
            $to_add = null;
            $to_add_quantity = (int)$gift['minimum'];

            switch ($gift['condition_type']) {
              case '1' : {
                if ((int)$properties['total'] < $this->getTotal() && (int)$properties['total_max'] > $this->getTotal()) {
                  $to_add = $gift['product_id'];
                }

              } break;

             case '2' : {
				$eligible_products = array_intersect($properties['certain'], $cart_products);
				$add_gift= array();
				if(isset($eligible_products)) {
					foreach($eligible_products as $eligible_product) {
						unset($quantity);
						$quantity=array();
						foreach($products as $key => $value) {
							 $exp_key = explode(':', $key);
							 if($exp_key[0] == $eligible_product){
								 $quantity[] = $value['quantity'];
							}
						}
						if(count($quantity) > 1 ) {
							$quantity = array_sum($quantity);
						} else {
							$quantity = $quantity[0];
						}
						
						if($quantity >= $properties['certain_product_quantity'] ) {
							$add_gift[] = 'true';
						} else {
							$add_gift[] = 'false';
						}
					} 
				}
				if (in_array("false", $add_gift)) {
    				$quantity_reached = false;
				} else {
					$quantity_reached = true;
				}

                if (
                  isset($properties['certain']) &&
                  array_values(array_intersect($properties['certain'], $cart_products)) === array_values($properties['certain']) &&
				  $quantity_reached
                ) {
                  $to_add = $gift['product_id'];
				
                }

              } break;

              case '3' : {
                $eligible_products = array_intersect($properties['some'], $cart_products);
				$add_gift= array();
				foreach($eligible_products as $eligible_product) {
					unset($quantity);
					$quantity=array();
					foreach($products as $key => $value) {
							 $exp_key = explode(':', $key);
							 if($exp_key[0] == $eligible_product){
								 $quantity[] = $value['quantity'];
							}
						}
						if(count($quantity) > 1 ) {
							$quantity = array_sum($quantity);
						} else {
							$quantity = $quantity[0];
						}
						
						if($quantity >= $properties['some_product_quantity'] ) {
						$add_gift[] = 'true';
					} else {
						$add_gift[] = 'false';
					}
				} 
				if (in_array("true", $add_gift)) {
    				$quantity_reached = true;
				} else {
					$quantity_reached = false;
				}
				if (
                  isset($properties['some']) &&
                  count(array_intersect($properties['some'], $cart_products)) &&
				  $quantity_reached 
                ) { 
                  $to_add = $gift['product_id'];
                }

              } break; 

              case '4' : {
                if (
                  isset($properties['categories']) &&
                  $this->categoriesHaveProducts($properties['categories'], $cart_products)
                ) {
                  $to_add = $gift['product_id'];
                }

              } break;

            }

            if (
              !empty($this->session->data['gift_teaser_exclude']) && 
              in_array($to_add, $this->session->data['gift_teaser_exclude'])
            ) {
              continue;
            }
			
            if (!empty($to_add)) {
              for ($i = 0; $i < $to_add_quantity; $i++) {
                $eligible_gifts[] = $to_add;
              }
            }
          }

          $option_key = 'gift_teaser';

           foreach ($eligible_gifts as $eligible_gift) {
            $product_options = $this->db->query("SELECT po.product_id, po.option_value_id as option_index, ovp.name FROM `". DB_PREFIX . "product_option_value` po LEFT JOIN `" . DB_PREFIX . "option_value_description` ovp ON (po.option_value_id = ovp.option_value_id) WHERE po.product_id=".(int)$eligible_gift)->rows;
            if(!empty($product_options)) {
                continue;
            }
            
            $key = (int)$eligible_gift . ':';
            $key .= base64_encode(serialize($option_key)) . ':';
 
            
			if ($this->config->get('config_auction_status_id') && is_array($this->config->get('config_auction_status_id'))) {
				$auction_status_ids = $this->config->get('config_auction_status_id');
			} else {
				$auction_status_ids = array('starting' => 1, 'relisting' => 2, 'inprogress' => 3, 'extended' => 4, 'won' => 5, 'expired' => 6, 'sold' => 7, 'voided' => 8);
			}
			if (!is_null($this->config->get('config_auction_normal_sales'))) {
				$normal_sales = (int)$this->config->get('config_auction_normal_sales');
			} else {
				$normal_sales = 0;
			}
			$auction_query = $this->db->query("SELECT a.auction_id FROM " . DB_PREFIX . "auction a INNER JOIN " . DB_PREFIX . "product_auction pa ON (a.product_auction_id = pa.product_auction_id) WHERE pa.product_id = '" . (int)$product_id . "' AND a.auction_status_id IN ('" . (int)$auction_status_ids['inprogress'] . "', '" . (int)$auction_status_ids['extended'] . "')");
			if (!empty($option) && is_int($option) && !is_array($option)) {
				$this->session->data['cart'][$key] = (int)$qty;		// option is an auction_id, this key is a won-auction
			} elseif (!$normal_sales && $auction_query->num_rows) {
				$this->remove($key);								// add-to-cart not allowed if live auction exists
			} elseif (!isset($this->session->data['cart'][$key])) {
			
              $this->session->data['cart'][$key] = 1;
            } else {
              $this->session->data['cart'][$key] += 1;
            }
          }
        }
		
 		 public function removeGifts() {
          foreach ($this->getProducts() as $key => $val) {
            if (!empty($val['gift_teaser'])) {
 
              if(empty($val['option'])) {
                  if (isset($this->session->data['cart'][$key])) {
                    unset($this->session->data['cart'][$key]);
                    $this->data = array();
                  }
              }
            }
          }
        }

        public function getAllGifts() {
          $sql = "SELECT *, gt.description AS description FROM `". DB_PREFIX . "gift_teaser` gt LEFT JOIN `" . DB_PREFIX . "product` p ON (gt.item_id = p.product_id) LEFT JOIN `" . DB_PREFIX . "product_description` pd ON (p.product_id = pd.product_id) WHERE gt.start_date < " . time() . " AND gt.end_date > " . time() ." AND gt.store_id = '" . $this->config->get('store_id') . "' AND language_id = '" . $this->config->get('config_language_id') . "' ORDER BY gt.sort_order ASC";

          $result = $this->db->query($sql);

          return $result->rows;
        }

        public function categoriesHaveProducts($category_ids, $product_ids) {
          $sql = "SELECT COUNT(*) as count FROM `" . DB_PREFIX . "product_to_category` WHERE category_id IN (" . implode(',', $category_ids) . ") AND product_id IN (" . implode(',', $product_ids) . ")";

          $result = $this->db->query($sql);

          return (int)$result->row['count'] > 0;
        }
      
	private $config;
	private $db;
	private $data = array();
	private $data_recurring = array();

  	public function __construct($registry) {
		$this->config = $registry->get('config');
		$this->customer = $registry->get('customer');
		$this->session = $registry->get('session');
		$this->db = $registry->get('db');
		$this->tax = $registry->get('tax');
		$this->weight = $registry->get('weight');

		if (!isset($this->session->data['cart']) || !is_array($this->session->data['cart'])) {
      		$this->session->data['cart'] = array();
    	}
	}
	      
  	public function getProducts() {
		if (!$this->data) {
			foreach ($this->session->data['cart'] as $key => $quantity) {
				$product = explode(':', $key);
				$product_id = $product[0];
				$stock = true;
	

			// Auction
			if (!empty($product[1]) && is_int(unserialize(base64_decode($product[1]))) && !is_array(unserialize(base64_decode($product[1])))) {
				$auction_id = (int)unserialize(base64_decode($product[1]));
				$product[1] = NULL;
			} else {
				$auction_id = 0;
			}
			
				// Options
				if (!empty($product[1])) {
					$options = unserialize(base64_decode($product[1]));
				} else {
					$options = array();
				} 
                
                // Profile
                
                if (!empty($product[2])) {
                    $profile_id = $product[2];
                } else {
                    $profile_id = 0;
                }
				
				$product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE p.product_id = '" . (int)$product_id . "' AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p.date_available <= NOW() AND p.status = '1'");
				
				if ($product_query->num_rows) {
					$option_price = 0;
					$option_points = 0;
					$option_weight = 0;
	
					$option_data = array();
	

         if (is_string($options)) {
          $gift_teaser = true;
          $options = array();
        } else {
          // GiftTeaser
                if (!empty($product[2]) && unserialize(base64_decode($product[2])) == "gift_teaser") {
                    $gift_teaser = true;
                } else {
                    $gift_teaser = false;
                } 
        }
      
					foreach ($options as $product_option_id => $option_value) {
						$option_query = $this->db->query("SELECT po.product_option_id, po.option_id, od.name, o.type FROM " . DB_PREFIX . "product_option po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE po.product_option_id = '" . (int)$product_option_id . "' AND po.product_id = '" . (int)$product_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "'");
						
						if ($option_query->num_rows) {
							if ($option_query->row['type'] == 'select' || $option_query->row['type'] == 'radio' || $option_query->row['type'] == 'image') {
								$option_value_query = $this->db->query("SELECT pov.option_value_id, ovd.name, pov.quantity, pov.subtract, pov.price, pov.price_prefix, pov.points, pov.points_prefix, pov.weight, pov.weight_prefix FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_option_value_id = '" . (int)$option_value . "' AND pov.product_option_id = '" . (int)$product_option_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
								
								if ($option_value_query->num_rows) {
									if ($option_value_query->row['price_prefix'] == '+') {
										$option_price += $option_value_query->row['price'];
									} elseif ($option_value_query->row['price_prefix'] == '-') {
										$option_price -= $option_value_query->row['price'];
									}
	
									if ($option_value_query->row['points_prefix'] == '+') {
										$option_points += $option_value_query->row['points'];
									} elseif ($option_value_query->row['points_prefix'] == '-') {
										$option_points -= $option_value_query->row['points'];
									}
																
									if ($option_value_query->row['weight_prefix'] == '+') {
										$option_weight += $option_value_query->row['weight'];
									} elseif ($option_value_query->row['weight_prefix'] == '-') {
										$option_weight -= $option_value_query->row['weight'];
									}
									
									if ($option_value_query->row['subtract'] && (!$option_value_query->row['quantity'] || ($option_value_query->row['quantity'] < $quantity))) {
										$stock = false;
									}
									
									$option_data[] = array(
										'product_option_id'       => $product_option_id,
										'product_option_value_id' => $option_value,
										'option_id'               => $option_query->row['option_id'],
										'option_value_id'         => $option_value_query->row['option_value_id'],
										'name'                    => $option_query->row['name'],
										'option_value'            => $option_value_query->row['name'],
										'type'                    => $option_query->row['type'],
										'quantity'                => $option_value_query->row['quantity'],
										'subtract'                => $option_value_query->row['subtract'],
										'price'                   => $option_value_query->row['price'],
										'price_prefix'            => $option_value_query->row['price_prefix'],
										'points'                  => $option_value_query->row['points'],
										'points_prefix'           => $option_value_query->row['points_prefix'],									
										'weight'                  => $option_value_query->row['weight'],
										'weight_prefix'           => $option_value_query->row['weight_prefix']
									);								
								}
							} elseif ($option_query->row['type'] == 'checkbox' && is_array($option_value)) {
								foreach ($option_value as $product_option_value_id) {
									$option_value_query = $this->db->query("SELECT pov.option_value_id, ovd.name, pov.quantity, pov.subtract, pov.price, pov.price_prefix, pov.points, pov.points_prefix, pov.weight, pov.weight_prefix FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_option_value_id = '" . (int)$product_option_value_id . "' AND pov.product_option_id = '" . (int)$product_option_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
									
									if ($option_value_query->num_rows) {
										if ($option_value_query->row['price_prefix'] == '+') {
											$option_price += $option_value_query->row['price'];
										} elseif ($option_value_query->row['price_prefix'] == '-') {
											$option_price -= $option_value_query->row['price'];
										}
	
										if ($option_value_query->row['points_prefix'] == '+') {
											$option_points += $option_value_query->row['points'];
										} elseif ($option_value_query->row['points_prefix'] == '-') {
											$option_points -= $option_value_query->row['points'];
										}
																	
										if ($option_value_query->row['weight_prefix'] == '+') {
											$option_weight += $option_value_query->row['weight'];
										} elseif ($option_value_query->row['weight_prefix'] == '-') {
											$option_weight -= $option_value_query->row['weight'];
										}
										
										if ($option_value_query->row['subtract'] && (!$option_value_query->row['quantity'] || ($option_value_query->row['quantity'] < $quantity))) {
											$stock = false;
										}
										
										$option_data[] = array(
											'product_option_id'       => $product_option_id,
											'product_option_value_id' => $product_option_value_id,
											'option_id'               => $option_query->row['option_id'],
											'option_value_id'         => $option_value_query->row['option_value_id'],
											'name'                    => $option_query->row['name'],
											'option_value'            => $option_value_query->row['name'],
											'type'                    => $option_query->row['type'],
											'quantity'                => $option_value_query->row['quantity'],
											'subtract'                => $option_value_query->row['subtract'],
											'price'                   => $option_value_query->row['price'],
											'price_prefix'            => $option_value_query->row['price_prefix'],
											'points'                  => $option_value_query->row['points'],
											'points_prefix'           => $option_value_query->row['points_prefix'],
											'weight'                  => $option_value_query->row['weight'],
											'weight_prefix'           => $option_value_query->row['weight_prefix']
										);								
									}
								}						
							} elseif ($option_query->row['type'] == 'text' || $option_query->row['type'] == 'textarea' || $option_query->row['type'] == 'file' || $option_query->row['type'] == 'date' || $option_query->row['type'] == 'datetime' || $option_query->row['type'] == 'time') {
								$option_data[] = array(
									'product_option_id'       => $product_option_id,
									'product_option_value_id' => '',
									'option_id'               => $option_query->row['option_id'],
									'option_value_id'         => '',
									'name'                    => $option_query->row['name'],
									'option_value'            => $option_value,
									'type'                    => $option_query->row['type'],
									'quantity'                => '',
									'subtract'                => '',
									'price'                   => '',
									'price_prefix'            => '',
									'points'                  => '',
									'points_prefix'           => '',								
									'weight'                  => '',
									'weight_prefix'           => ''
								);						
							}
						}
					} 
				
					if ($this->customer->isLogged()) {
						$customer_group_id = $this->customer->getCustomerGroupId();
					} else {
						$customer_group_id = $this->config->get('config_customer_group_id');
					}
					
					$price = $product_query->row['price'];
					
					// Product Discounts
					$discount_quantity = 0;
					
					foreach ($this->session->data['cart'] as $key_2 => $quantity_2) {
						$product_2 = explode(':', $key_2);
						
						if ($product_2[0] == $product_id) {
							$discount_quantity += $quantity_2;
						}
					}
					
					$product_discount_query = $this->db->query("SELECT price FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "' AND quantity <= '" . (int)$discount_quantity . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY quantity DESC, priority ASC, price ASC LIMIT 1");
					
					if ($product_discount_query->num_rows) {
						$price = $product_discount_query->row['price'];
					}
					
					// Product Specials
					$product_special_query = $this->db->query("SELECT price FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY priority ASC, price ASC LIMIT 1");
				
					if ($product_special_query->num_rows) {
						$price = $product_special_query->row['price'];
					}						
			
					// Reward Points
					$product_reward_query = $this->db->query("SELECT points FROM " . DB_PREFIX . "product_reward WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "'");
					
					if ($product_reward_query->num_rows) {	
						$reward = $product_reward_query->row['points'];
					} else {
						$reward = 0;
					}
					
					// Downloads		
					$download_data = array();     		
					
					$download_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_download p2d LEFT JOIN " . DB_PREFIX . "download d ON (p2d.download_id = d.download_id) LEFT JOIN " . DB_PREFIX . "download_description dd ON (d.download_id = dd.download_id) WHERE p2d.product_id = '" . (int)$product_id . "' AND dd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
				
					foreach ($download_query->rows as $download) {
						$download_data[] = array(
							'download_id' => $download['download_id'],
							'name'        => $download['name'],
							'filename'    => $download['filename'],
							'mask'        => $download['mask'],
							'remaining'   => $download['remaining']
						);
					}
					
					// Stock
					if (!$product_query->row['quantity'] || ($product_query->row['quantity'] < $quantity)) {
						$stock = false;
					}
                    
                    $recurring = false;
                    $recurring_frequency = 0;
                    $recurring_price = 0;
                    $recurring_cycle = 0;
                    $recurring_duration = 0;
                    $recurring_trial_status = 0;
                    $recurring_trial_price = 0;
                    $recurring_trial_cycle = 0;
                    $recurring_trial_duration = 0;
                    $recurring_trial_frequency = 0;
                    $profile_name = '';
                    
                    if ($profile_id) {
                        $profile_info = $this->db->query("SELECT * FROM `" . DB_PREFIX . "profile` `p` JOIN `" . DB_PREFIX . "product_profile` `pp` ON `pp`.`profile_id` = `p`.`profile_id` AND `pp`.`product_id` = " . (int) $product_query->row['product_id'] . " JOIN `" . DB_PREFIX . "profile_description` `pd` ON `pd`.`profile_id` = `p`.`profile_id` AND `pd`.`language_id` = " . (int) $this->config->get('config_language_id') . " WHERE `pp`.`profile_id` = " . (int) $profile_id . " AND `status` = 1 AND `pp`.`customer_group_id` = " . (int) $customer_group_id)->row;
                        
                        if ($profile_info) {
                            $profile_name = $profile_info['name'];
                            
                            $recurring = true;
                            $recurring_frequency = $profile_info['frequency'];
                            $recurring_price = $profile_info['price'];
                            $recurring_cycle = $profile_info['cycle'];
                            $recurring_duration = $profile_info['duration'];
                            $recurring_trial_frequency = $profile_info['trial_frequency'];
                            $recurring_trial_status = $profile_info['trial_status'];
                            $recurring_trial_price = $profile_info['trial_price'];
                            $recurring_trial_cycle = $profile_info['trial_cycle'];
                            $recurring_trial_duration = $profile_info['trial_duration'];
                        }
                    }
					

			$price = ($price + $option_price);
			$total = ($price + $option_price) * $quantity;
			$minimum = $product_query->row['minimum'];
			$subtract = $product_query->row['subtract'];
			// Product Auction
			if ($this->config->get('config_auction_status_id') && is_array($this->config->get('config_auction_status_id'))) {
				$auction_status_ids = $this->config->get('config_auction_status_id');
			} else {
				$auction_status_ids = array('starting' => 1, 'relisting' => 2, 'inprogress' => 3, 'extended' => 4, 'won' => 5, 'expired' => 6, 'sold' => 7, 'voided' => 8);
			}
			if ($auction_id) {
				$product_auction_query = $this->db->query("SELECT a.highest_bid_amount FROM " . DB_PREFIX . "auction a INNER JOIN " . DB_PREFIX . "product_auction pa ON (a.product_auction_id = pa.product_auction_id) WHERE pa.product_id = '" . (int)$product_id . "' AND a.auction_id = '" . (int)$auction_id . "' AND auction_status_id = '" . $auction_status_ids['won'] . "'");
				if ($product_auction_query->num_rows) {
					$price = (float)(string)((float)$product_auction_query->row['highest_bid_amount'] / (int)$quantity);
					$total = (float)$product_auction_query->row['highest_bid_amount'];
					$stock = true;		// auctions already deducted reserved quantity from stock, therefore stock check is not required
					$minimum = 0;		// auctions already deducted reserved quantity from stock, therefore mininum is not applicable
					$subtract = 0;		// auctions already deducted reserved quantity from stock, therefore subtract is not required
				}
			}
			
					$this->data[$key] = array(
						'key'                       => $key,
						'product_id'                => $product_query->row['product_id'],

        'gift_teaser' => $gift_teaser,
      
						'name'                      => $product_query->row['name'],
						'model'                     => $product_query->row['model'],
						'shipping'                  => $product_query->row['shipping'],
						'image'                     => $product_query->row['image'],

			'auction_id'      => $auction_id,
			
						'option'                    => $option_data,
						'download'                  => $download_data,
						'quantity'                  => $quantity,
						'minimum'                   => $minimum,
						'subtract'                  => $subtract,
						'stock'                     => $stock,
						
		'real_price'                     => $price,
        'price'                     => ($gift_teaser==true) ? '0' : ($price + $option_price),
      
						
	  	'total'                     => ($gift_teaser==true) ? '0' : ($price + $option_price) * $quantity,
      
						'reward'                    => $reward * $quantity,
						'points'                    => ($product_query->row['points'] ? ($product_query->row['points'] + $option_points) * $quantity : 0),
						
	 	'real_tax_class_id'              =>  $product_query->row['tax_class_id'],
	  	'tax_class_id'              =>  ($gift_teaser==true) ? '0' : $product_query->row['tax_class_id'],
      
						'weight'                    => ($product_query->row['weight'] + $option_weight) * $quantity,
						'weight_class_id'           => $product_query->row['weight_class_id'],
						'length'                    => $product_query->row['length'],
						'width'                     => $product_query->row['width'],
						'height'                    => $product_query->row['height'],
						'length_class_id'           => $product_query->row['length_class_id'],
                        'profile_id'                => $profile_id,
                        'profile_name'              => $profile_name,
                        'recurring'                 => $recurring,
                        'recurring_frequency'       => $recurring_frequency,
                        'recurring_price'           => $recurring_price,
                        'recurring_cycle'           => $recurring_cycle,
                        'recurring_duration'        => $recurring_duration,
                        'recurring_trial'           => $recurring_trial_status,
                        'recurring_trial_frequency' => $recurring_trial_frequency,
                        'recurring_trial_price'     => $recurring_trial_price,
                        'recurring_trial_cycle'     => $recurring_trial_cycle,
                        'recurring_trial_duration'  => $recurring_trial_duration,
					);
				} else {
					$this->remove($key);
				}

			//Q: Coupon Free Product
			$this->data[$key]['cfp_total'] = $this->data[$key]['total'];
			
			}
		}


		// loop through the finished package and update cfp total if the correct coupon products exist or no coupon products are needed
		//Q: Coupon Free Product
		if (isset($this->session->data['coupon']) && isset($this->session->data['coupon_free'])) {
			
			$bFound = false;
			$coupon_product_info = $this->db->query("SELECT * FROM " . DB_PREFIX . "coupon_product cp LEFT JOIN " . DB_PREFIX . "coupon c ON (c.coupon_id = cp.coupon_id) WHERE c.code = '" . $this->session->data['coupon'] . "'");
			if ($coupon_product_info->num_rows) { // Check if certain coupon products required first

				// Get array of all coupon product product ids
				foreach ($coupon_product_info->rows as $coupon_products) {
					$xcoupon_products[] = $coupon_products['product_id'];
				}

				// If coupon products found, first check that the required item is in the cart
				foreach ($this->data as $key => $product) {
					$this->data[$key]['cfp_total'] = $product['total']; // reset the cpf_total
					if (in_array($product['product_id'], $xcoupon_products)) {
						$bFound = true;
					}
				}

				// if we found the necessary coupon product in the cart, update the free items with the new cfp_total
				if ($bFound) {
					foreach ($this->data as $key => $product) {
						$this->data[$key]['cfp_total'] = $product['total'];
						$free_product_code = $this->db->query("SELECT code FROM " . DB_PREFIX . "coupon c LEFT JOIN " . DB_PREFIX . "coupon_free_product cfp ON (c.coupon_id = cfp.coupon_id) WHERE cfp.product_id = '" . (int)$product['product_id'] . "'");
						if ($free_product_code->num_rows) {
							$free_product_code = $free_product_code->row['code'];
							//if ($this->session->data['coupon'] == $free_product_code) {
							if (strcasecmp($this->session->data['coupon'], $free_product_code) === 0) {
								$this->data[$key]['cfp_total'] -= $product['price'] * 1;
							}
						}
					}
				}

			} else {  // If no coupon products then just apply it.
				foreach ($this->data as $key => $product) {
					$this->data[$key]['cfp_total'] = $product['total'];
					$free_product_code = $this->db->query("SELECT code FROM " . DB_PREFIX . "coupon c LEFT JOIN " . DB_PREFIX . "coupon_free_product cfp ON (c.coupon_id = cfp.coupon_id) WHERE cfp.product_id = '" . (int)$product['product_id'] . "'");
					if ($free_product_code->num_rows) {
						$free_product_code = $free_product_code->row['code'];
						//if ($this->session->data['coupon'] == $free_product_code) {
						if (strcasecmp($this->session->data['coupon'], $free_product_code) === 0) {
							$this->data[$key]['cfp_total'] -= $product['price'] * 1;
						}
					}
				}
			}
		}//
			


        $setting = $this->getGiftsSettings('giftTeaser', $this->config->get('store_id'));

        if (!empty($setting['giftTeaser']['FreeGiftLabel'][$this->config->get('config_language_id')])) {
          $free_gift = $setting['giftTeaser']['FreeGiftLabel'][$this->config->get('config_language_id')];
        } else {
          $free_gift = '';
        }

        foreach ($this->data as &$product) {
          $product['name'] = !empty($free_gift) && !empty($product['gift_teaser']) && stripos($product['name'], $free_gift) === false ? $product['name'] . ' (' . trim($free_gift) . ')' : $product['name'];
        }
        
      
		return $this->data;
  	}

    public function getRecurringProducts(){
        $recurring_products = array();
        
        foreach ($this->getProducts() as $key => $value) {
            if ($value['recurring']) {
                $recurring_products[$key] = $value;
            }
        }
        
        return $recurring_products;
    }
		  
  	
        public function add($product_id, $qty = 1, $option, $profile_id = '', $gift = false) {
      
        $key = (int) $product_id . ':';
        
        if ($option) {
            $key .= base64_encode(serialize($option)) . ':';
        }  else {
            $key .= ':';
        }
        
        if ($profile_id) {
            $key .= (int) $profile_id;
        }

        if($gift ==  true) {
            $key .= base64_encode(serialize("gift_teaser"));
        }
      

        if ((int) $qty && ((int) $qty > 0)) {
            
			if ($this->config->get('config_auction_status_id') && is_array($this->config->get('config_auction_status_id'))) {
				$auction_status_ids = $this->config->get('config_auction_status_id');
			} else {
				$auction_status_ids = array('starting' => 1, 'relisting' => 2, 'inprogress' => 3, 'extended' => 4, 'won' => 5, 'expired' => 6, 'sold' => 7, 'voided' => 8);
			}
			if (!is_null($this->config->get('config_auction_normal_sales'))) {
				$normal_sales = (int)$this->config->get('config_auction_normal_sales');
			} else {
				$normal_sales = 0;
			}
			$auction_query = $this->db->query("SELECT a.auction_id FROM " . DB_PREFIX . "auction a INNER JOIN " . DB_PREFIX . "product_auction pa ON (a.product_auction_id = pa.product_auction_id) WHERE pa.product_id = '" . (int)$product_id . "' AND a.auction_status_id IN ('" . (int)$auction_status_ids['inprogress'] . "', '" . (int)$auction_status_ids['extended'] . "')");
			if (!empty($option) && is_int($option) && !is_array($option)) {
				$this->session->data['cart'][$key] = (int)$qty;		// option is an auction_id, this key is a won-auction
			} elseif (!$normal_sales && $auction_query->num_rows) {
				$this->remove($key);								// add-to-cart not allowed if live auction exists
			} elseif (!isset($this->session->data['cart'][$key])) {
			
                $this->session->data['cart'][$key] = (int) $qty;
            } else {
                $this->session->data['cart'][$key] += (int) $qty;
            }
        }

        $this->data = array();

        $this->updateGifts();
      
  	}

  	public function update($key, $qty) {
    	if ((int)$qty && ((int)$qty > 0)) {
      		$this->session->data['cart'][$key] = (int)$qty;
    	} else {
	  		$this->remove($key);
		}
		

        $this->updateGifts();
      
		$this->data = array();
  	}

  	public function remove($key) {

        $key_parts = explode(':', $key);
        if (!empty($key_parts[1])) {
          $key_option = unserialize(base64_decode($key_parts[1]));
          $key_product_id = $key_parts[0];

          if (empty($this->session->data['gift_teaser_exclude'])) {
            $this->session->data['gift_teaser_exclude'] = array();
          }

          if (!in_array($key_product_id, $this->session->data['gift_teaser_exclude']) && is_string($key_option) && $key_option == 'gift_teaser') {
            $this->session->data['gift_teaser_exclude'][] = $key_product_id;
          }
        }
      
		if (isset($this->session->data['cart'][$key])) {
     		unset($this->session->data['cart'][$key]);
  		}
		

        $this->updateGifts();
      
		$this->data = array();
	}
	
  	public function clear() {
		$this->session->data['cart'] = array();

        $this->updateGifts();
      
		$this->data = array();
  	}
	
  	public function getWeight() {
		$weight = 0;
	
    	foreach ($this->getProducts() as $product) {
			if ($product['shipping']) {
      			$weight += $this->weight->convert($product['weight'], $product['weight_class_id'], $this->config->get('config_weight_class_id'));
			}
		}
	
		return $weight;
	}
	
  	public function getSubTotal() {
		$total = 0;
		
		foreach ($this->getProducts() as $product) {
			$total += $product['total'];
		}

		return $total;
  	}
	
	public function getTaxes() {
		$tax_data = array();
		
		foreach ($this->getProducts() as $product) {
			if ($product['tax_class_id']) {
				$tax_rates = $this->tax->getRates($product['price'], $product['tax_class_id']);
				
				foreach ($tax_rates as $tax_rate) {
					if (!isset($tax_data[$tax_rate['tax_rate_id']])) {
						$tax_data[$tax_rate['tax_rate_id']] = ($tax_rate['amount'] * $product['quantity']);
					} else {
						$tax_data[$tax_rate['tax_rate_id']] += ($tax_rate['amount'] * $product['quantity']);
					}
				}
			}
		}
		
		return $tax_data;
  	}

  	public function getTotal() {
		$total = 0;
		
		foreach ($this->getProducts() as $product) {
			$total += $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'];
		}

		return $total;
  	}
	  	
  	public function countProducts() {
		$product_total = 0;
			
		$products = $this->getProducts();
			
		foreach ($products as $product) {
			$product_total += $product['quantity'];
		}		
					
		return $product_total;
	}
	  
  	public function hasProducts() {
    	return count($this->session->data['cart']);
  	}

    public function hasRecurringProducts(){
        return count($this->getRecurringProducts());
    }
  
  	public function hasStock() {
		$stock = true;
		
		foreach ($this->getProducts() as $product) {
			if (!$product['stock']) {
	    		$stock = false;
			}
		}
		
    	return $stock;
  	}
  
  	public function hasShipping() {
		$shipping = false;
		
		foreach ($this->getProducts() as $product) {
	  		if ($product['shipping']) {
	    		$shipping = true;
				
				break;
	  		}		
		}
		
		return $shipping;
	}
	
  	public function hasDownload() {
		$download = false;
		
		foreach ($this->getProducts() as $product) {
	  		if ($product['download']) {
	    		$download = true;
				
				break;
	  		}		
		}
		
		return $download;
	}	
}
?>