<?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/country.class.php';
include_once './core/order.class.php';
include_once './core/orderhelper.class.php';
include_once './core/itemhelper.class.php';
include_once './core/customer.class.php';
include_once './core/customergroups.class.php';
include_once './core/customerhelper.class.php';
include_once './core/tax.class.php';
include_once './core/payment_method.class.php';
include_once './core/item.class.php';
include_once './core/cs_ticket.class.php';
include_once './core/cs_ticket_message.class.php';
include_once './core/deliverer.class.php';
include_once './core/delivererhelper.class.php';
include_once './core/cstickethelper.php';
include_once './core/cancellationreasons.class.php';
include_once './core/config.class.php';

class admin_order_editor {

	protected $layout_object;
	protected $base_object;

	protected $order_object;
	protected $customer_object;
	protected $country_object;
	protected $customer_group_object;
	protected $item_object;
	protected $deliverer_object;
	protected $cancellation_reasons_object;

	function __construct($base_object, $layout_object) {
		$this->layout_object = $layout_object;
		$this->base_object = $base_object;

		$this->order_object = new Order($base_object);
		$this->customer_object = new Customer($this->base_object);
		$this->country_object = new Country($this->base_object);
		$this->item_object = new Item($this->base_object);

		$this->deliverer_object = new Deliverer($this->base_object);
		$this->customer_group_object = new CustomerGroups($this->base_object);
		$this->cancellation_reasons_object = new CancellationReasons($base_object);
	}

	function run() {
		if (isset($_GET['action'])) {
			$action = $_GET['action'];
		} else if (isset($_POST['action'])) {
			$action = $_POST['action'];
		} else {
			$action = 'add_order';
		}

		if (isset($_GET['id'])) {
			$id = $_GET['id'];
		} else if (isset($_POST['id'])) {
			$id = $_POST['id'];
		} else {
			$id = false;
		}

		if ($action == 'submit') {
			$this->save($id);
		} else {
			return $this->edit($id);
		}
	}

