<?php 
final class Cart {
  	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() {
		$product_data = array();

    	foreach ($this->session->data['cart'] as $key => $quantity) {
      		$product = explode(':', $key);
      		$product_id = $product[0];
			$stock = true;

			// Options
      		if (isset($product[1])) {
        		$options = unserialize(base64_decode($product[1]));
      		} else {
        		$options = array();
      		}
			
      		$product_query = $this->db->query("SELECT *,pd.optionname as optionnamefinal FROM " . DB_PREFIX . "product_vw p LEFT JOIN " . DB_PREFIX . "product_description_vw 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();
/*      
      			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_vw 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_vw 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_vw 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_vw 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_vw 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
				$query = $this->db->query("SELECT points FROM " . DB_PREFIX . "product_reward_vw WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "'");
				
				if ($query->num_rows) {	
					$reward1 = $query->row['points'];
				} else {
					$reward1 = 0;
				}
				$query = $this->db->query("SELECT p.price FROM " . DB_PREFIX . "product_reward_vw pr," . DB_PREFIX . "product p WHERE p.product_id = pr.product_id AND p.product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "'");
				
				if ($query->num_rows) {	
					$reward = $query->row['price'];
				} else {
					$reward = 0;
				}
*/		
				$reward = 0;
				$reward1 = 0;
				
				// Downloads		
				$download_data = array();     		
/*				
				$download_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_download_vw 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;
				}

//New Codes Starts Here	
/*
				$prdprice=0;
				$metal_weight = 0;
				$product_metal_weight = $this->db->query("SELECT sum(weight) as weight FROM " . DB_PREFIX . "product_metalcontent_vw WHERE product_id = '" . (int)$product_id . "' ");
				if ($product_metal_weight->num_rows) {
					$metal_weight = $product_metal_weight->row['weight'];
				}

				$gem_weight = 0;
				$laboursettingcost = 0;
				$product_gem_weight = $this->db->query("SELECT sum(a.weight * a.count) as weight, sum(b.cost * a.count) as laboursettingcost,a.* FROM " . DB_PREFIX . "product_gemcontent_vw a,laboursettingcost b WHERE a.setting_id=b.setting_id and product_id = '" . (int)$product_id . "' ");
				if ($product_gem_weight->num_rows) {
					$gem_weight = $product_gem_weight->row['weight'];
					$laboursettingcost = $product_gem_weight->row['laboursettingcost'];
				}
				
				$product_weight = $metal_weight + $gem_weight;

				$labour_weight_cost = 0;
				$product_weight_cost = $this->db->query("SELECT cost FROM " . DB_PREFIX . "labour_weight_based_costs WHERE low_weight >= ". $product_weight  ."	and high_weight < " . $product_weight );
				if ($product_weight_cost->num_rows) {
					$labour_weight_cost = $product_weight_cost->row['cost'] * $product_weight;
				}
								
				if(isset($product_query->row['overriding_mark_up_ubsolute']) && $product_query->row['overriding_mark_up_ubsolute'] !=0 ){

					$prdprice=$product_query->row['overriding_mark_up_ubsolute'];
					
				}else{
					
					$prdprice=0;
					$prdprice += $laboursettingcost;
					$prdprice += $labour_weight_cost;
					$prdprice += $prdprice * $product_query->row['product_id'];
					$prdprice += $prdprice * $product_query->row['overriding_markup_percentage'];
					$prdprice += 20 ; // Shipping Cost
					$prdprice += 30 ; // Packaging Cost
				
				}
//New Codes Ends Here
				$comments = '<br>     - Labour Setting Cost '. $laboursettingcost;
				$comments .= '<br>     - Labour Weight Cost '. $labour_weight_cost;
				$comments .= '<br>     - Labour Setting Cost'. $laboursettingcost;
				$comments .= '<br>     - Shipping Cost 20$' ;
				$comments .= '<br>     - Packaging Cost 30$';
				*/
				
				if(isset($this->session->data[$key.'_country'])){
					$country=$this->session->data[$key.'_country'];
				}else{
					$this->session->data[$key.'_country'] = 'AUS';
					$country='AUS';
				}
				if(isset($this->session->data[$key.'_ringsize'])){
					$ringsize=$this->session->data[$key.'_ringsize'];
				}else{
					$this->session->data[$key.'_ringsize'] = 'bbbb';
					$ringsize='bbbb';
				}
	
				if(isset($this->session->data[$key.'_engravetxt'])){
					$engravetxt=$this->session->data[$key.'_engravetxt'];
				}else{
					$this->session->data[$key.'_engravetxt'] = '';
					$engravetxt='';
				}
				if(isset($this->session->data[$key.'_engravefont'])){
					$engravefont=$this->session->data[$key.'_engravefont'];
				}else{
					$this->session->data[$key.'_engravefont'] = '';
					$engravefont='';
				}
				$gem_query = "";
				$gemsArray = "";
				$gem_query = $this->db->query("select * FROM product_gemavail pga WHERE pga.rapnet = 1 and pga.product_id = '" . $product_query->row['parent_product_id'] . "'");
				if ($gem_query->num_rows) { 
					$x=$gem_query->num_rows;
					foreach ($gem_query->rows as $gem_row) 
					{
					if(isset($this->session->data[ 'LotNo-' . $product_query->row['parent_product_id'] . '-' . $gem_row['product_gemavail_id'] ])){
							$pos = strpos($product_query->row['image'], $gem_row['product_gemavail_id'] );
							if ($pos === false) {	} else {
//								$this->log->write(" In Shopping Cart - LotNo " . $gem_row['product_id'] . ' = ' . $gem_row['product_gemavail_id'] . " For " . $this->session->data[ 'LotNo-' . $gem_row['product_id'] . '-' . $gem_row['product_gemavail_id']]);
//								echo " Let No " . $gem_row['product_id'] . ' = ' . $gem_row['product_gemavail_id'] . " For " . $this->session->data[ 'LotNo-' . $product_query->row['parent_product_id'] . '-' . $gem_row['product_gemavail_id']];
								$gemsArray .= $gem_row['gem'] . ":" . $gem_row['product_gemavail_id'] . ":" . $this->session->data[ 'LotNo-' . $product_query->row['parent_product_id'] . '-' . $gem_row['product_gemavail_id']] . ";";
							}
						}
					}
				}
//				echo $gemsArray . "<br>";
//echo $product_query->row['name'].$product_query->row['optionnamefinal'];
				

      			$product_data[$key] = array(
        			'key'             => $key,
        			'product_id'      => $product_query->row['product_id'],
        			'parent_product_id'      => $product_query->row['parent_product_id'],
        			'image'      	  => $product_query->row['parent_product_id'],
        			//'name'            => $product_query->row['name'].$comments, 
        			'name'            => $product_query->row['name'],
        			'type'            => $product_query->row['type'],
        			'optionname'      => $product_query->row['optionname'], 
        			'model'           => $product_query->row['model'],
					'shipping'        => $product_query->row['shipping'],
        			'image'           => $product_query->row['image'],
        			'option'          => $option_data,
					'download'        => $download_data,
        			'quantity'        => $quantity,
					'gemsArray'       => $gemsArray,
        			'country'         => $country,
        			'ringsize'        => $ringsize,
        			'minimum'         => $product_query->row['minimum'],
        			'engrave'         => $product_query->row['engrave'],
        			'engravetxt'      => $engravetxt,
        			'engravefont'     => $engravefont,
        			'svgContents'     => $product_query->row['svgContents'],
					'engravePrd'     => $product_query->row['engravePrd'],					
					'subtract'        => $product_query->row['subtract'],
					'stock'           => $stock,
	      			'price'           => ($price + $option_price) ,
//        			'price'           => ($prdprice + $option_price) ,
	     			'total'           => ($price + $option_price) * $quantity ,
//	      			'total'           => ($prdprice + $option_price) * $quantity ,
					'reward'          => $reward * $quantity,
					//'points'          => ($product_query->row['points'] + $option_points) * $quantity,
					'points'          => ($product_query->row['price'] + $option_points) * $quantity,
					'tax_class_id'    => $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']					
      			);
			} else {
				$this->remove($key);
			}
    	}
			 			
		return $product_data;
  	}
		  
