<?php
/* --------------------------------------------------------------
   $Id: order.php,v 1.1.1.1 2008/10/27 07:56:40 cvs Exp $

   XT-Commerce - community made shopping
   http://www.xt-commerce.com

   Copyright (c) 2003 XT-Commerce
   --------------------------------------------------------------
   based on:
   (c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
   (c) 2002-2003 osCommerce(order.php,v 1.6 2003/02/06); www.oscommerce.com
   (c) 2003	 nextcommerce (order.php,v 1.12 2003/08/18); www.nextcommerce.org

   Released under the GNU General Public License
   --------------------------------------------------------------
   Third Party contribution:

   Customers Status v3.x  (c) 2002-2003 Copyright Elari elari@free.fr | www.unlockgsm.com/dload-osc/ | CVS : http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/elari/?sortby=date#dirlist

   Credit Class/Gift Vouchers/Discount Coupons (Version 5.10)
   http://www.oscommerce.com/community/contributions,282
   Copyright (c) Strider | Strider@oscworks.com
   Copyright (c  Nick Stanko of UkiDev.com, nick@ukidev.com
   Copyright (c) Andre ambidex@gmx.net
   Copyright (c) 2001,2002 Ian C Wilson http://www.phesis.org

   Released under the GNU General Public License
   --------------------------------------------------------------*/

class order {
	var $info, $totals, $products, $customer, $delivery,$costs,$rueckerstattungen,$language_id,$editor_id,$serial_numbers;

	function order($order_id) {
		global $_SESSION;
		$this->language_id = 2;
		$this->info = array();
		$this->totals = array();
		$this->products = array();
		$this->customer = array();
		$this->delivery = array();
		$this->costs = array();
		$this->serial_numbers = array();
		$this->rueckerstattungen = array();
		$this->editor_id = $_SESSION['customer_id'];
		$this->query($order_id);	
	}

