<?php
/*
 * @version			$Id: index.php 10381 2008-06-01 03:35:53Z $
 * @package			Carteasy
 * @copyright		Copyright (C) 2005 - 2011 Wlanium
 * @license			proprietary
 * @author			Thomas Bartelt
 * Carteasy is a web shop system
 */

include_once './core/item.class.php';

class Shoppingcart {

	private $base_object;
	private $db;
	private $customer_object;
	private $item_object;

	function __construct($base_object) {
		$this->base_object = $base_object;
		$this->db = $base_object->db;
		$this->customer_object = $base_object->customer;
		$this->item_object = new Item($base_object);
	} // end __construct

	function add($item_id, $quantity, $variant1 = false, $variant2 = false, $quantity_replace = false) {
		if (!is_numeric($quantity) || $quantity < 0) {
			$quantity = 1;
		}

		if ($item_id) {
			$sql = "
				SELECT
					quantity
				FROM
					shopping_cart_items
				WHERE
					session_id = '".$this->db->real_escape_string(session_id())."'
				AND
					item_id = '".$this->db->real_escape_string($item_id)."'
				AND
					variant_1 = '".$this->db->real_escape_string($variant1)."'
				AND
					variant_2 = '".$this->db->real_escape_string($variant2)."'
				AND
					stamp = ''
			";

			$oldQuantity = $this->db->query($sql)->fetch_object()->quantity;

			if (is_numeric($quantity_replace)) {
				$quantity = $quantity_replace;
			} else {
				$quantity += $oldQuantity;
			}

			// Statistics
			if (empty($oldQuantity)) $oldQuantity = 0;
			$sqlStat = "
				UPDATE
					items
				SET
					added2cart = added2cart + ".$this->db->real_escape_string($quantity)." - ".$oldQuantity."
				WHERE
					id = '".$this->db->real_escape_string($item_id)."'
			";
			$this->db->query($sqlStat);

			// Calculation
			$this->item_object->id = $item_id;
			$item = $this->item_object->get_data($this->base_object->customer_group->id);

			$prices = $this->item_object->calculate_prices($item, $quantity, $variant1, $variant2);

			if ($this->base_object->config->shopConfiguration['save_customer_shoppingcart'] == 1 && $this->customer_object->id) {
				$sql = "
					REPLACE INTO
						shopping_cart_items (
							session_id,
							item_id,
							variant_1,
							variant_2,
							quantity,
							price_sum_net,
							price_sum_gross,
							stamp,
							date_added,
							customer_id
						)
					VALUES (
						'".$this->db->real_escape_string(session_id())."',
						'".$this->db->real_escape_string($item_id)."',
						'".$this->db->real_escape_string($variant1)."',
						'".$this->db->real_escape_string($variant2)."',
						'".$this->db->real_escape_string($quantity)."',
						'".$this->db->real_escape_string($prices['itemPriceNet'] * $quantity)."',
						'".$this->db->real_escape_string($prices['itemPriceGross'] * $quantity)."',
						'',
						NOW(),".
						$this->db->real_escape_string($this->customer_object->id)."
					)
				";
			} else {
				$sql = "
					REPLACE INTO
						shopping_cart_items (
							session_id,
							item_id,
							variant_1,
							variant_2,
							quantity,
							price_sum_net,
							price_sum_gross,
							stamp,
							date_added
						)
					VALUES (
						'".$this->db->real_escape_string(session_id())."',
						'".$this->db->real_escape_string($item_id)."',
						'".$this->db->real_escape_string($variant1)."',
						'".$this->db->real_escape_string($variant2)."',
						'".$this->db->real_escape_string($quantity)."',
						'".$this->db->real_escape_string($prices['itemPriceNet'] * $quantity)."',
						'".$this->db->real_escape_string($prices['itemPriceGross'] * $quantity)."',
						'',
						NOW()
					)
				";
			}
			$this->db->query($sql);
		}

		return;
	} // end add


	public function get_overview() {
		$sql = "
			SELECT
				SUM(price_sum_net) AS sumNet,
				SUM(price_sum_gross) AS sumGross,
				SUM(quantity) AS amount_sum,
				COUNT(1) AS different_amount_sum
			FROM
				shopping_cart_items
			WHERE
				session_id = '".$this->db->real_escape_string(session_id())."'
		";
		$data = $this->db->query($sql)->fetch_array();

		if ($this->base_object->customer_group->show_tax) {
			$data['price_sum'] = $data['sumGross'];
		} else {
			$data['price_sum'] = $data['sumNet'];
		}
		$data['price_tax_text'] = $this->base_object->customer_group->price_tax_text;

		return $data;
	} // end get_overview


