<?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 './libs/paymorrow/paymorrowProxyUtil.php';
include_once './core/shoppingcart.class.php';
include_once './core/country.class.php';
include_once './core/shippingmethod.class.php';

class Shop_Paymorrow {

	const PAYMORROW_CATEGORY = 'FASHION';

	private $error_message;

	private $request;
	private $order;
	private $customer;

	private $todayDateTime;

	private $iframe;
	private $request_id;

	private $customer_data;
	private $country_object;
	private $shoppingcart_object;

	public function __construct($base_object, $request_id) {
		$this->todayDateTime = date("c");

		$this->base_object = $base_object;
		$this->error_message = '';

		// setup request
		$this->request = new paymorrowOrderRequestType();

		$this->request->requestMerchantId = $this->base_object->config->shopConfiguration['paymorrow_merchant_id'];
		$this->request_id = $request_id;
		$this->request->requestId = $this->request_id;
		$this->request->requestTimestamp = $this->todayDateTime;
		$this->request->requestLanguageCode = "de";

		$this->order = false;
		$this->customer = false;

		$this->iframe = '';
		$this->customer_data = $base_object->customer->get_data();
		$this->country_object = new Country($base_object);
		$this->shoppingcart_object = new Shoppingcart($base_object);
	}

	public function get_error() {
		return $this->error_message;
	}