	function query($order_id) {
		$order_query = xtc_db_query("select *
                                  from " . TABLE_ORDERS . " o where
                                  orders_id = '" . xtc_db_input($order_id) . "'");

		$order = xtc_db_fetch_array($order_query);

		$totals_query = xtc_db_query("select * from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . xtc_db_input($order_id) . "' order by sort_order");
		while ($totals = xtc_db_fetch_array($totals_query)) {
			$this->totals[] = array('title' => $totals['title'],
                                'text' => $totals['text'],
                                'value' => $totals['value'],
                                'id' => $totals['orders_id'],
                                'otid' => $totals['orders_total_id'],
                                'class' => $totals['class']);
		}
      
		$costs_query = xtc_db_query("select * from costs where orders_id = '" . xtc_db_input($order_id) . "' order by date_created");
		while ($costs = xtc_db_fetch_array($costs_query)) {
			$this->costs[] = array('class' => $costs['class'],
				'reclamations_id'=>$costs['reclamations_id'],
				'customers_id'=>$costs['customers_id'],
				'comments'=>xtc_db_input($costs['comments']),
				'value'=>xtc_db_input($costs['value']),
				'date_created'=>$costs['date_created'],
				'editor_id'=>$costs['editor_id']
			);
		}
		
		$rueck_query = xtc_db_query("select * from rueckerstattungen where orders_id = '" . xtc_db_input($order_id) . "' order by date_created");
		while ($rueck = xtc_db_fetch_array($rueck_query)) {
			$this->rueckerstattungen[] = array('reclamations_id' => $rueck['reclamations_id'],
				'id'=>$rueck['rueckerstattungs_id'],
				'betrag'=>$rueck['betrag'],
				'paymode'=>$rueck['paymode'],
				'date_created'=>$rueck['date_created'],
				'date_payment'=>$rueck['date_payment'],
				'kto_nummer'=>$rueck['kto_nummer'],
				'kto_blz'=>$rueck['kto_blz'],
				'kto_inhaber'=>$rueck['kto_inhaber'],
				'kto_bank'=>$rueck['kto_bank'],
				'kto_grund'=>$rueck['kto_grund'],
				'kto_iban'=>$rueck['kto_iban'],
				'kto_swift'=>$rueck['kto_swift'],
				'comments'=>$rueck['comments'],
				'editor_id'=>$rueck['editor_id'],
				'status'=>$rueck['status'],
			);
		}
      
		$eb_query = xtc_db_query("SELECT customers_ebay_userid FROM customers WHERE customers_id='".$order['customers_id']."'");
		$eb = xtc_db_fetch_array($eb_query);
		$ebayuser = $eb['customers_ebay_userid'];

		$this->info = array('currency' => $order['currency'],
		  'currency_value' => $order['currency_value'],
		  'payment_method' => $order['payment_class'],
		  'status' => $order['customers_status'],
		  'status_name' => $order['customers_status_name'],
		  'status_image' => $order['customers_status_image'],
		  'status_discount' => $order['customers_status_discount'],
		  'cc_type' => $order['cc_type'],
		  'cc_owner' => $order['cc_owner'],
		  'cc_number' => $order['cc_number'],
		  'cc_expires' => $order['cc_expires'],
		  'comments' => $order['comments'],
		  'language' => $order['language'],
		  'date_purchased' => $order['date_purchased'],
		  'date_shipping' => $order['date_shipping'],
		  'orders_status' => $order['orders_status'],
		  'orders_status_name' => $this->get_status_name($order['orders_status']),
		  'id' => $order['orders_id'],

		  /* DAS ALTE KOMBINIEREN-HANDLING */
		  'is_parent' => $order['is_parent'],
		  'parent_orders_id' => $order['parent_orders_id'],

		  /* KOMBINIEREN-HISTORY */
		  'combined_orders_id'=>$order['combined_orders_id'],

		  'ebay_id'=>$order['ebay_id'],
		  'ebay_userid'=>$ebayuser,
		  'last_modified' => $order['last_modified'],
		  'date_payment' => $order['date_payment'],
		  'no_warning' => $order['no_warning'],
		  'versender' => $order['versender'],
		  'shipping_class' => $order['shipping_class'],
		  'shipping_method' => $order['shipping_method'],
		  'warning_span_date' => $order['warning_span_date'],
		  'warning_span' => $order['warning_span'],
		  'warning_status' => $order['warning_status'],
		  'block_shipping' => $order['block_shipping'],
		  'ebay_no_shippingaddress'=>$order['ebay_no_shippingaddress'],
		  'ebay_no_registrationaddress'=>$order['ebay_no_registrationaddress'],
		  'ebay_different_address'=>$order['ebay_different_address'],
		  'select_set'=>$order['select_set'],
		  'select_set_status'=>$order['select_set_status'],
		  'select_set_product_status'=>$order['select_set_product_status'],
		  'rueckstand'=>$order['rueckstand'],
		  'orders_split_id'=>$order['orders_split_id']
		);

      $this->customer = array('name' => $order['customers_name'],
			'company' => $order['customers_company'],
			'csID' => $order['customers_cid'],
			'vat_id' => $order['customers_vat_id'],
			'shop_id' => $order['shop_id'],
			'ID' => $order['customers_id'],
			'cIP' => $order['customers_ip'],
			'street_address' => $order['customers_street_address'],
			'suburb' => $order['customers_suburb'],
			'city' => $order['customers_city'],
			'postcode' => $order['customers_postcode'],
			'state' => $order['customers_state'],
			'country' => $order['customers_country'],
			'format_id' => $order['customers_address_format_id'],
			'telephone' => $order['customers_telephone'],
			'mobile' => $order['customers_mobile'],
			'email_address' => $order['customers_email_address']
		);

      // WE NEED THE COUNTRY ID
      $delivery_country_id_query = xtc_db_query("SELECT countries_id,countries_iso_code_2 FROM countries WHERE countries_name='".xtc_db_prepare_input($order['delivery_country'])."'");
      $delivery_country_id = xtc_db_fetch_array($delivery_country_id_query);

      $this->delivery = array('name' => $order['delivery_name'],
			'company' => $order['delivery_company'],
			'street_address' => $order['delivery_street_address'],
			'suburb' => $order['delivery_suburb'],
			'city' => $order['delivery_city'],
			'postcode' => $order['delivery_postcode'],
			'state' => $order['delivery_state'],
			'country' => $order['delivery_country'],
			'country_id' => $delivery_country_id['countries_id'],
			'iso_code_2' => $delivery_country_id['countries_iso_code_2'],
			'format_id' => $order['delivery_address_format_id']
		);

		$this->billing = array('name' => $order['billing_name'],
			'company' => $order['billing_company'],
			'street_address' => $order['billing_street_address'],
			'suburb' => $order['billing_suburb'],
			'city' => $order['billing_city'],
			'postcode' => $order['billing_postcode'],
			'state' => $order['billing_state'],
			'country' => $order['billing_country'],
			'format_id' => $order['billing_address_format_id']
		);

		$index = 0;
		if($order['is_parent'] == 'y') {
			$orders_products_query = xtc_db_query("select o.parent_orders_id,
                                                 p.orders_products_id,p.products_id, p.products_name, p.products_model, p.products_price, p.products_tax, p.products_quantity, p.final_price,p.allow_tax, p.products_discount_made
                                             from
                                                 " . TABLE_ORDERS_PRODUCTS . " p, " .TABLE_ORDERS. " o
                                             where
                                                 o.parent_orders_id=".$order_id." && p.orders_id=o.orders_id");
		}else{
			$orders_products_query = xtc_db_query("select
                                                 orders_products_id,products_id, products_name, products_model, products_price, products_tax, products_quantity, final_price,allow_tax, products_discount_made
                                             from
                                                 " . TABLE_ORDERS_PRODUCTS . "
                                             where
                                                 orders_id ='" . xtc_db_input($order_id) . "'");
		}

		while ($orders_products = xtc_db_fetch_array($orders_products_query)) {
			$this->products[$index] = array('qty' => $orders_products['products_quantity'],
				'opID'=> $orders_products['orders_products_id'],
				'name' => $orders_products['products_name'],
				'id' => $orders_products['products_id'],
				'model' => $orders_products['products_model'],
				'tax' => $orders_products['products_tax'],
				'price' => $orders_products['products_price'],
				'discount' => $orders_products['products_discount_made'],
				'final_price' => $orders_products['final_price'],
				'allow_tax' => $orders_products['allow_tax']
			);

			$subindex = 0;
			$attributes_query = xtc_db_query("select products_options, products_options_values, options_values_price, price_prefix from " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_id = '" . xtc_db_input($order_id) . "' and orders_products_id = '" . $orders_products['orders_products_id'] . "'");
			if (xtc_db_num_rows($attributes_query)) {
				while ($attributes = xtc_db_fetch_array($attributes_query)) {
					$this->products[$index]['attributes'][$subindex] = array('option' => $attributes['products_options'],
                                                                     'value' => $attributes['products_options_values'],
                                                                     'prefix' => $attributes['price_prefix'],
                                                                     'price' => $attributes['options_values_price']);

					$subindex++;
				}
			}
			$index++;
		}
	}

	function get_products_date_available(){
		$return_array = array();
		for($i=0;$i<sizeOf($this->products);$i++){
			$date_query = xtDBquery(sprintf("SELECT products_date_available FROM products WHERE products_id='%s' and products_date_available>now()",$this->products[$i]['id']));
			$date = xtc_db_fetch_array(&$date_query,true);
			if($date['products_date_available']){
				$return_array[$this->products[$i]['id']] = $date['products_date_available'];
			}
		}
		return $return_array;
	}

	function calculate( ) {
		$this->total = 0;
		$this->weight = 0;
		if (!is_array($this->products)) 
			return 0;
		reset($this->products);
		while (list($id, ) = each($this->products)) {
			if(!function_exists('xtc_get_ext_products_weight'))
				require(DIR_FS_INC.'xtc_get_ext_products_weight.inc.php');
			$weight = xtc_get_ext_products_weight($this->products[$id]['id']);
			$this->weight += ($this->products[$id]['qty'] * $weight);
		}
	}

	function count_contents() {  // get total number of items in cart 
   	$total_items = 0;
		if (is_array($this->products)) {
			reset($this->products);
			while (list($id, ) = each($this->products)) {
				$total_items += $this->get_quantity($id);
			}
		}
		return $total_items;
	}

	function show_weight() {
		$this->calculate();
		return $this->weight;
	}

	function get_quantity($id) {
		if (isset($this->products[$id])) {
			return $this->products[$id]['qty'];
		} else {
			return 0;
		}
	}
    
	function recalc(){
	
		$cinfo = xtc_oe_customer_infos($this->customer['ID']);
		$status_query = xtc_db_query("select customers_status_show_price_tax,customers_status_add_tax_ot from " . TABLE_CUSTOMERS_STATUS . " where customers_status_id = '" . $this->info['status'] . "'");
		$status = xtc_db_fetch_array($status_query);

		// Errechne neue Zwischensumme für die Bestellung Anfang
		if($this->info['is_parent'] == 'n') {
			$products_query = xtc_db_query("select SUM(final_price) as subtotal_final from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $this->info['id'] . "' ");
			$products = xtc_db_fetch_array($products_query);
			$subtotal_final = $products['subtotal_final'];
		}else{
			$products_query = xtc_db_query("select SUM(op.final_price) as subtotal_final from " . TABLE_ORDERS_PRODUCTS . " op, ".TABLE_ORDERS." o where o.parent_orders_id = '" . $this->info['id'] . "' && op.orders_id=o.orders_id");
			while( $products = xtc_db_fetch_array($products_query) ) {
				$subtotal_final += $products['subtotal_final'];
			}
		}
		//********************* COMBINED PAYMENT CHANGE
	
		$xtPrice = new xtcPrice($this->info['currency'],$this->info['status']);
	
		$subtotal_text = $xtPrice->xtcFormat($subtotal_final,true);

		xtc_db_query("update " . TABLE_ORDERS_TOTAL . " set text = '" . $subtotal_text . "', value = '" . $subtotal_final . "' where orders_id = '" . $this->info['id'] . "' and class = 'ot_subtotal' ");

		// Falls No Tax
		$check_no_tax_value_query = xtc_db_query("select count(*) as count from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $this->info['id'] . "' and class = 'ot_subtotal_no_tax'");
		$check_no_tax_value = xtc_db_fetch_array($check_no_tax_value_query);
		if ($check_no_tax_value_query['count'] != '0') {
			$subtotal_no_tax_value_query = xtc_db_query("select SUM(value) as subtotal_no_tax_value from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $this->info['id'] . "' and class != 'ot_tax' and class != 'ot_total' and class != 'ot_subtotal_no_tax' and class != 'ot_coupon' and class != 'ot_gv'");
			$subtotal_no_tax_value = xtc_db_fetch_array($subtotal_no_tax_value_query);
			$subtotal_no_tax_final = $subtotal_no_tax_value['subtotal_no_tax_value'];
			$subtotal_no_tax_text = $xtPrice->xtcFormat($subtotal_no_tax_final, true);
			xtc_db_query("update " . TABLE_ORDERS_TOTAL . " set text = '" . $subtotal_no_tax_text . "', value = '" . $subtotal_no_tax_final . "' where orders_id = '" . $this->info['id'] . "' and class = 'ot_subtotal_no_tax' ");
		}
		
		$subtotal_query = xtc_db_query("select SUM(value) as value from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $this->info['id'] . "' and class != 'ot_subtotal_no_tax' and class != 'ot_tax' and class != 'ot_subtotal'");
		$subtotal = xtc_db_fetch_array($subtotal_query);

		$subtotal_final = $subtotal['value'];
		$subtotal_text = $xtPrice->xtcFormat($subtotal_final, true);
		xtc_db_query("update " . TABLE_ORDERS_TOTAL . " set text = '" . $subtotal_text . "', value = '" . $subtotal_final . "' where orders_id = '" . $this->info['id'] . "' and class = 'ot_total'");

		//********************* COMBINED PAYMENT CHANGE
		if($this->info['is_parent'] == 'n') {
			$products_query = xtc_db_query("select final_price, products_tax, allow_tax from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $this->info['id'] . "' ");
		}else{
			$products_query = xtc_db_query("select op.final_price, op.products_tax, op.allow_tax from " . TABLE_ORDERS_PRODUCTS . " op, ".TABLE_ORDERS." o where o.parent_orders_id = '" . $this->info['id'] . "' && o.orders_id=op.orders_id");
		}
		//********************* COMBINED PAYMENT CHANGE
	
		while($products = xtc_db_fetch_array($products_query)){
			$tax_rate = $products['products_tax'];
			$multi = (($products['products_tax'] / 100) + 1);

			if ($products['allow_tax'] == '1') {
				$bprice = $products['final_price'];
				$nprice = $xtPrice->xtcRemoveTax($bprice, $tax_rate);
				$tax = $xtPrice->calcTax($nprice, $tax_rate);
			} else {
				$nprice = $products['final_price'];
				$bprice = $xtPrice->xtcAddTax($nprice, $tax_rate);
				$tax = $xtPrice->calcTax($nprice, $tax_rate);
			}

			// KEINE MWST BEI ENTSPRECHENDER KUNDENGRUPPENCONFIG
			if ($status['customers_status_add_tax_ot'] == 1) {
				$sql_data_array = array (
					'orders_id' => $this->info['id'], 
					'n_price' => xtc_db_prepare_input($nprice), 
					'b_price' => xtc_db_prepare_input($bprice), 
					'tax' => xtc_db_prepare_input($tax), 
					'tax_rate' => xtc_db_prepare_input($products['products_tax']));

				$insert_sql_data = array (
					'class' => 'products'
				);
				$sql_data_array = xtc_array_merge($sql_data_array, $insert_sql_data);
				xtc_db_perform(TABLE_ORDERS_RECALCULATE, $sql_data_array);
			}
		}
		// Produkte Ende
	
		// Module Anfang

		$module_query = xtc_db_query("select value, class from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $this->info['id'] . "' and class!='ot_total' and class!='ot_subtotal_no_tax' and class!='ot_tax' and class!='ot_subtotal' and class!='ot_payment_fee'");
		while ($module_value = xtc_db_fetch_array($module_query)) {
			$module_name = str_replace('ot_', '', $module_value['class']);

			if ($module_name != 'discount') {
				if ($module_name != 'shipping') {
					switch( strtoupper($module_name) ){
						case 'COD_FEE':
							// COD FEE Tax heisst COD_TAX
							$mod_key = 'COD';
							break;
						default:
							$mod_key = strtoupper($module_name);
							break;
					}
					$module_tax_class = constant(MODULE_ORDER_TOTAL_ . $mod_key . _TAX_CLASS);
				} else {
					$module_tmp_name = split('_', $this->info['shipping_class']);
					$module_tmp_name = $module_tmp_name[0];
					if ($module_tmp_name != 'selfpickup') {
						if (defined(MODULE_SHIPPING_ . strtoupper($module_tmp_name) . _TAX_CLASS)) {
							$module_tax_class = constant(MODULE_SHIPPING_ . strtoupper($module_tmp_name) . _TAX_CLASS);
						} else {
							$module_tax_class = '';
						}
					} else {
						$module_tax_class = '';
					}
				}
			} else {
				$module_tax_class = '0';
			}

			$module_tax_rate = xtc_get_tax_rate($module_tax_class, $cinfo['country_id'], $cinfo['zone_id']);

			if ($status['customers_status_show_price_tax'] == 1) {
				$module_b_price = $module_value['value'];
				if ($module_tax == '0') {
					$module_n_price = $module_value['value'];
				} else {
					$module_n_price = $xtPrice->xtcRemoveTax($module_b_price, $module_tax_rate);
				}
				$module_tax = $xtPrice->calcTax($module_n_price, $module_tax_rate);
			} else {
				$module_n_price = $module_value['value'];
				$module_b_price = $xtPrice->xtcAddTax($module_n_price, $module_tax_rate);
				$module_tax = $xtPrice->calcTax($module_n_price, $module_tax_rate);
			}
			// KEINE MWST BEI ENTSPRECHENDER KUNDENGRUPPENCONFIG
			if ($status['customers_status_add_tax_ot'] == 1) {
				$sql_data_array = array (
					'orders_id' => $this->info['id'], 
					'n_price' => xtc_db_prepare_input($module_n_price), 
					'b_price' => xtc_db_prepare_input($module_b_price), 
					'tax' => xtc_db_prepare_input($module_tax), 
					'tax_rate' => xtc_db_prepare_input($module_tax_rate));

				$insert_sql_data = array (
					'class' => $module_value['class']
				);
				$sql_data_array = xtc_array_merge($sql_data_array, $insert_sql_data);
				xtc_db_perform(TABLE_ORDERS_RECALCULATE, $sql_data_array);
			}
		}
		// Module Ende  

		// Alte UST Löschen ANFANG
		xtc_db_query("delete from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $this->info['id'] . "' and class='ot_tax'");
		// Alte UST Löschen ENDE

		// Neue Mwst. zusammenrechnen Anfang

		$ust_query = xtc_db_query("select tax_rate, SUM(tax) as tax_value_new from " . TABLE_ORDERS_RECALCULATE . " where orders_id = '" . $this->info['id'] . "' and tax !='0' GROUP by tax_rate ");
		while ($ust = xtc_db_fetch_array($ust_query)) {

			$ust_desc_query = xtc_db_query("select tax_description from " . TABLE_TAX_RATES . " where tax_rate = '" . $ust['tax_rate'] . "'");
			$ust_desc = xtc_db_fetch_array($ust_desc_query);

			$title = $ust_desc['tax_description'];

			if ($ust['tax_value_new']) {
				$text = $xtPrice->xtcFormat($ust['tax_value_new'], true);

				$sql_data_array = array (
					'orders_id' => $this->info['id'], 
					'title' => xtc_db_prepare_input($title), 
					'text' => xtc_db_prepare_input($text), 
					'value' => xtc_db_prepare_input($ust['tax_value_new']), 
					'class' => 'ot_tax');

				$insert_sql_data = array (
					'sort_order' => MODULE_ORDER_TOTAL_TAX_SORT_ORDER
				);
				$sql_data_array = xtc_array_merge($sql_data_array, $insert_sql_data);
				xtc_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
			}

		}


		if ($status['customers_status_show_price_tax'] == 0){
			$total_query = xtc_db_query("SELECT SUM(value) as totalsum FROM orders_total WHERE orders_id='".$this->info['id']."' and class != 'ot_total' and class != 'ot_subtotal_no_tax'");
		}else{
			$total_query = xtc_db_query("SELECT SUM(value) as totalsum FROM orders_total WHERE orders_id='".$this->info['id']."' and class != 'ot_total' and class != 'ot_tax'");
		}



		$total = xtc_db_fetch_array($total_query);
		$text = $xtPrice->xtcFormat($total['totalsum'], true);

		$sql_data_array = array (
			'text' => xtc_db_prepare_input($text), 
			'value' => xtc_db_prepare_input($total['totalsum']), 
		);
		xtc_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array,'update',"orders_id='".$this->info['id']."' and class='ot_total'");
		
		// Löschen des Zwischenspeichers Anfang
		xtc_db_query("delete from " . TABLE_ORDERS_RECALCULATE . " where orders_id = '" . $this->info['id'] . "'");
		// Löschen des Zwischenspeichers Ende
	}
	
	function is_kasse(){
		$kasse_query = xtc_db_query("SELECT id FROM kasse WHERE orders_id='".$this->info['id']."'");
		if(xtc_db_num_rows($kasse_query)>0){
			return true;
		}
		return false;
	}
	
	function get_kasse_data(){
		$kasse_query = xtc_db_query("SELECT * FROM kasse WHERE orders_id='".$this->info['id']."'");
		$kasse = xtc_db_fetch_array($kasse_query);
		$data_array = array('id'=>$kasse['id'],
			'paymode'=>$kasse['paymode'],
			'date_purchased'=>$kasse['date_purchased'],
			'quantity_purchased'=>$kasse['quantity_purchased'],
			'tax_rate'=>$kasse['tax_rate'],
			'total'=>$kasse['total'],
			'send'=>$kasse['send'],
			'branches_id'=>$kasse['branches_id']
		);
		return $data_array;
	}
	
	function get_status_name($status){
		$orders_status_query = xtc_db_query("select orders_status_name from " . TABLE_ORDERS_STATUS . " where orders_status_id = '" . $status . "' and language_id = '" . $this->language_id . "'");
		$orders_status = xtc_db_fetch_array($orders_status_query);
		return $orders_status['orders_status_name'];
	}
	
	// KOMBINIERTE ERMITTELN
	function get_combined_orders(){
  		$child_orders = array();
		$query = xtc_db_query("SELECT orders_id FROM ".TABLE_ORDERS." WHERE combined_orders_id = '".$this->info['id']."'");
	  	while($res = xtc_db_fetch_array($query)) {
  			$link = xtc_href_link(FILENAME_ORDERS,'oID='.$res['orders_id'].'&action=edit');
			$child_orders[] = array('orders_id'=>$res['orders_id'],'link'=>$link);
	  	}
	  	return $child_orders;
	}

	// ALTES KOMBINIEREN HANDLING
	function get_child_orders(){
  		$child_orders = array();
		$query = xtc_db_query("SELECT orders_id FROM ".TABLE_ORDERS." WHERE parent_orders_id = '".$this->info['id']."'");
	  	while($res = xtc_db_fetch_array($query)) {
			// yes accounting
			if ( ($_SESSION['customers_status']['customers_status_id'] == '0') && ($admin_access['f_orders_view'] == '1')) {
	  			$link = xtc_href_link(FILENAME_ORDERS,'oID='.$res['orders_id'].'&action=edit');
	  		}
			$child_orders[] = array('orders_id'=>$res['orders_id'],'link'=>$link);
	  	}
	  	return $child_orders;
	}
	
	function add_history($status_id,$notified,$comments){
		$insert_sql_array = array(
			'orders_id'=>$this->info['id'],
			'orders_status_id'=>$status_id,
			'date_added'=>'now()',
			'customer_notified'=>$notified,
			'comments'=>$comments,
			'editor_id'=>$this->editor_id
		);
		xtc_db_perform('orders_status_history',$insert_sql_array);
	}
	
	function save_select_set($_POST){
		global $messageStack;
		// ERMITTELE PID,SELECT_SET UND QTY DES AUKTIONS-SET-PRODUKTS
		$pid_query = xtc_db_query("SELECT op.products_id,op.products_quantity,ea.select_set FROM ebay_auctions ea,orders o LEFT JOIN orders_products op USING(orders_id) WHERE ea.ebay_id='".$this->info['ebay_id']."' and o.ebay_id=ea.ebay_id and o.orders_id='".$this->info['id']."'");
		$pid_res = xtc_db_fetch_array($pid_query);
		$pID = $pid_res['products_id'];
		$qty = $pid_res['products_quantity'];
		$select_set = $pid_res['select_set'];
		
		$error = false;
		$collie_products_delete = array(); // enthaelt die abgewaehlten produkte
		$save_array = array(); // die ausgewaehlten produkte
		
		// START PRUEFUNG DER VARIABLEN		
		if($select_set == 1){
					$collies = xtc_get_product_collies($pID);
				
					for($i=0;$i<$qty;$i++){
						foreach($collies as $ck=>$collie){
							if( $collie['collie_products_id'] == $_POST['pid'][ $this->info['id'] ][$pID][$i] ){
							}else{
								$collie_products_delete[$collie['collie_products_id']] = $collie_products_delete[ $this->info['id'] ][$collie['collie_products_id']]+$collie['quantity'];
							}
						}
					}
					if(sizeOf($collies)>0){
						if($_POST['pid'] and is_array($_POST['pid'][ $this->info['id'] ]) and is_array($_POST['pid'][ $this->info['id'] ][$pID]) ){
							for($i=0;$i<$qty;$i++){
								$in_collie = false;
								foreach($collies as $ck=>$collie){
									if( $collie['collie_products_id'] == $_POST['pid'][ $this->info['id'] ][$pID][$i] ){
										$in_collie = true;
									}
								}
								if(!$in_collie){
									$messageStack->add_session('Es wurde ein Produkt &uuml;bergeben, was nicht zum Set geh&ouml;rt. Sollte das Problem weiterhin bestehen, setzen Sie sich bitte mit uns in Verbindung.');
									$error = true;
								}else{
									$save_array[$pID][$i] = $_POST['pid'][ $this->info['id'] ][$pID][$i];
								}
							}
						}else{
							$error = true;
							$messageStack->add_session('Es wurden nicht alle Produkte zur Bestellung &uuml;bergeben. Sollte das Problem weiterhin bestehen, setzen Sie sich bitte mit uns in Verbindung.');
						}
					}
		}
		// -----------------------------------------------
		// ENDE PRUEFUNG
		// -----------------------------------------------
	
		if($error){
			$_POST['step'] = '2';
		}else{
				// -----------------------------------------------
				// START SET AUSWAHL
				// -----------------------------------------------
				if(sizeOf($save_array) > 0){
				
					// HIER HOLEN WIR ALLE ZUR RECHNG GESPEICHERTEN SN NR
					// VON DENEN ZIEHEN WIR DIE UEBERGEBENEN COLLIPRODUKTE AB
					// UND LOESCHEN DEN REST
						
					foreach($save_array as $pID => $newpIDarray){
						foreach($newpIDarray as $nr => $newpID){
							$is_serial_query = xtc_db_query("SELECT serial_numbers FROM products WHERE products_id='".$newpID."'");
							$is_serial = xtc_db_fetch_array($is_serial_query);
							if(STOCK_ALLOW_CHECKOUT != 'true' and $is_serial['serial_numbers'] == '1'){
								$existing_serial = $this->get_serial_numbers();
								if( is_array( $existing_serial[ $newpID ] ) and sizeOf( $existing_serial[ $newpID ] ) > 0){
									$collie_qty_query = xtc_db_query("SELECT quantity FROM products_collies WHERE products_id='".$pID."' and collie_products_id='".$newpID."'");
									$collie_qty = xtc_db_fetch_array($collie_qty_query); 
									// WIR ENTFERNEN IMMER SOVIEL SN WIE TREFFER
									// DIE VERBLEIBENDEN LOESCHEN WIR
									for($i=0;$i<$collie_qty['quantity'];$i++){
										$existing_serial[$newpID] = array_slice( $existing_serial[$newpID],1);
									}
								}
							}
						}
					}
					
					// NUN NOCH UEBERGEBLIEBENE SN NUMMERN LOESCHEN
					if(sizeOf($existing_serial) > 0){
						foreach($existing_serial as $pID=>$snArray){
							if(sizeOf($snArray)>0){
								// NUR DIE SN NUMMERN LOESCHEN DIE NICHT MEHR IN DER
								// RECHNUNG SIND
								foreach($snArray as $sk=>$sn){
									$opID_query = xtc_db_query("SELECT ops.orders_products_id FROM orders_products op LEFT JOIN orders_products_serials ops USING(orders_products_id) WHERE orders_id='".$this->info['id']."'");
									$opID = xtc_db_fetch_array($opID_query);
									xtc_db_query("DELETE FROM orders_products_serials WHERE orders_products_id='".$opID['orders_products_id']."' and products_id='".$pID."' and serial_number='".$sn."'");
									xtc_db_query("UPDATE products_serials SET serial_status='0' WHERE serial_number='".xtc_db_prepare_input($sn)."' and products_id='".$newpID."'");
									$comments = 'Seriennummer '.$sn.' des Produkts '.xtc_get_products_name($pID).' (pID: '.$pID.') wurde wieder freigegeben.'; 
									$this->add_history($this->info['orders_status'],$notified=0,$comments);
								}
							}
						}
					}
									
					foreach($save_array as $pID => $newpIDarray){
						// LOESCHE DAS SET PRODUKT
						xtc_db_query("DELETE FROM orders_products WHERE orders_id='".$this->info['id']."' and products_id='".$pID."'");
						$comments = sizeOf($newpIDarray).' x Set-Produkt '.xtc_get_products_name($pID).' (pID: '.$pID.') wurde in Auswahlset-Bearbeitung geloescht.';
						$this->add_history($this->info['orders_status'],$notified=0,$comments);

						// FUEGE AUSGEWAEHLTE(S) PRODUKT(E) EIN
						foreach($newpIDarray as $nr => $newpID){
						
							$collie_qty_query = xtc_db_query("SELECT quantity FROM products_collies WHERE collie_products_id='".$newpID."' and products_id='".$pID."'");
							$collie_qty = xtc_db_fetch_array($collie_qty_query);
							
							$model_query = xtc_db_query("SELECT products_model FROM products WHERE products_id='".$newpID."'");
							$model_res = xtc_db_fetch_array($model_query);
							$model = $model_res['products_model'];
							$price = $this->products[0]['price']/$collie_qty['quantity'];
							$discount = $this->products[0]['discount'];
							$final_price = $this->products[0]['final_price'];
							$tax = $this->products[0]['tax'];
							$allow_tax = $this->products[0]['allow_tax'];
							// da die collis zum setprodukt stueck fuer stueck ausgewaehlt werden
							// koennen immer als grundlage 1 des sets
							$qty = $collie_qty['quantity'];
							 

							$new_opID = $this->insert_product($newpID,$model,xtc_get_products_name($newpID),$price,$discount,$final_price,$tax,$qty,$allow_tax);
							$comments = $collie_qty['quantity']. "x Colli-Produkt ".xtc_get_products_name($newpID)." (pID: ".$newpID.") wurde in der Auswahlset-Bearbeitung ausgewaehlt und ersetzt das Set-Produkt.";
							$this->add_history($this->info['orders_status'],$notified=0,$comments);
							
							// DIE VERBLIEBENEN SN VERWEISEN NUN NOCH AUF DIE *ALTE* ORDERS_PRODUCTS_ID DES SET ARTIKELS
							// DIESE MUESSEN WIR AUF DIE EBEN ERZEUGTE ORDERS_PRODUCTS_ID UPDATEN
							xtc_db_query("UPDATE orders_products_serials SET orders_products_id='".$new_opID."' WHERE orders_products_id='".$this->products[0]['opID']."' and products_id='".$newpID."'");
						}
					}
				} // end if save_array>0
	
				if(sizeOf($collie_products_delete)>0){
					foreach($collie_products_delete as $pID=>$qty){
						$SQ = new products_quantity($pID);
						$new_qty = $qty;
						$qty_total = $SQ->get_products_total_qty();
						$SQ->update_qty( $new_qty, $SQ->get_default_storage_id(),$qty_total,'Abwahl des Produkts (Set mit Variantenauswahl) in Auswahlset-Bearbeitung der Re-Nr: '.$this->info['id'].' Rueckbuchung '.$new_qty.' Stk.');
						$comments = $new_qty." x Colli-Produkt ".xtc_get_products_name($pID)." (pID: ".$pID.") nach Abwahl in Auswahlset-Bearbeitung dem Bestand wieder zugefuehrt.";
						$this->add_history($this->info['orders_status'],$notified=0,$comments);
					}
				}
				
				// -----------------------------------------------
				// ENDE SET AUSWAHL
				// -----------------------------------------------
				
				// NUN DEN SELECT_SET STATUS UPDATEN				
				xtc_db_query("UPDATE orders SET select_set_status='1',select_set_product_status='1',last_modified='now()' WHERE orders_id='".$this->info['id']."'");
				$comments = 'Auswahlset-Bearbeitung abgeschlossen.';
				$this->add_history($this->info['orders_status'],$notified=0,$comments);
		}
	}
	
	// hole die zu den rechnungsprodukten gespeicherten SN	
	function get_serial_numbers(){
		$this->serial_numbers = array();
		$orders_products_serials_query = xtc_db_query("SELECT ops.* FROM orders_products_serials ops,orders_products op WHERE op.orders_id='".$this->info['id']."' and op.orders_products_id=ops.orders_products_id");
		while($orders_products_serials = xtc_db_fetch_array($orders_products_serials_query)){
			$this->serial_numbers[ $orders_products_serials['products_id'] ][] = $orders_products_serials['serial_number'];
		}
	}
	
	function insert_product($pID,$model,$name,$price,$discount,$final_price,$tax,$qty,$allow_tax){
		$insert_sql_array = array(
		  'orders_id'=>$this->info['id'],
		  'products_id'=>$pID,
		  'products_model'=>$model,
		  'products_name'=>$name,
		  'products_price'=>$price,
		  'products_discount_made'=>$discount,
		  'final_price'=>$final_price,
		  'products_tax'=>$tax,
		  'products_quantity'=>$qty,
		  'allow_tax'=>$allow_tax,
		  'date_added'=>'now()'
		);
		xtc_db_perform('orders_products',$insert_sql_array);
		return mysql_insert_id();
	}
	
	function update_shippingcosts($otID,$value,$title){
		$customers_status = $this->info['status'];
		$xtPrice = new xtcPrice($this->info['currency'],$customers_status);

	        $text = $xtPrice->xtcFormat($value,1);
		$update_sql_array = array( 
			'title'=>$title,
			'text'=>$text,
			'value'=>$value
		);
		xtc_db_perform(TABLE_ORDERS_TOTAL,$update_sql_array,'update',"orders_total_id='".$otID."' and orders_id='".$this->info['id']."'");
		$comments = 'Versandkosten wurden von '.$original_total.' zu '.$formated_value.' geaendert.';
		$this->add_history($this->info['orders_status'],$notified=0,$comments);
	}
	
	function delete_orders_total_entry($otID){
		xtc_db_query("delete from " . TABLE_ORDERS_TOTAL . " where orders_total_id = '" . $otID . "' and orders_id='".$this->info['id']."'");
	}

	function update_orders_status($status_id){
		$update_sql_array = array(
			'orders_status'=>$status_id,
			'last_modified'=>'now()'
		);
		xtc_db_perform('orders',$update_sql_array,'update','orders_id='.$this->info['id']);
	}

	function remove_tax(){
		global $shipping_modules;
		$customers_status = $this->info['status'];
		$xtPrice = new xtcPrice($this->info['currency'],$customers_status);
		$_class = current(split('_',$this->info['shipping_class']));
		$_class = $_class.'.php';
		for($i=0;$i<sizeOf($shipping_modules->modules);$i++){
			if($shipping_modules->modules[$i] == $_class){
				$shipping_method = $_class;
			}
		}
		if(!$shipping_method){
			$shipping_method = $shipping_modules->modules[0];
		}
		$shipping_class_instance_name = current(split('.php',$shipping_method));
		$shipping_class_tax_class = $GLOBALS[$shipping_class_instance_name]->tax_class;
		$shipping_class_tax_value = xtc_get_tax_rate($shipping_class_tax_class);


		if(sizeOf($this->products)>0){
			$subtotal_no_tax = 0;
			// DURCHLAUFE PRODUKTE UND ERMITTELE DIE NETTO-ZWISCHENSUMME
			foreach($this->products as $k=>$product){
				$orig_price = $product['price'];
				$orig_final_price = $product['final_price'];
				$orig_tax = $product['tax'];
				if($orig_tax>0){
					$netto_price = xtc_oe_get_price_o_tax($orig_price,$orig_tax,0);
					$netto_final_price = xtc_oe_get_price_o_tax($orig_final_price,$orig_tax,0);

					$subtotal_no_tax += $netto_final_price;
					
					$sql_array = array('products_tax'=>0,
						'products_price'=>$netto_price,
						'allow_tax'=>0,
						'products_tax'=>0,
						'final_price'=>$netto_final_price
					);
					xtc_db_perform('orders_products',$sql_array,'update','orders_id=\''.$this->info['id'].'\' and products_id=\''.$product['id'].'\'');
				}
			}
			// WENN EINE NETTOZWISCHENSUMME ERMITTELT WURDE, DB UPDATE
			if($subtotal_no_tax > 0){
				// NACHSEHEN OB BEREITS EINE ot_subtotal_no_tax CLASS IN
				// ORDERS_TOTAL GESPEICHERT IST, WENN JA DANN SUMME UPDATEN
				foreach($this->totals as $k=>$v){
					if($v['class'] == 'ot_subtotal_no_tax'){
						$ot_subtotal_no_tax = true;
						$text=$xtPrice->xtcFormat($subtotal_no_tax,true);
						$update_sql_array = array(
							'value'=>$subtotal_no_tax,
							'text'=>$text
						);
						xtc_db_perform('orders_total',$update_sql_array,'update',"orders_id='".$this->info['id']."' and class='ot_subtotal_no_tax'");
					}
				}
				// ES IST NOCH KEINE ot_subtotal_no_tax CLASS IN ORDERS_TOTAL
				// ALSO EINE NEUE ANLEGEN
				if(!$ot_subtotal_no_tax){
					$text=$xtPrice->xtcFormat($subtotal_no_tax,true);
					$insert_sql_array = array(
						'title'=>MODULE_ORDER_TOTAL_SUBTOTAL_NO_TAX_TITLE,
						'class'=>'ot_subtotal_no_tax',
						'orders_id'=>$this->info['id'],
						'sort_order'=>MODULE_ORDER_TOTAL_SUBTOTAL_NO_TAX_SORT_ORDER,
						'value'=>$subtotal_no_tax,
						'text'=>$text
					);
					xtc_db_perform('orders_total',$insert_sql_array);
				}
				xtc_db_query("DELETE FROM orders_total WHERE orders_id='".$this->info['id']."' and class='ot_subtotal'");
			} // ENDE NEUE ZWISCHENSUMME SPEICHERN
		} // ENDE IF PRODUCTS

		// TOTALS DURCHLAUFEN UND NACH SHIPPINGCOSTS SUCHEN
		foreach($this->totals as $k=>$v){
			if($v['class'] == 'ot_shipping'){
				$netto_shippingcosts = xtc_oe_get_price_o_tax($v['value'], $shipping_class_tax_value, 0);
				$text=$xtPrice->xtcFormat($netto_shippingcosts,true);
				$update_sql_array = array(
					'value'=>$netto_shippingcosts,
					'text'=>$text
				);
				xtc_db_perform('orders_total',$update_sql_array,'update',"orders_id='".$this->info['id']."' and class='ot_shipping'");
			}
		}
		xtc_db_query("DELETE FROM orders_total WHERE orders_id='".$this->info['id']."' and class='ot_tax'");
		$this->order($this->info['id']);
		$this->recalc();
	}

	function is_netto(){
		if(sizeOf($this->products)>0){
			if($this->products[0]['tax']>0)
				return false;
		}else{
			$customers_status_query = xtc_db_query("SELECT customers_status_add_tax_ot FROM " . TABLE_CUSTOMERS_STATUS . " WHERE customers_status_id = '" . $this->info['status'] . "'");
			$customers_status_value = xtc_db_fetch_array($customers_status_query);
	    		if($customers_status_value['customers_status_add_tax_ot'] > 0){
				return false;
			}
		}
		return true;
	}

	function insert_shippingcosts($inp_price,$title,$file='yes.php'){
		$customers_status = $this->info['status'];
		$xtPrice = new xtcPrice($this->info['currency'],$customers_status);

	        $text = $xtPrice->xtcFormat($inp_price,1);
	        $sort = MODULE_ORDER_TOTAL_SHIPPING_SORT_ORDER;
	 
	        $insert_sql_array = array('orders_id' => $this->info['id'],
			'title' => $title,
			'text' => xtc_db_prepare_input($text),
			'value' => xtc_db_prepare_input($inp_price),
			'class' => 'ot_shipping',
			'sort_order' => $sort
		);
	        xtc_db_perform(TABLE_ORDERS_TOTAL, $insert_sql_array);
		$module = current(split('\.php',$file));
		require (DIR_FS_LANGUAGES . $_SESSION['language'] . '/modules/shipping/' . $file);
		$shipping_text = constant(MODULE_SHIPPING_ . strtoupper($module) . _TEXT_TITLE);
		$shipping_class = $module . '_' . $module;

		$sql_data_array = array (
			'shipping_method' => xtc_db_prepare_input($shipping_text
		), 'shipping_class' => xtc_db_prepare_input($shipping_class),);
		xtc_db_perform(TABLE_ORDERS, $sql_data_array, 'update', 'orders_id = \'' . $this->info['id'] . '\'');

		$comments = 'Versandkosten wurden mit '.$text.' hinzugefuegt.';
		$this->add_history($this->info['orders_status'],$notified=0,$comments);
	}
}
?>
