<?php
/*
 * @package		Easyway Shop 5.5
 * @copyright	Copyright (C) 2005 - 2012 TA-EDV
 * @license		proprietary
 * @author		Richard Kammermayer <rk@ta-edv.de>,
 * 				John T. Daly <jd@ta-edv.de>
 * 
 * Easyway Shop is a web e-commerce system
 */

include_once('./core/shoppingcart.class.php');

class website_shoppingcart {


	private $base_object;
	private $layout_object;
	private $item_object;


	public function __construct($base_object, $layout_object) {
		$this->base_object = $base_object;
		$this->layout_object = $layout_object;
		$this->item_object = new Item($base_object);
		$this->shoppingcart_object = new Shoppingcart($base_object);
	}


	function run() {
		$action = '';
		
		if (isset($_POST['update_item']) && $_POST['update_item']) {
			$action = 'update_shoppingcart';
		} elseif (isset($_POST['amount']) && $_POST['amount']) {
			$action = 'add_item';
		}
		
		if ($action == 'update_shoppingcart') {
			$this->update_shoppingcart();
		} elseif ($action == 'add_item') {
			$this->add_item();
		}
			
		return $this->show_shoppingcart();
	} // end run


	private function show_shoppingcart() {
		if (isset($_POST['customer_info'])) {
			$_SESSION['customer_info'] = $_POST['customer_info'];
		}
		
		if (isset($_SESSION['customer_info']) && $_SESSION['customer_info']) {
			$this->layout_object->assign('customer_info', $_SESSION['customer_info']);
		}
		
		$data = $this->shoppingcart_object->get_data();
		
		$this->layout_object->assign('shoppingcart', $data);
		$this->layout_object->assign('shoppingcartVATUsage', $this->base_object->customer_group->show_tax);
		
		return $this->layout_object->_fetch('content_shoppingcart.tpl');
	} // end show_shoppingcart


	private function update_shoppingcart() {
		foreach ($_POST['update_item'] as $item => $quantity) {
			if ($quantity > 0) {
				$this->shoppingcart_object->update($item, $quantity);
			} else {
				$this->shoppingcart_object->remove($item);
			}
		}
	} // end update_shoppingcart


	private function add_item() {
		$this->shoppingcart_object->add($_POST['item_id'], $_POST['amount'], $_POST['variant'][1], $_POST['variant'][2]);
		$multiplier = 1;
		if ($this->item_object->is_combination_item()) {
			$multiplier = (int)$_POST['amount'];
		}
			
		if (is_array($_POST['additionalItems'])) {
			foreach ($_POST['additionalItems'] as $addItem) {
				if (is_array($addItem)) {
					$this->shoppingcart_object->add($addItem['id'], ((int)$_POST['amount'] * $multiplier), $addItem['variant_1'], $addItem['variant_2']);
				} else {
					$this->shoppingcart_object->add($addItem, 1);
				}
			}
		}
	} // end add_item


} // end website_shoppingcart

/* EOF */