	private function edit($id) {
		if ($id) {
			// get order tickets
			$revised_orders_list = OrderHelper::get_revision_history_for_order($id);

			$ticket_object = new Cs_ticket($this->base_object);
			$ticket_message_object = new Cs_ticket_message($this->base_object);

			$all_tickets = CSTicketHelper::get_tickets_by_ids($revised_orders_list);

			$tickets = array();
			foreach ($all_tickets as $ticket) {
				// get first message
				$ticket->first_message = $ticket_message_object->get_first_message($ticket->id);
				$tickets[] = $ticket;
			}

			$this->layout_object->assign('tickets', $tickets);

			try {
				$order = $this->order_object->get_order_by_id($id);

				$customer_id = $order['header']->customer_id;

				if (OrderHelper::order_has_revision($id)) {
					$order_revisions = OrderHelper::get_all_orders_by_order_number($order['header']->order_number);

					$this->layout_object->assign('order_history', $order_revisions);
				}

				$this->customer_group_object->get_by_user($customer_group_id);

				$order_data = $order['header'];
				$customer_group_id = CustomerHelper::get_customer_group_id_by_customer_id($customer_id);
				$customer_email = CustomerHelper::get_customer_email($customer_id);
				$group_data = $this->customer_group_object->get($customer_group_id);

				$order_data->group_id = $group_data->id;
				$order_data->group_name = $group_data->name;
				$order_data->group_show_tax = $group_data->show_tax;
				$order_data->customer_email = $customer_email;
				$order_items = array_reverse($order['items']);

				$order_footer = $order['footer'];

				// deliverers
				$deliverers = DelivererHelper::get_deliverers_with_prices_by_country($order_data->shipping_country);
				$this->layout_object->assign('deliverers', $deliverers);

				// payment method
				$payment_method = PaymentHelper::getActivePaymentMethodsByCountry($order['header']->shipping_country);
				$this->layout_object->assign('payment_method_list', $payment_method);

				// cancellation reasons
				$cancellation_reasons = $this->cancellation_reasons_object->get_all('active');
				$this->layout_object->assign('cancellation_reasons', $cancellation_reasons);

				$this->layout_object->assign('addresses', $this->customer_object->get_address_by_customer_id($customer_id));

				$shipping_charge_taxes = ($order_footer->shipping_charges / 119.0) * 19;
				$payment_method_charge_taxes = ($order_footer->payment_method_charges / 119.0) * 19;

				$additional_chrges = $shipping_charge_taxes + $payment_method_charge_taxes;

				if (isset($order_footer->taxes['19.00'])) {
					$order_footer->taxes['19.00'] += $shipping_charge_taxes + $payment_method_charge_taxes;
				} else {
					if ($additional_chrges > 0) {
						$order_footer->taxes['19.00'] = $shipping_charge_taxes + $payment_method_charge_taxes;
					}
				}

				$this->layout_object->assign('order', $order_data);
				$this->layout_object->assign('order_items', $order_items);
				$this->layout_object->assign('footer', $order_footer);
			} catch (Exception $e) {
				$this->layout_object->assign('error_message', $e->getMessage());
			}
		} else {
			if ($_GET['customer_id']) {
				$this->customer_object->set_id($_GET['customer_id']);
				$customer_data = $this->customer_object->get_data();
				$customer_group_data = $this->customer_group_object->get($customer_data->group_id);

				$temp = new stdClass();
				$temp->customer_id = $customer_data->id;
				$temp->group_id = $customer_data->group_id;
				$temp->customer_number = $customer_data->number;
				$temp->customer_name = $customer_data->firstname.' '.$customer_data->surname;
				$temp->group_show_tax = $customer_group_data->show_tax;
				$temp->group_name = $customer_group_data->name;

				$this->layout_object->assign('order', $temp);
				$this->layout_object->assign('addresses', $this->customer_object->get_address_by_customer_id($_GET['customer_id']));

				//doesn't work hmm, besides i would still need to insert the fields in the template
				$this->layout_object->assign('use_default_address', true);

				$default_address_country_id = CustomerHelper::get_default_address_country($customer_data->id);

				if ($default_address_country_id) {
					// deliverers
					$deliverers = DelivererHelper::get_deliverers_with_prices_by_country($default_address_country_id);
					$this->layout_object->assign('deliverers', $deliverers);

					// payment method
					$payment_method = PaymentHelper::getActivePaymentMethodsByCountry($default_address_country_id);
					$this->layout_object->assign('payment_method_list', $payment_method);
				}
			}
		}

		if (Config::has_key('invoice_number_manual')) {
			$invoice_number_manual = Config::get_value('invoice_number_manual');
		} else {
			$invoice_number_manual = false;
		}
		$this->layout_object->assign('invoice_number_manual', $invoice_number_manual);

		if (Config::has_key('shipping_list_number_manual')) {
			$shipping_list_number_manual = Config::get_value('shipping_list_number_manual');
		} else {
			$shipping_list_number_manual = false;
		}
		$this->layout_object->assign('shipping_list_number_manual', $shipping_list_number_manual);

		// get countries
		$countries = $this->country_object->get_all();
		$this->layout_object->assign('countries', $countries);

		// payment methods
		$order_status = $this->order_object->get_order_status_object();
		$this->layout_object->assign('order_status_list', $order_status);

		// billing status
		$billing_status = $this->order_object->get_billing_status_object();
		$this->layout_object->assign('billing_status_list', $billing_status);

		// taxes
		$taxes = new Tax($this->base_object);
		$this->layout_object->assign('tax_rates', $taxes->get_all());

		$this->layout_object->assign('order_list', $this->layout_object->fetch('table_order_order_list.tpl'));

		if (isset($_GET['action']) && $_GET['action'] == 'order_print') {
			echo $this->layout_object->fetch('admin_order_print.tpl');
			exit();
		}
		else {
			return $this->layout_object->fetch('admin_order_editor.tpl');
		}
	}