  	public function add($product_id, $qty = 1,$size, $options = array()) {
    	if (!$options) {
      		$key = (int)$product_id;
    	} else {
      		$key = (int)$product_id . ':' . base64_encode(serialize($options));
    	}
		
			if (!isset($this->session->data['size'][$key])) {
      			$this->session->data['size'][$key] = (int)$size;
    		}
    	
		if ((int)$qty && ((int)$qty > 0)) {
    		if (!isset($this->session->data['cart'][$key])) {
      			$this->session->data['cart'][$key] = (int)$qty;
    		} else {
      			$this->session->data['cart'][$key] += (int)$qty;
    		}
		}
  	}

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

  	public function updateCountry($key, $country) { 

      	$this->session->data['cart'][$key] = $country;
  	}

  	public function updateRingSize($key, $size) {
      	$this->session->data['cart'][$key]['ringsize'] = $size;
  	}

  	public function remove($key) {
		if (isset($this->session->data['cart'][$key])) {
     		unset($this->session->data['cart'][$key]);
  		}
	}
	
  	public function clear() {
		$this->session->data['cart'] = 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['total'], $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'];
					} else {
						$tax_data[$tax_rate['tax_rate_id']] += $tax_rate['amount'];
					}
				}
			}
		}
		
		return $tax_data;
  	}

	public function getTaxesTotal() {
		$tax_data = array();
		$tax_total = 0;
		foreach ($this->getProducts() as $product) {
			if ($product['tax_class_id']) {
				$tax_rates = $this->tax->getRates($product['total'], $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'];						
					} else {
						$tax_data[$tax_rate['tax_rate_id']] += $tax_rate['amount'];
					}
					$tax_total += $tax_rate['amount'];
				}
			}
		}
		
		return $tax_total;
  	}
  	public function getTotal() {
		$total = 0;
		
		foreach ($this->getProducts() as $product) {
			$total += $this->tax->calculate($product['total'], $product['tax_class_id'], $this->config->get('config_tax'));
		}

		return $total;
  	}
  	
	public function getTotalRewardPoints() {
		$total = 0;
		
		foreach ($this->getProducts() as $product) {
			$total += $product['reward'];
		}

		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 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;
	}	
}
?>