<?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
 */

// including libs
include_once './libs/klarna/Klarna.php';
include_once './libs/xmlrpc/xmlrpc.inc';
include_once './libs/xmlrpc/xmlrpc_wrappers.inc';

class Shop_klarna {

	private $error_message;
	private $base_object;
	private $customer_data;
	private $shoppingcart;

	public function __construct($base_object) {

		$this->error_message = '';

		$this->klarna = new Klarna();
		KlarnaConfig::$store = false;

		$this->base_object = $base_object;
		$this->customer_data = $base_object->customer->get_data();
		$this->shoppingcart = false;

		//Create the config object, since we aren't storing the file, we
		//don't need to specify a URI.
		$config = new KlarnaConfig($file = null);

		$config['eid'] = 0; //Merchant ID or Estore ID, an integer above 0
		if (isset($this->base_object->config->shopConfiguration['klarna_eid']) && $this->base_object->config->shopConfiguration['klarna_eid']) {
			$config['eid'] = $this->base_object->config->shopConfiguration['klarna_eid'];
		}

		$config['secret'] = ''; //The shared secret / password
		if (isset($this->base_object->config->shopConfiguration['klarna_secret']) && $this->base_object->config->shopConfiguration['klarna_secret']) {
			$config['secret'] = $this->base_object->config->shopConfiguration['klarna_secret'];
		}

		if ($this->customer_data->default_address_country_id == 27) {
			$config['country'] = KlarnaCountry::DE;
		} else if ($this->customer_data->default_address_country_id == 29) {
			$config['country'] = KlarnaCountry::AT;
		} else {
			$config['country'] = KlarnaCountry::DE;
		}

		$config['language'] = KlarnaLanguage::DE;
		$config['currency'] = KlarnaCurrency::EUR;
		$config['mode'] = Klarna::LIVE; //or Klarna::BETA, depending on	which server your eid is associated with.

		//Define pclass settings:
		$config['pcStorage'] = 'json'; //Which storage module? can be json, xml or mysql.
		$config['pcURI'] = './web/'.SHOP_SYSTEM.'/config/pclasses.json'; //Where the json filefor the pclasses are stored.

		//Should we use HTTPS?
		$config['ssl']  = true;

		//Should we error report/status report to Klarna?
		$config['candice'] = true; //(set to false if your server doesn't support UDP)

		$config['xmlrpcDebug'] = false;

		//Do we want to see normal debug information?
		$config['debug'] = true;

		//Set the config object.
		$this->klarna->setConfig($config);
	} // end __construct


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


	public function set_shoppingcart($shoppingcart) {
		$this->shoppingcart = $shoppingcart;
	} // end set_shoppingcart


	public function set_order_data($delivery_charges, $payment_method_charges) {
		if ($this->shoppingcart) {

			$tax = key($this->shoppingcart['tax_values']);
			foreach ($this->shoppingcart['items'] as $item) {
				$qty = $item->quantity;
				$artNo = $item->number;
				$title = utf8_decode($item->name);
				$price = round($item->calculatedPrices['itemPriceGross'], 2);
				$vat = 19;//$tax;
				$discount = 0;
				$flags = KlarnaFlags::INC_VAT;

				$this->klarna->addArticle($qty, $artNo, $title, $price, $vat, $discount, $flags);
			}

			// $delivery_charges 
			$this->klarna->addArticle(
				$qty = 1,
				$artNo = "",
				$title = "Versandkosten",
				$price = $delivery_charges,
				$vat = 19,
				$discount = 0,
				$flags = KlarnaFlags::INC_VAT + KlarnaFlags::IS_SHIPMENT 
			);

			// $payment_method_charges
			$this->klarna->addArticle(
				$qty = 1,
				$artNo = "",
				$title = "Zahlungsgebuehren",
				$price = $payment_method_charges,
				$vat = 19,
				$discount = 0,
				$flags = KlarnaFlags::INC_VAT + KlarnaFlags::IS_HANDLING
			);

			if (isset($this->shoppingcart['gift_certificate_code'])) {
				foreach ($this->shoppingcart['tax_values'] as $key => $value) {
					$this->klarna->addArticle(
						$qty = 1,
						$artNo = "",
						$title = "Gutscheine ".$this->shoppingcart['gift_certificate_code'].' zu '.$value['gift']['percent'].'%',
						$price = - $value['gift']['gross'],
						$vat = $key,
						$discount = 0,
						$flags = KlarnaFlags::INC_VAT
					);
				}
			}
		}
	} // end set_order_data