	private function save($id) {
		$data = new stdClass();

		$show_taxes = $_POST['show_taxes'];
		unset($_POST['show_taxes']);

		if (isset($_POST['order'])) {
			$order = $_POST['order'];

			if (isset($order['is_eu_order'])) {
				$data->is_eu_order = $order['is_eu_order'] == 'on' ? 1 : 0;
			} else {
				$data->is_eu_order = 0;
			}

			if (isset($order['customer_vat_reg_num'])) {
				$data->customer_vat_reg_num = $order['customer_vat_reg_num'];
			}

		}

		if (isset($_POST['export_to_shipping'])) {
			$data->export_to_shipping = $_POST['export_to_shipping'];
		}

		if (isset($_POST['paymorrow'])) {
			$paymorrow = $_POST['paymorrow'];

			if (isset($paymorrow['paymorrow_request_id'])) {
				$data->paymorrow_request_id = $paymorrow['paymorrow_request_id'];
			}

			if (isset($paymorrow['paymorrow_transaction_id'])) {
				$data->paymorrow_transaction_id = $paymorrow['paymorrow_transaction_id'];
			}

			if (isset($paymorrow['paymorrow_response_result_code'])) {
				$data->paymorrow_response_result_code = $paymorrow['paymorrow_response_result_code'];
			}

			if (isset($paymorrow['paymorrow_response_status_code'])) {
				$data->paymorrow_response_status_code = $paymorrow['paymorrow_response_status_code'];
			}

			if (isset($paymorrow['paymorrow_response_timestamp'])) {
				$data->paymorrow_response_timestamp = $paymorrow['paymorrow_response_timestamp'];
			}

			if (isset($paymorrow['paymorrow_bic'])) {
				$data->paymorrow_bic = $paymorrow['paymorrow_bic'];
			}

			if (isset($paymorrow['paymorrow_iban'])) {
				$data->paymorrow_iban = $paymorrow['paymorrow_iban'];
			}

			if (isset($paymorrow['paymorrow_national_bank_code'])) {
				$data->paymorrow_national_bank_code = $paymorrow['paymorrow_national_bank_code'];
			}

			if (isset($paymorrow['paymorrow_national_bank_account_number'])) {
				$data->paymorrow_national_bank_account_number = $paymorrow['paymorrow_national_bank_account_number'];
			}

			if (isset($paymorrow['paymorrow_payment_reference'])) {
				$data->paymorrow_payment_reference = $paymorrow['paymorrow_payment_reference'];
			}
		}

		if (isset($_POST['klarna'])) {
			$klarna = $_POST['klarna'];

			if (isset($klarna['klarna_invoice_number'])) {
				$data->klarna_invoice_number = $klarna['klarna_invoice_number'];
			}
		}

		if (isset($_POST['orderInfo'])) {
			$orderInfo = $_POST['orderInfo'];

			if (isset($orderInfo['order_number'])) {
				$data->order_number = $orderInfo['order_number'];
			}

			if (isset($orderInfo['order_revision'])) {
				$data->order_revision = $orderInfo['order_revision'];
			}

			if (isset($orderInfo['order_addendum'])) {
				$data->order_addendum = $orderInfo['order_addendum'];
			}
		}

		if (isset($_POST['inventory_management'])) {
			$inventory_management = $_POST['inventory_management'];

			if (isset($inventory_management['inventory_decremented'])) {
				$data->inventory_decremented = $inventory_management['inventory_decremented'];
			}

			if (isset($inventory_management['inventory_decremented_date'])) {
				$data->inventory_decremented_date = $inventory_management['inventory_decremented_date'];
			}

			if (isset($inventory_management['inventory_incremented'])) {
				$data->inventory_incremented = $inventory_management['inventory_incremented'];
			}

			if (isset($inventory_management['inventory_incremented_date'])) {
				$data->inventory_incremented_date = $inventory_management['inventory_incremented_date'];
			}
		}

		if (isset($_POST['invoice_email'])) {
			$invoice_email = $_POST['invoice_email'];

			if (isset($invoice_email['invoice_email_sent'])) {
				$data->invoice_email_sent = $invoice_email['invoice_email_sent'];
			}

			if (isset($invoice_email['invoice_email_date'])) {
				$data->invoice_email_date = $invoice_email['invoice_email_date'];
			}

			if (isset($invoice_email['invoice_email_recipient'])) {
				$data->invoice_email_recipient = $invoice_email['invoice_email_recipient'];
			}
		}

		// cancellation
		if (isset($_POST['cancellationData'])) {
			if (isset($_POST['cancellationData']['cancellation_date'])) {
				$data->cancellation_date = $_POST['cancellationData']['cancellation_date'];
			}

			if (isset($_POST['cancellationData']['cancellation_status'])) {
				$data->cancellation_status = $_POST['cancellationData']['cancellation_status'];
			}

			if (isset($_POST['cancellationData']['cancellation_reason_id']) && $_POST['cancellationData']['cancellation_reason_id'] != '-') {
				$data->cancellation_reason_id = $_POST['cancellationData']['cancellation_reason_id'];
			}

			if (isset($_POST['cancellationData']['cancellation_info'])) {
				$data->cancellation_info = $_POST['cancellationData']['cancellation_info'];
			}
		}

		if (isset($_POST['without_shipping_charges']) && $_POST['without_shipping_charges'] == 'yes') {
			$data->without_shipping_charges = 1;
		} else {
			$data->without_shipping_charges = 0;
		}

		if (isset($_POST['giftCertificate'])) {
			$data->giftCertificateCode = $_POST['giftCertificate']['gift_certificate_code'];
		}

		if (isset($_POST['dateOptions'])) {
			$dates = $_POST['dateOptions'];

			if ($dates['order_date']) {
				$data->order_date = $dates['order_date'];
			}

			if ($dates['billing_date']) {
				$data->billing_date = $dates['billing_date'];
			}

			if ($dates['payment_date']) {
				$data->payment_date = $dates['payment_date'];
			}
		}

		$data->paypal = $_POST['paypal'];

		if (isset($_POST['orderNotice'])) {
			$notices = $_POST['orderNotice'];

			if ($notices['customer_info']) {
				$data->customer_info = $notices['customer_info'];
			}

			if ($notices['invoice_info']) {
				$data->invoice_info = $notices['invoice_info'];
			}

			if ($notices['internal_info']) {
				$data->internal_info = $notices['internal_info'];
			}

			if ($notices['delivery_note_info']) {
				$data->delivery_note_info = $notices['delivery_note_info'];
			}
		}

		if (isset($_POST['group_id'])) {
			$group_id = $_POST['group_id'];
		}

		$data->revisor_id = $this->base_object->customer->id;
		$orderData = $_POST['orderOptions'];

		if (isset($_POST['customer'])) {
			$data->customer = (object) $_POST['customer'];
		} 

		if (isset($_POST['billingAddress'])) {
			$data->billingAddress = (object) $_POST['billingAddress'];
		}

		if (isset($_POST['shippingAddress'])) {
			$data->shippingAddress = (object) $_POST['shippingAddress'];
		}

		$break_order_apart = false;
		$not_delierable = false;

		if (isset($_POST['order_item'])) {
			$items = $this->make_items_array($_POST['order_item']);

			if (isset($_POST['child_item'])) {
				$children = $this->make_child_items_array($_POST['child_item']);
				$items = array_merge($items, $children);
			}

			foreach ($items as $order_item) {
				$this->item_object->id = $order_item->item_id;

				$item = $this->item_object->get_data($group_id, false);

				$prices = $this->item_object->calculate_prices($item, $order_item->quantity, $order_item->variant_1, $order_item->variant_2, $order_item->price, $data->customer->customer_id);

				$data->items[] = array(
					'itemId' => $order_item->item_id,
					'variant1' => $order_item->variant_1,
					'variant2' => $order_item->variant_2,
					'quantity' => $order_item->quantity,
					'prices' => $prices,
					'mainItemNumber' => $item->number,
					'variantItemNumber' => $item->variant_data[$order_item->variant_1][$order_item->variant_2]['item_number'],
					'vatId' => $item->tax_id,
					'vatRate' => $item->tax,
					'vatValue' => $prices['itemPriceGross'] - $prices['itemPriceNet'],
					'name' => $item->name,
					'item_status' => $order_item->item_status,
					'item_status_text' => $order_item->item_status_text,
					'delivery_date' => $order_item->delivery_date,
					'backorder_quantity' => $order_item->backorder_quantity,
					'userData' => $order_item->user_data,
					'parentItemId' => $order_item->parent_item_id,
					'stamp' => $order_item->stamp
				);

				++$data->itemsQuantity;
				$data->itemsOverallQuantity += $itemDataSet->quantity;

				$data->itemSumNet += $prices['itemPriceNet'] * $order_item->quantity;
				$data->itemSumGross += $prices['itemPriceGross'] * $order_item->quantity;
				$data->itemSumVat['id'][$item->tax_id] += ($prices['itemPriceGross'] - $prices['itemPriceNet']) * $order_item->quantity;
				$data->itemSumVat['rate'][$item->tax] += ($prices['itemPriceGross'] - $prices['itemPriceNet']) * $order_item->quantity;
			}
		}

		//tracking code
		$data->trackingcode = $orderData['trackingcode'];

		$customer_group_id = $group_id;
		// Payment
		$data->payment = PaymentHelper::getPaymentDataByIdAndCountry(
			$orderData['payment_method'], 
			$data->shippingAddress->country,
			$this->base_object->config->shopConfiguration['default_vat_value'],
			$data->itemSumGross,
			$customer_group_id
		);

		$data->payment->status = $orderData['payment_status'];

		// Deliverer
		// TODO: delivery method can't be defined in backend order editor
		$data->shipping = DelivererHelper::getDeliveryDataByIdAndCountry(
			$orderData['delivery_method'], 
			$data->shippingAddress->country,
			$this->base_object->config->shopConfiguration['default_vat_value'],
			$customer_group_id
		);

		if ($orderData['invoice_number'] != '') {
			$data->invoice_number = $orderData['invoice_number'];
		}

		$data->order_status = $orderData['order_status'];

		if (isset($_POST['generate_invoice_number']) && $_POST['generate_invoice_number'] == 'yes') {
			$invoice_number = true;
		} else {
			$invoice_number = false;
		}

		if (isset($_POST['generate_shipping_list_number']) && $_POST['generate_shipping_list_number'] == 'yes') {
			$shipping_list_number = true;
		} else {
			$shipping_list_number = false;
		}

		if (isset($_POST['manual_shipping_charges']) && $_POST['manual_shipping_charges'] != '') {
			$data->manual_shipping_charges = $_POST['manual_shipping_charges'];
		}


		$data->set_inventory = (isset($_POST['set_inventory'])) ? $_POST['set_inventory'] : 0;

		$status_has_chagned = false;

		if ($id) {
			//echo "update"; exit();
			$status_has_chagned = $this->has_order_changed($data->order_status, $id);

			$data->old_order_id = $id;

			$return = $this->order_object->update($data, $invoice_number, $shipping_list_number, $show_taxes);
		} else {
			//echo "create"; exit();
			$return = $this->order_object->create($data, $invoice_number, $shipping_list_number, $show_taxes);
		}



		if ($return) {
			if ($status_has_chagned) {
				// emails on status change
				$this->checkorderStatus($data->order_status,$return,$data->customer->customer_id);
			}

			header('location: http://'.$_SERVER["SERVER_NAME"].'/index.php?admin_modul=admin_order_editor&id='.$return);
		} else {
			header('location: http://'.$_SERVER["SERVER_NAME"].'/index.php?admin_modul=admin_order_editor');
		}
	}