	function get_data() {
		if ($this->base_object->customer_group->id) {
			$customer_group_id = $this->base_object->customer_group->id;
		} else {
			$customer_group_id = $this->base_object->customer_group->id = 1;
		}

		$tax_rate_object = new Tax($this->base_object);
		$tax_rates = $tax_rate_object->get_all();

		$data = array(
			'amount_sum' => 0,
			'price_sum_net' => 0,
			'price_sum_gross' => 0,
			'shown_price_sum' => 0,
			'tax_values' => array()
		);

		$sql = "
			SELECT
				sc.shopping_cart_item_id,
				sc.item_id,
				sc.parent_item_id,
				sc.stamp,
				sc.variant_1,
				sc.variant_2,
				sc.quantity,
				sc.price_sum_gross,
				sc.price_sum_net,
				sc.user_data,
				i.*,
				iav.item_number
			FROM
				item_attribute_variants iav
			RIGHT JOIN
				shopping_cart_items sc
			ON
				iav.item_id = sc.item_id
			AND
				iav.attribut1 = sc.variant_1
			AND
				iav.attribut2 = sc.variant_2
			LEFT JOIN
				items i
			ON
				i.id = sc.item_id
			WHERE
				sc.session_id = '".$this->db->real_escape_string(session_id())."'
			GROUP BY
				sc.shopping_cart_item_id
		";

		// TODO: group by is a dirty fix, i don't understand how this error comes to be

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

		$parents = array();
		$children = array();

		$data['item_weight'] = 0;
		$data['bulk_goods'] = 0;
		$data['standard_shipping_items'] = 0;
		if (is_object($rs) && $rs->num_rows > 0) {
			while ($obj = $rs->fetch_object()) {
				// THIS IS UGLY, THERE SHOULD BE A NICER WAY TO CALC THE PRICE
				$this->item_object->id = $obj->item_id;
				$item = $this->item_object->get_data($customer_group_id);
				$obj->calculatedPrices = $this->item_object->calculate_prices($item, $obj->quantity, $obj->variant_1, $obj->variant_2);

				if ($obj->parent_item_id == 0) {
					$obj->children = array();
					$parents[] = $obj;
				} else {
					$children[] = $obj;
				}

				// for shipping calculation
				if ($obj->shipping_cost_type == 0) {
					$data['item_weight'] += $obj->quantity * $obj->shipping_weight;
				}
				if ($obj->shipping_cost_type == 0 && $obj->shipping_item_type == 1) {
					$data['bulk_goods'] += $obj->quantity;
				}
				if ($obj->shipping_cost_type == 0) {
					$data['standard_shipping_items'] += $obj->quantity;
				}

				// for the footer
				$data['amount_sum'] += $obj->quantity;
				$data['price_sum_net'] += round($obj->calculatedPrices['itemPriceNet'] * $obj->quantity, 2);
				$data['price_sum_gross'] += round($obj->calculatedPrices['itemPriceGross'] * $obj->quantity, 2);

				$tax_rate = $tax_rates[$obj->tax_id]->steuersatz;

				if (isset($data['tax_values'][$tax_rate])) {
					$data['tax_values'][$tax_rate]['gross'] += round($obj->calculatedPrices['itemPriceGross'] * $obj->quantity, 2);
					$data['tax_values'][$tax_rate]['net'] += round($obj->calculatedPrices['itemPriceNet'] * $obj->quantity, 2);
					$data['tax_values'][$tax_rate]['vat'] += round(($obj->calculatedPrices['itemPriceGross'] - $obj->calculatedPrices['itemPriceNet']) * $obj->quantity, 2);

					if ($this->base_object->customer_group->show_tax) {
						$data['tax_values'][$tax_rate]['show'] += $data['tax_values'][$tax_rate]['gross'];
					} else {
						$data['tax_values'][$tax_rate]['show'] += $data['tax_values'][$tax_rate]['net'];
					}
				} else {
					$data['tax_values'][$tax_rate] = array();

					$data['tax_values'][$tax_rate]['gross'] = round($obj->calculatedPrices['itemPriceGross'] * $obj->quantity, 2);
					$data['tax_values'][$tax_rate]['net'] = round($obj->calculatedPrices['itemPriceNet'] * $obj->quantity, 2);
					$data['tax_values'][$tax_rate]['vat'] = round(($obj->calculatedPrices['itemPriceGross'] - $obj->calculatedPrices['itemPriceNet']) * $obj->quantity, 2);

					if ($this->base_object->customer_group->show_tax) {
						$data['tax_values'][$tax_rate]['show'] = $data['tax_values'][$tax_rate]['gross'];
					} else {
						$data['tax_values'][$tax_rate]['show'] = $data['tax_values'][$tax_rate]['net'];
					}
				}

				if ($this->base_object->customer_group->show_tax) {
					$data['shown_price_sum'] = $data['price_sum_gross'];
				} else {
					$data['shown_price_sum'] = $data['price_sum_net'];
				}
			}

			foreach ($children as $child) {
				foreach ($parents as $key => $parent) {
					if ($parent->stamp == $child->stamp) {
						$parents[$key]->children[] = $child;
					}
				}
			}
		}

		$data['items'] = $parents;
		$data['price_tax_text'] = $this->base_object->customer_group->price_tax_text;

		return $data;
	} // end get_data