	public function set_address($billing_address, $shipping_address) {
		if ($this->customer_data->default_address_country_id == 27) {
			$country = KlarnaCountry::DE;
		} else if ($this->customer_data->default_address_country_id == 29) {
			$country = KlarnaCountry::AT;
		} else {
			$country = KlarnaCountry::DE;
		}

		$addr_billing = new KlarnaAddr(
			$email = $this->customer_data->email,
			$telno = $this->customer_data->phone,
			$cellno = $this->customer_data->mobile,
			$fname = utf8_decode($billing_address['firstname']),
			//$fname = $billing_address['firstname'],
			$lname = utf8_decode($billing_address['surname']),
			//$lname = $billing_address['surname'],
			$careof = '',
			$street = utf8_decode($billing_address['street']),
			//$street = $billing_address['street'],
			$zip = $billing_address['zip_code'],
			$city = utf8_decode($billing_address['city']),
			//$city = $billing_address['city'],
			//$country = KlarnaCountry::DE,
			$country,
			$houseNo = utf8_decode($billing_address['house_number']),
			//$houseNo = $billing_address['house_number'],
			$houseExt = null
		);

		$addr_shipping = new KlarnaAddr(
			$email = $this->customer_data->email,
			$telno = $this->customer_data->phone,
			$cellno = $this->customer_data->mobile,
			$fname = utf8_decode($shipping_address['firstname']),
			//$fname = $shipping_address['firstname'],
			$lname = utf8_decode($shipping_address['surname']),
			//$lname = $shipping_address['surname'],
			$careof = '',  //No care of, C/O.
			$street = utf8_decode($shipping_address['street']),
			//$street = $shipping_address['street'],
			$zip = $shipping_address['zip_code'],
			$city = utf8_decode($shipping_address['city']),
			//$city = $shipping_address['city'],
			//$country = KlarnaCountry::DE,
			$country,
			$houseNo = utf8_decode($shipping_address['house_number']),
			//$houseNo = $shipping_address['house_number'],
			$houseExt = null
		);

		//Next we tell the Klarna instance to use the address in the next order.
		$this->klarna->setAddress(KlarnaFlags::IS_BILLING, $addr_billing); //Billing / invoice address
		$this->klarna->setAddress(KlarnaFlags::IS_SHIPPING, $addr_shipping); //Shipping / delivery address
	} // end set_address


	public function transaction_test($pay_in_installments = false) {
		global $DEVMODE;

		try {
			$pno = substr($this->customer_data->burth_date,8,2).substr($this->customer_data->burth_date,5,2).substr($this->customer_data->burth_date,0,4);

			if ($this->customer_data->honorific == 2) {
				// company
				$this->error_message = 'Klarna steht nur Privatkunden zur Verf&uuml;gung. Bitte w&auml;hlen Sie eine andere Bezahlmethode.';

				return false;
			} else if ($this->customer_data->honorific == 1) {
				$gender = KlarnaFlags::FEMALE; //The customer is a male.
			} else {
				$gender = KlarnaFlags::MALE; //The customer is a male.
			}
			$flags = KlarnaFlags::NO_FLAG; //No specific behaviour like TEST_MODE.^

			// pclass values:
			// -1 -> Rechnung
			// 2882 -> Finanzierung (24 Monate)
			$pclass = KlarnaPClass::INVOICE;
			if ($pay_in_installments) {
				$pclass = 2882;
			}

			$result = $this->klarna->addTransaction($pno, $gender, $flags, $pclass);

			//Check the order status
			if ($result[1] == KlarnaFlags::ACCEPTED) {
				//$this->klarna->deleteInvoice($result[0]);

				return true;
			} else if ($result[1] == KlarnaFlags::PENDING) {
				$this->klarna->deleteInvoice($result[0]);

				$this->error_message = 'Klarna ist f&uuml;r Sie nicht verf&uuml;gbar, bitte w&auml;hlen Sie eine andere Bezahlmethode.';

				return false;
			} else if ($result[1] == KlarnaFlags::DENIED) {
				$this->error_message = 'Sie k&ouml;nnen bei uns nicht mit Klarna bestellen. Bitte w&auml;hlen sei eine andere Bezahlmethode. Sie k&ouml;nnen sich mit Klarna in Verbindung setzen wenn sie trotzdem mit Klarna bezahlen wollen. ';

				return false;
			}
		} catch(Exception $e) {
			//The purchase was denied or something went wrong, print the message:
			if ($DEVMODE) {
				echo "<pre>".$e->getMessage()." (#".$e->getCode().")</pre>";

				$this->error_message = $e->getMessage();
			} else {
				//$this->error_message = "ERROR NR: ".$e->getCode().' '.$e->getMessage();
				$this->error_message = utf8_encode($e->getCode()).' : '.utf8_encode($e->getMessage());
			}
		}

		return false;
	} // end transaction_test