	private function checkorderStatus($orderStatus_id,$order_id,$customer_id) {
		if ($orderStatus_id == 3) {
			$event_type = 5;
		} else if ($orderStatus_id == 4) {
			$event_type = 6;
		} else if ($orderStatus_id == 5) {
			$event_type = 7;
		} else if ($orderStatus_id == 6) {
			$event_type = 8;
		}

		if ($event_type) {
			$ticket_object = new Cs_ticket($this->base_object);
			$ticket_object->event($event_type, $customer_id, $order_id);
		}

		return;
	}

	private function has_order_changed($order_status_id, $order_id) {
		$event_type = 0;

		$db = $this->base_object->db;

		$sql = "SELECT * FROM orders
				WHERE id = ".$order_id." AND order_status != ".$order_status_id;

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

		return $result->num_rows > 0;
	}

	private function make_items_array($data) {
		$len = count($data['item_id']);

		for ($i = 0; $i < $len; $i++) {
			$tmp = new stdClass();

			$tmp->quantity = $data['amount'][$i];
			$tmp->item_id = $data['item_id'][$i];
			$tmp->variant_1 = $data['variant1'][$i];
			$tmp->variant_2 = $data['variant2'][$i];
			$tmp->taxes = $data['taxes'][$i];
			$tmp->price = $data['price'][$i];
			$tmp->item_status = $data['item_status'][$i];
			$tmp->item_status_text = $data['item_status_text'][$i];
			$tmp->delivery_date = $data['delivery_date'][$i];
			$tmp->backorder_quantity = $data['backorder_quantity'][$i];

			// NEW for holzeisstock
			$tmp->user_data = $data['user_data'][$i];
			$tmp->parent_item_id = $data['parent_item_id'][$i];
			$tmp->stamp = $data['stamp'][$i];

			$return[] = $tmp;
		}

		return $return;
	}

	private function make_child_items_array($data) {
		$len = count($data['is_selected']);
		$return = array();

		for ($i = 0; $i < $len; $i++) {
			if ($data['is_selected'][$i] == 1) {
				$tmp = new stdClass();

				$tmp->quantity = $data['amount'][$i];
				$tmp->item_id = $data['item_id'][$i];
				$tmp->variant_1 = $data['variant1'][$i];
				$tmp->variant_2 = $data['variant2'][$i];
				$tmp->taxes = $data['taxes'][$i];
				$tmp->price = $data['price'][$i];

				// not set / editable
				$tmp->item_status = 0;
				$tmp->backorder_quantity = 0;
				$tmp->delivery_date = '';
				$tmp->item_status_text = '';

				// NEW for holzeisstock
				$tmp->user_data = $data['user_data'][$i];
				$tmp->parent_item_id = $data['parent_item_id'][$i];
				$tmp->stamp = $data['stamp'][$i];

				$return[] = $tmp;
			}
		}

		return $return;
	}

}

?>