	public function set_order_data($delivery_charges, $payment_method_charges, $order_number) {
		$cartdata = $this->shoppingcart_object->get_data();

		// create order
		$this->order = new OrderType();

		$this->order->orderId = $order_number;
		$this->order->orderTimestamp = $this->todayDateTime;

		// add shipping details, not pricing to order
		$orderShipmentDetails = new OrderShipmentDetailType();

		$orderShipmentDetails->shipmentMethod = "STANDARD";
		$orderShipmentDetails->shipmentProvider = ShippingMethod::get_name($_POST['shipping_method']);

		$this->order->orderShipmentDetails = $orderShipmentDetails;

		foreach ($cartdata as $item) {
			if (isset($item[0]) && gettype($item[0] == 'object')) {
				// the object returned by the shoping cart class is bullshit!
				// look what I have to do to remove the crap!
				$item =  $item[0];

				$qty = $item->cartQuantity;
				$artNo = $item->number;
				$title = $item->name;
				$price = round($item->calculatedPrices['itemPriceGross'], 2);
				$vat = $item->tax;
				$discount = 0;

				$itemsArray[] = array(
					"itemQuantitiy"			 => $item->cartQuantity,
					"itemArticleId"			 => $item->number,
					"itemDescription"		 => $item->name,
					"itemCategory"			 => Shop_Paymorrow::PAYMORROW_CATEGORY,
					"itemUnitPrice"			 => round($item->calculatedPrices['itemPriceGross'], 2),
					"itemVatRate"			 => round($item->tax),
					"itemAmountInclusiveVAT" => true
				);
			}
		}

		// $delivery_charges
		if ($delivery_charges > 0) {
			$itemsArray[] = array(
				"itemQuantitiy"			 => 1,
				"itemArticleId"			 => "shipping-19",
				"itemDescription"		 => "Versandkosten",
				"itemCategory"			 => "SHIPPING",
				"itemUnitPrice"			 => $delivery_charges,
				"itemVatRate"			 => 19,
				"itemAmountInclusiveVAT" => true
			);
		}

		// $payment_method_charges
		if ($payment_method_charges > 0) {
			$itemsArray[] = array(
				"itemQuantitiy"			 => 1,
				"itemArticleId"			 => "payment-19",
				"itemDescription"		 => "Zahlungsgebuehren",
				"itemCategory"			 => "MISC",
				"itemUnitPrice"			 => $payment_method_charges,
				"itemVatRate"			 => 19,
				"itemAmountInclusiveVAT" => true
			);
		}

		$vatAmount19 = 0;
		$vatAmount7  = 0;
		$j = 0;
		$orderItemsArray = array();
		$orderAmountVATArray = array();

		while ($itemsArray[$j] != NULL) {
			// compilation of ordered items (orderItems)
			$orderItems = new orderItemType();
			$orderItems->itemId 				= $j+1;
			$orderItems->itemQuantity			= $itemsArray[$j]['itemQuantitiy'];  // quantity
			$orderItems->itemArticleId			= $itemsArray[$j]['itemArticleId'];  // product id
			$orderItems->itemDescription		= $itemsArray[$j]['itemDescription']; // product description
			$orderItems->itemCategory			= $itemsArray[$j]['itemCategory']; // paymorrow category type
			$orderItems->itemUnitPrice			= $itemsArray[$j]['itemUnitPrice']; // product unit price
			$orderItems->itemCurrencyCode		= "EUR"; // currency
			$orderItems->itemVatRate			= $itemsArray[$j]['itemVatRate']; // vat rate
			$orderItems->itemExtendedAmount		= $itemsArray[$j]['itemQuantitiy'] * $itemsArray[$j]['itemUnitPrice']; // total price of the same article
			$orderItems->itemAmountInclusiveVAT	= $itemsArray[$j]['itemAmountInclusiveVAT']; // product incl. oder excl. vat?
			$orderItemsArray[$j] 				= $orderItems;

			// calculation of VAT values (orderVatRate)
			if ($orderItems->itemVatRate	== 19) {
				$this->order->orderAmountVATTotal 	   += round((($orderItems->itemExtendedAmount*$orderItems->itemVatRate)/(100+$orderItems->itemVatRate)), 2);
				$vatAmount19 					   += round((($orderItems->itemExtendedAmount*$orderItems->itemVatRate)/(100+$orderItems->itemVatRate)), 2);
			} else if ($orderItems->itemVatRate == 7) {
				$this->order->orderAmountVATTotal 	   += round((($orderItems->itemExtendedAmount*$orderItems->itemVatRate)/(100+$orderItems->itemVatRate)), 2);
				$vatAmount7 					   += round((($orderItems->itemExtendedAmount*$orderItems->itemVatRate)/(100+$orderItems->itemVatRate)), 2);
			} else if ($orderItems->itemVatRate == 0) {
				$this->order->orderAmountVATTotal 	   += round((($orderItems->itemExtendedAmount*$orderItems->itemVatRate)/(100+$orderItems->itemVatRate)), 2);
				$vatAmount0 					   += round((($orderItems->itemExtendedAmount*$orderItems->itemVatRate)/(100+$orderItems->itemVatRate)), 2);
			}
			//calculation of gross and net order value
			$this->order->orderAmountNet		+= round((($orderItems->itemExtendedAmount*100)/(100+$orderItems->itemVatRate)), 2); // Nettopreis der gesammten Bestellung
			$this->order->orderAmountGross	+= $orderItems->itemExtendedAmount; // Bruttopreis der gesammten Bestellung

			$j++;
		}
		$this->order->orderItems=$orderItemsArray;

		//compilation of VAT values (orderVatRate)
		$k = 0;
		if ($vatAmount19 != 0) {
			$orderVatRateType19 = new orderVatRate();
			$orderVatRateType19->vatRate			= 19;
			$orderVatRateType19->orderVatAmount = $vatAmount19;
			$orderAmountVATArray[$k] = $orderVatRateType19;

			$k++;
		}

		if ($vatAmount7 != 0) {
			$orderVatRateType7 = new orderVatRate();
			$orderVatRateType7->vatRate			= 7;
			$orderVatRateType7->orderVatAmount = $vatAmount7;
			$orderAmountVATArray[$k] = $orderVatRateType7;

			$k++;
		}

		if ($vatAmount0 != 0) {
			$orderVatRateType0 = new orderVatRate();
			$orderVatRateType0->vatRate = 0;
			$orderVatRateType0->orderVatAmount = 0;
			$orderAmountVATArray[$k] = $orderVatRateType0;

			$k++;
		}

		$orderAmountVAT = new orderAmountVatType();

		$orderAmountVAT->orderVatRate = $orderAmountVATArray;

		$this->order->orderAmountVAT = $orderAmountVAT;

		$this->order->orderCurrencyCode = "EUR";
	}