	public function transaction($pay_in_installments = false) {
		try {
			$pno = substr($this->customer_data->burth_date,8,2).substr($this->customer_data->burth_date,5,2).substr($this->customer_data->burth_date,0,4);
			if ($this->customer_data->honorific == 2) {
				// company
				$this->error_message = 'Klarna steht nur Privatkunden zur Verf&uuml;gung. Bitte w&auml;hlen Sie eine andere Bezahlmethode.';

				return false;
			} else if ($this->customer_data->honorific == 1) {
				$gender = KlarnaFlags::FEMALE; //The customer is a male.
			} else {
				$gender = KlarnaFlags::MALE; //The customer is a male.
			}
			$flags = KlarnaFlags::NO_FLAG; //No specific behaviour like TEST_MODE.^

			// pclass values:
			// -1 -> Rechnung
			// 2882 -> Finanzierung (24 Monate)
			$pclass = KlarnaPClass::INVOICE;
			if ($pay_in_installments) {
				$pclass = 2882;
			}

			$result = $this->klarna->addTransaction($pno, $gender, $flags, $pclass);

			//Check the order status
			if ($result[1] == KlarnaFlags::ACCEPTED) {

				return $result[0];
			} else if ($result[1] == KlarnaFlags::PENDING) {

				$this->klarna->deleteInvoice($result[0]);
				$this->error_message = 'Klarna ist f&uuml;r Sie nicht verf&uuml;gbar, bitte w&auml;hlen Sie eine andere Bezahlmethode.';

				return false;
			} else if ($result[1] == KlarnaFlags::DENIED) {

				$this->error_message = 'Sie k&ouml;nnen bei uns nicht mit Klarna bestellen. Bitte w&auml;hlen sei eine andere Bezahlmethode. Sie k&ouml;nnen sich mit Klarna in Verbindung setzen wenn sie trotzdem mit Klarna bezahlen wollen. ';

				return false;
			}
		} catch(Exception $e) {
			//The purchase was denied or something went wrong, print the message:
			if ($DEVMODE) {
				echo "<pre>".$e->getMessage()." (#".$e->getCode().")</pre>";

				exit();
			} else {
				$this->error_message = utf8_encode($e->getMessage());
			}
		}

		return false;
	} // end transaction


	public function get_installments($sum) {

		$data = array();
		$flag = KlarnaFlags::PRODUCT_PAGE; // or KlarnaFlags::CHECKOUT_PAGE, if you want
		// to do it for the whole order.
		$pclass = $this->klarna->getCheapestPClass($sum, $flag);

		// Did we get a PClass? (it is false if we didn't)
		if ($pclass) {
			// Here we reuse the same values as above:
			$value = KlarnaCalc::calc_monthly_cost(
					$sum,
					$pclass,
					$flag
			);
			$data[] = array(
					'months' => 24,
					'monthly_costs' => $value
			);
		}

		/*
		$installments = get_pclass_ids();
		foreach ($installments as $inst) {
			$type = get_type($inst);
			if ($type == 1) {
				// calc monthly costs
				$flag = KlarnaFlags::PRODUCT_PAGE; //or KlarnaFlags::CHECKOUT_PAGE, if you want to do it for the whole order.
				$pclass = $this->klarna->getCheapestPClass($sum, $flag);
				//Did we get a PClass? (it is false if we didn't)
				if ($pclass) {
					//Here we reuse the same values as above:
					$monthly_costs = KlarnaCalc::calc_monthly_cost(
							$sum,
							$pclass,
							$flag
					);
				}
				if ($monthly_costs) {
					$data[$inst] = array(
						'months' => get_months($inst),
						'monthly_costs' => $monthly_costs
					);
				}
			}
		}*/

		return  $data;
	} // end get_installments


	public function activate($invoice_number) {
		global $DEVMODE;

		try {
			$this->klarna->activateInvoice($invoice_number);

			return true;
		} catch(Exception $e) {
			//The purchase was denied or something went wrong, print the message:
			if ($DEVMODE) {
				echo "<pre>".$e->getMessage()." (#".$e->getCode().")</pre>";

				$this->error_message = utf8_encode($e->getMessage());
			} else {
				$this->error_message = utf8_encode($e->getMessage());
			}

			return false;
		}
	} // end activate


	public function delete($invoice_number) {
		global $DEVMODE;

		try {
			$this->klarna->deleteInvoice($invoice_number);

			return true;
		} catch(Exception $e) {
			//The purchase was denied or something went wrong, print the message:
			if ($DEVMODE) {
				echo "<pre>".$e->getMessage()." (#".$e->getCode().")</pre>";

				$this->error_message = utf8_encode($e->getMessage());
			} else {
				$this->error_message = utf8_encode($e->getMessage());
			}

			return false;
		}
	} // end delete


} // ene Shop_klarna

//include('./web/'.SHOP_SYSTEM.'/config/pclass.php');