	// TODO: is this still being used?
	function cartid2array($id) {
		$a_array = explode("__variant__",$id);
		$split_id = array(
			'id' => array_shift($a_array)
		);

		if ($a_array) {
			foreach ($a_array as $variant) {
				$item = explode("__value__",$variant);
				$split_id['variant'][] = array(
				'key'   =>$item[0],
				'value' =>$item[1]
				);
			}
		}

		return $split_id;
	} // end cartid2array


	function update($id, $quantity) {
		$sql = "SELECT * FROM shopping_cart_items
				WHERE shopping_cart_item_id = ".$this->db->real_escape_string($id)." AND stamp = ''";

		if ($this->db->query($sql)->num_rows) {
			// not a combi item
			$sql = "UPDATE shopping_cart_items SET quantity = ".$this->db->real_escape_string($quantity)."
					WHERE shopping_cart_item_id = ".$this->db->real_escape_string($id);
		} else {
			$sql = "UPDATE shopping_cart_items sci2 
					RIGHT JOIN shopping_cart_items sci1 ON sci2.stamp = sci1.stamp
					SET sci2.quantity = ".$this->db->real_escape_string($quantity)."
					WHERE sci1.shopping_cart_item_id = ".$this->db->real_escape_string($id);
		}

		return $this->db->query($sql);
	} // end update


	function remove($id) {
		$sql = "SELECT * FROM shopping_cart_items 
				WHERE shopping_cart_item_id = ".$this->db->real_escape_string($id)." AND stamp != ''";

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

		if ($rs->num_rows == 0) {
			// not a combi item
			$sql = "DELETE FROM shopping_cart_items
					WHERE shopping_cart_item_id = ".$this->db->real_escape_string($id);
		} else {
			$sql = "DELETE FROM shopping_cart_items
					WHERE stamp = '".$rs->fetch_object()->stamp."'";
		}

		return $this->db->query($sql);
	} // end remove


	function clear($all = false) {
		if (!$all && $this->base_object->config->shopConfiguration['save_customer_shoppingcart'] == 1) {
			$sql = "
				DELETE FROM
					shopping_cart_items
				WHERE
					(session_id = '".$this->db->real_escape_string(session_id())."'
				OR
					DATEDIFF(NOW(), date_added) > 2)
				AND customer_id = 0;";
		} else {
			$sql = "
				DELETE FROM
					shopping_cart_items
				WHERE
					session_id = '".$this->db->real_escape_string(session_id())."'
				OR
					DATEDIFF(NOW(), date_added) > 2";
		}
		$this->db->query($sql);

		return;
	} // end clear


	function check_memorize($article_id) {
		if (isset($_SESSION['easyshop']['article_memorize'][$article_id])) {
			return 1;
		}

		return 0;
	} // end check_memorize


	public function has_items() {
		$sql = "SELECT * FROM shopping_carts 
				WHERE session_id = '".$this->db->real_escape_string(session_id())."'";

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

		if ($result->num_rows > 0) {
			return true;
		}

		return false;
	} // end check_memorize


	function update_customer_cart() {
		// set new session_id for old saved items
		$sql = "UPDATE shopping_cart_items
				SET session_id = '".$this->db->real_escape_string(session_id())."'
				WHERE customer_id=".$this->db->real_escape_string($this->customer_object->id);
		$rs = $this->db->query($sql);

		// set customer id vor new saved items
		$sql = "UPDATE shopping_cart_items
				SET customer_id=".$this->db->real_escape_string($this->customer_object->id)."
				WHERE session_id = '".$this->db->real_escape_string(session_id())."'";
		$rs = $this->db->query($sql);

		return false;
	}

} //end Shoppingcart