	public function set_address($billing_address, $shipping_address) {
		//echo "in the function<br />";
		// add customer information to customer
		$this->customer = new customerType();
		//echo "after make customer</br />";
		$this->customer->customerId = $this->customer_data->number;
		$this->customer->customerIPAddress = $_SERVER['REMOTE_ADDR'];
		$this->customer->customerPreferredLanguage = "de";
		//echo "after seting some customer data<br />";
		$customerPersonalDetails = new customerPersonalDetailsType();
		//echo "after new customer personal data<br />";
		$customerPersonalDetails->customerGivenName = $billing_address['firstname'];
		$customerPersonalDetails->customerSurname = $billing_address['surname'];
		$customerPersonalDetails->customerEmail = $this->customer_data->email;
		//echo "after seting some personal data<br />";
		if ($billing_address['honorific'] != 2) {
			$this->customer->orderCustomerType = "PERSON";
			if ($billing_address['honorific'] == 0) {
				$customerPersonalDetails->customerGender = "M";
			} else if ($billing_address['honorific'] == 1) {
				$customerPersonalDetails->customerGender = "F";
			}
		} else {
			throw new Exception('customer is company');
		}
		//echo "damn<br />";
		$customerPersonalDetails->customerDateOfBirth = $this->customer_data->burth_date;
		if ($this->customer_data->phone != '') {
			$customerPersonalDetails->customerPhoneNo = $this->customer_data->phone;
		} else if ($this->customer_data->mobile != '') {
			$customerPersonalDetails->customerPhoneNo = $this->customer_data->mobile;
		} else {
			$customerPersonalDetails->customerPhoneNo = '';
		}

		$this->customer->customerPersonalDetails = $customerPersonalDetails;

		// add billing address to customer
		$customerAddress = new AddressType();

		$customerAddress->addressStreet = $billing_address['street'];
		$customerAddress->addressHouseNo = $billing_address['house_number'];
		$customerAddress->addressPostalCode = $billing_address['zip_code'];
		$customerAddress->addressLocality = $billing_address['city'];

		// get country code for country ID
		$this->country_object->set_id($billing_address['country']);
		$customerAddress->addressCountryCode = $this->country_object->get_data()->iso_code_2;

		$this->customer->customerAddress = $customerAddress;

		// add shipping address to order
		$addressShipmentType = new AddressType();

		$addressShipmentType->addressStreet = $shipping_address['street'];
		$addressShipmentType->addressHouseNo = $shipping_address['house_number'];
		$addressShipmentType->addressPostalCode = $shipping_address['zip_code'];
		$addressShipmentType->addressLocality = $shipping_address['city'];

		// get country code for country ID
		$this->country_object->set_id($shipping_address['country']);
		$addressShipmentType->addressCountryCode = $this->country_object->get_data()->iso_code_2;

		$this->order->orderShippingAddress = $addressShipmentType;
	} // end set_address

	public function transaction() {
		$requestMerchantUrls = new requestMerchantUrlType();
		$return_url = 'http://'.$_SERVER['SERVER_NAME'].'/Kasse/';
		$requestMerchantUrls->merchantSuccessUrl = $return_url;
		$requestMerchantUrls->merchantPaymentMethodChangeUrl = $return_url;
		$requestMerchantUrls->merchantNotificationUrl = 'http://'.$_SERVER['SERVER_NAME'].'/LightingRod/';

		$this->request->requestMerchantUrls = $requestMerchantUrls;

		$this->order->orderCustomer = $this->customer;

		$this->request->order = $this->order;

		$paymorrowOrderResponse = sendRequestToPaymorrow($this->request, $this->base_object->config->shopConfiguration['paymorrow_pass']);

		/*if ($paymorrowOrderResponse->responseError) {
			$this->error_message =	"error type = ".$paymorrowOrderResponse->responseError->responseErrorType.
							", error no = ".$paymorrowOrderResponse->responseError->responseErrorNo.
							", erro msg = ".$paymorrowOrderResponse->responseError->responseErrorMessage;
		}*/

		if ($paymorrowOrderResponse->responseResultCode == 'ACCEPTED') {
			$this->iframe = $paymorrowOrderResponse->responseResultURL;

			return true;
		}

		return false;
	}

	public function get_iframe_url() {
		return $this->iframe;
	}

}
