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

include_once './core/item.class.php';
include_once './core/structure.class.php';
include_once './core/shoppingcart.class.php';
include_once './core/config.class.php';
include_once './core/memory.class.php';
include_once './core/itemhelper.class.php';
include_once './core/customer_group.class.php';
include_once './core/cs_ticket.class.php';
include_once './core/shop_klarna.class.php';

class website_item {
	
	private $base_object;
	private $layout_object;
	private $item_object;
	private $structure_object;
	private $shoppingcart_object;
	
	public $item_data;
	
	private $klarna_variant;
	private $klarna_accessories;
	
	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->structure_object = new Structure($base_object);
		$this->shoppingcart_object = new Shoppingcart($base_object);
	}

	function run($item_id) {
		$customer_id = $this->base_object->customer->customer_id;
		if ($customer_id) {
			$not_logged_in = false;
		} else {
			$not_logged_in = true;
		}
		$this->layout_object->assign('not_logged_in', $not_logged_in);
		
		if (isset($_POST['create_opinion']) && $_POST['create_opinion']) {
			$this->item_object->create_opinion(
				array(
					'item_id' => $item_id,
					'rang' => $_POST['rang'],
					'opinion_text' => $_POST['opinion_text'],
					'user_id' => $this->base_object->customer->id,
					'user_name' =>  $this->base_object->customer->firstname.' '.substr($this->base_object->customer->surname,0,1).' aus '.$this->base_object->customer->default_address_city
				)
			);

		}
		
		if (isset($_POST['amount']) && $_POST['amount']) { 
			$this->add_item_to_shopingcart($item_id);
		}
		
		if (isset($_POST['memorize'])) {
			$this->add_item_to_memory($item_id);
		}
		
		if (isset($_POST['request_price_info'])) {
			$this->send_request_price_info($item_id);
		}
		
		if (isset($_GET['action'])) {
			$action = $_GET['action'];
		} else {
			$action = false;
		}
		
		$this->lock_shoppingcart();
		
		if ($action == 'get_variant_price') {
			$this->get_variant_price($item_id);
		} elseif ($action == 'print') {
			$this->item_print($item_id);
		} elseif ($action == 'get_variant_data') {
			$this->get_variant_data($item_id);
		} elseif ($action == 'get_images') {
			$this->get_images($item_id);
		} else {
			return $this->item_view($item_id);
		}
	}
	
	private function lock_shoppingcart() {
		if (isset($this->base_object->config->shopConfiguration['lock_shoppingcart']) && $this->base_object->config->shopConfiguration['lock_shoppingcart']) {
			if ($this->shoppingcart_object->has_items()) {
				$this->layout_object->assign('lock_shoppingcart', true);
			}
		}
	}
	
	private function send_request_price_info($item_id) {
		$cs_ticket_objet = new Cs_ticket($this->base_object);
		
		$title = "Preisanfrage von " . $_POST['request_name_field'] . "<" . $_POST['request_email_field'] . ">";
		$message = "Name: " . $_POST['request_name_field'] . "\n";
		$message .= "E-Mail: " . $_POST['request_email_field'] . "\n";
		$message .= "Telefon: " . $_POST['request_telephone_field'] . "\n";
		$message .= "Artikel: " . $_POST['request_item_name'] . "\n";
		$message .= "Artikel-Nr.: " . $_POST['request_item_number'] . "\n";
		$message .= "Nachricht: \n" . $_POST['request_message_field'];
		
		$this->layout_object->assign('price_info_request_was_sent', true);
	}
	
	private function add_item_to_shopingcart($item_id) {
		if (isset($_POST['is_combination']) && $_POST['is_combination'] == 'yes') {
			$stamp = uniqid();
			
			$this->shoppingcart_object->add_combi($item_id, $_POST['amount'], $_POST['variant'][1], $_POST['variant'][2], false, false, false, $stamp);
			$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)) {
						
						$user_data = false;
						if (isset($addItem['user_data']) && $addItem['user_data'] != '') {
							$user_data = $addItem['user_data'];
						}
						
						$this->shoppingcart_object->add_combi($addItem['id'], ((int)$_POST['amount'] * $multiplier), $addItem['variant_1'], $addItem['variant_2'], false, $item_id, $user_data, $stamp);
					} else {
						$this->shoppingcart_object->add_combi($addItem, 1);
					}
				}
			}
			
			$this->layout_object->assign('itemAddedToCart', true);
		} else {
			$this->shoppingcart_object->add($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);
					}
				}
			}
			
			$this->layout_object->assign('itemAddedToCart', true);
		}
	}
	
	private function add_item_to_memory($item_id) {
		$memory_object = new Memory();
		$memory_object->add($item_id);
	}
	
	private function get_variant_price($item_id) {
		$group_id = ($this->base_object->customer_group->adaptPricesFromId != 0) ? $this->base_object->customer_group->adaptPricesFromId : $this->base_object->customer_group->id;
		$taxrate = ItemHelper::get_item_taxrate($item_id);
		$data = ItemHelper::get_item_variant_prices($item_id, $group_id, $taxrate);
		$data = $data[$_POST['data'][0]][$_POST['data'][1]];
		
		$tax_type = Customer_group::get_taxation_type($this->base_object->customer_group->id);
		
		if ($tax_type == 1) {
			$data['price'] = $data['priceGross'];
		}
			
		$data['price'] = number_format($data['price'], 2, ',', ' ');
		
		echo json_encode($data);
		exit();
	}
	
	private function klarna_installments($price) {
		$klarna_object = new Shop_klarna($this->base_object);
		return $klarna_object->get_installments($price);
	}
	
	private function klarna_installments_for_variants($data) {
		$this->klarna_variant = array();

		foreach ($data as $level_one_key => $level_one_data) {
			foreach ($level_one_data as $level_two_key => $level_two_data) {
				$klarna_data = $this->klarna_installments($level_two_data['priceGross']);
				$this->klarna_variant[$level_one_key][$level_two_key] = $klarna_data; 
			}
		}

		$this->layout_object->assign('klarna_variants', json_encode($this->klarna_variant));
	}
	
	private function klarna_installments_for_accessories($data) {
		$this->klarna_accessories = array();

		foreach ($data as $item) {
			$this->klarna_accessories[$item->id] = $this->klarna_installments($item->shop_price_1);
		}

		$this->layout_object->assign('klarna_accessories', json_encode($this->klarna_accessories));
	}
	
	private function item_view($item_id) {
		// get item data
		$this->item_object->set_id($item_id);
		$this->item_data = $this->item_object->get_data($this->base_object->customer_group->id);
		$this->item_data->opinion = $this->item_object->get_opinion_list($this->item_data->id);
		$this->item_data->avg_opinion = $this->item_object->get_avg_opinion($this->item_data->id);
		
		// overwrite shippable
		if ($this->item_data->inventory > 0) {
			$this->item_data->shippable = $this->item_data->shippable_inventory;
		}
		
		// overwrite files with parent files, for variants
		if (isset($this->item_data->parent_files)) {
			$this->item_data->files = $this->item_data->parent_files;
		}
		
		// overwrite assigned items with parent assigend items, for variants
		if (isset($this->item_data->parent_assignedItemSet)) {
			$this->item_data->assignedItemSet = $this->item_data->parent_assignedItemSet;
		}
		
		$images = array() ;
		$documents = array();
		foreach ($this->item_data->files as $file) {
			if ($file->type == 0) {
				$images[] = $file;
			}
			else {
				$documents[] = $file;
			}
		}
		
		// default image 
		if (!$images) {
			$file = new stdClass;
			$file->file_name = 'default_image.png';
			$images[] = $file;
		}
		
		$this->item_data->files = $images;
		$this->item_data->documents = $documents;

		// klarna
		if ((isset($this->base_object->config->shopConfiguration['klarna_eid']) && 
			$this->base_object->config->shopConfiguration['klarna_eid'] != '') && 
			(isset($this->base_object->config->shopConfiguration['klarna_secret']) && 
			$this->base_object->config->shopConfiguration['klarna_secret'] != ''))
		{
			$klarna_installments = $this->klarna_installments($this->item_data->price_1_tax);
			$this->layout_object->assign('klarna_installments', $klarna_installments);
			
			if ($this->item_data->schema_data->selectable_attribute_1 > 0) {
				$this->klarna_installments_for_variants($this->item_data->variant_data);
			}
			
			if (count($this->item_data->assignedItemSet) > 0) {
				$this->klarna_installments_for_accessories($this->item_data->assignedItemSet);
			}
		}
		
		$this->layout_object->assign('shopArticle', $this->item_data);
		$all_structurepath = $this->structure_object->get_all_tree_full_path(1);
		// get structure data
		//$structure_data = $this->structure_object->get_data($this->item_data->structure_id);
		//echo var_dump($this->structure_object->get_all_item_categories());
		$sd = $this->item_object->getStructureAssignment();
		$structure_data = array();
		foreach ($sd as $key => $value) {
			$structure = $this->structure_object->get_data($key);
			if ($structure) {
				$structure->name = $all_structurepath[$structure->id]->path_name.'-&gt'.$structure->name;
				if ($structure->id == $this->item_data->structure_id) {
					$this->item_data->main_structure_uri_path = $all_structurepath[$structure->id]->uri_path.'/'.$structure->short_uri;
				}
				if ($structure->active == 1) {
					$structure_data[] = $structure;
				}
			}
		}

		$this->structure_data = $structure_data;
		$this->layout_object->assign('structure_data', $structure_data);
		
		// get countries
		include_once './core/countryhelper.class.php';
		$countries = CountryHelper::get_delivery_and_shipping_info_for_all_countries();
		$this->layout_object->assign('countries', $countries);
		
		if (isset($_GET['opinion_show']) && $_GET['opinion_show']) {
			$this->layout_object->assign('opinion_show', true);
		}
		
		return $this->layout_object->_fetch('content_item.tpl');
	}
	
	private function item_print($item_id) {
		// get item data
		$this->item_object->set_id($item_id);
		$this->item_data = $this->item_object->get_data($this->base_object->customer_group->id);

		$images = array() ;
		$documents = array();
		foreach ($this->item_data->files as $file) {
			if ($file->type == 0) {
				$images[] = $file;
			}
			else {
				$documents[] = $file;
			}
		}

		// default image 
		if (!$images) {
			$file = new stdClass;
			$file->file_name = 'default_image.png';
			$images[] = $file;
		}
		
		$this->item_data->files = $images;
                
		$this->layout_object->assign('shopArticle', $this->item_data);
		
		// we asign the structure data to another variable in the website init, it never gets called if we call this module
		// get structure data
		$this->layout_object->assign('current_menu_id', $this->item_data->structure_id); // hack by jd for sh menu hack to work here too
		$structure_data = $this->structure_object->get_data($this->item_data->structure_id);
		$this->layout_object->assign('structure_data', $structure_data);
		
		echo $this->layout_object->_fetch('content_item_print.tpl');
		exit();
	}
	
	// copy of get_variant_prices
	private function get_variant_data($item_id) {
		$group_id = ($this->base_object->customer_group->adaptPricesFromId != 0) ? $this->base_object->customer_group->adaptPricesFromId : $this->base_object->customer_group->id;
		$taxrate = ItemHelper::get_item_taxrate($item_id);

		$data = ItemHelper::get_item_variant_prices($item_id, $group_id, $taxrate);
		$data = $data[$_POST['data'][0]][$_POST['data'][1]];
	
		$tax_type = Customer_group::get_taxation_type($this->base_object->customer_group->id);
	
		if ($tax_type == 1) {
			$data['price'] = $data['priceGross'];
		}
			
		$data['price'] = number_format($data['price'], 2, ',', ' ');
		
		// end of c-n-p
		$image = ItemHelper::get_item_variant_image($item_id, $_POST['data'][0], $_POST['data'][1]);
		
		if ($image) {
			$data['image'] = $image;
		}
		
		echo json_encode($data);
		exit();
	}
	
	private function get_images($item_id) {
		$images = ItemHelper::get_additional_item_images($item_id);
		
		echo json_encode($images);
		exit();
	}
}
