<?php

	class wpsg_mod_klarna extends wpsg_mod_basic
	{
		
		var $lizenz = 2;
		var $id = 816; 
		
		var $version = "3.0.6";
		//var $hilfeURL = 'http://wpshopgermany.de/?p=1575';
		
		var $free = true;
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('Klarna', 'wpsg');
			$this->group = __('Zahlungsarten', 'wpsg');
			$this->desc = __('Ermöglicht die Zahlungsart Rechnung über Klarna.', 'wpsg');
						
		} // public function __construct()
		
		public function install()
		{
			
			$this->shop->checkDefault('wpsg_mod_klarna_bezeichnung', $this->name, false, true);
			$this->shop->checkDefault('wpsg_mod_klarna_aktiv', '1');
			$this->shop->checkDefault('wpsg_mod_klarna_hint', __('Zahlen Sie auf Rechnung mit dem Zahlungsdienstleister "Klarna"', 'wpsg'), false, true);
			
			$this->shop->checkDefault('wpsg_mod_klarna_merchantID', '<!-- Erhalten Sie von Klarna --!>');
			$this->shop->checkDefault('wpsg_mod_klarna_sharedSecret', '<!-- Erhalten Sie von Klarna --!>');
			
			$this->shop->checkDefault('wpsg_mod_klarna_gebuehr', '0');
			$this->shop->checkDefault('wpsg_mod_klarna_mwst', '0');
			$this->shop->checkDefault('wpsg_mod_klarna_mwstland', '0');
			
		} // public function install()
		
		public function settings_edit()
		{
						
			$pages = get_pages();
			
			$arPages = array(
				'-1' => __('Neu anlegen und zuordnen', 'wpsg')
			);
			
			foreach ($pages as $k => $v)
			{
				$arPages[$v->ID] = $v->post_title.' (ID:'.$v->ID.')';
			}
			
			$this->shop->view['pages'] = $arPages;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_klarna/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_klarna_bezeichnung', $_REQUEST['wpsg_mod_klarna_bezeichnung']);
			$this->shop->update_option('wpsg_mod_klarna_aktiv', $_REQUEST['wpsg_mod_klarna_aktiv']);
			$this->shop->update_option('wpsg_mod_klarna_aktiv_from', $_REQUEST['wpsg_mod_klarna_aktiv_from']);
			$this->shop->update_option('wpsg_mod_klarna_aktiv_to', $_REQUEST['wpsg_mod_klarna_aktiv_to']);
			$this->shop->update_option('wpsg_mod_klarna_hint', $_REQUEST['wpsg_mod_klarna_hint']);
			
			$this->shop->update_option('wpsg_mod_klarna_merchantID', $_REQUEST['wpsg_mod_klarna_merchantID']);
			$this->shop->update_option('wpsg_mod_klarna_sharedSecret', $_REQUEST['wpsg_mod_klarna_sharedSecret']);
			
			$this->shop->update_option('wpsg_mod_klarna_sandbox', $_REQUEST['wpsg_mod_klarna_sandbox']);
			
			$this->shop->update_option('wpsg_mod_klarna_gebuehr', $_REQUEST['wpsg_mod_klarna_gebuehr']);
			$this->shop->update_option('wpsg_mod_klarna_mwst', $_REQUEST['wpsg_mod_klarna_mwst']);
			$this->shop->update_option('wpsg_mod_klarna_mwstland', $_REQUEST['wpsg_mod_klarna_mwstland']);
			
			$this->shop->createPage(__('Erfolgreiche Klarna Zahlung', 'wpsg'), 'wpsg_mod_klarna_success', $_REQUEST['wpsg_mod_klarna_success']);
			$this->shop->createPage(__('Fehlgeschlagene Klarna Zahlung', 'wpsg'), 'wpsg_mod_klarna_error', $_REQUEST['wpsg_mod_klarna_error']);
						
		} // public function settings_save()
		
		public function addPayment(&$arPayment) 
		{
			
			if (!is_admin() && $this->shop->get_option('wpsg_mod_klarna_aktiv') != '1');
			
			$mwst_value = $this->getTaxValue($this->shop->get_option('wpsg_mod_klarna_mwst'), $this->shop->getDefaultCountry());
						
			$arPayment[$this->id] = array(
				'id' => $this->id,
				'name' => __($this->shop->get_option('wpsg_mod_klarna_bezeichnung'), 'wpsg'),
				'preis' => $this->shop->get_option('wpsg_mod_klarna_gebuehr'),
				'mwst' => $this->shop->get_option('wpsg_mod_klarna_mwst'),
				'mwst_value' => $mwst_value,
				'mwst_null' => $this->shop->get_option('wpsg_mod_klarna_mwstland'),
				'hint' => __($this->shop->get_option('wpsg_mod_klarna_hint')),
				'logo' => $this->shop->getRessourceURL('mods/mod_klarna/gfx/klarna_rechnung.png'),
				'logo_100x25' => $this->shop->getRessourceURL('mods/mod_klarna/gfx/logo_100x25.png')
			);
			
		} // public function addPayment(&$arPayment)
				
		public function calcPayment(&$arBasket) 
		{ 
			
			if ($arBasket['checkout']['payment'] == $this->id)
			{
			 
				$payment_price = $this->getPreis($this->shop->get_option('wpsg_mod_klarna_gebuehr'), $arBasket['sum']['preis']);
				
				if ($this->shop->get_option('wpsg_mod_klarna_mwstland') == '1' && $arBasket['noMwSt'])
				{
					
					// Keine MwSt. berechnen !
					$arBasket['sum']['preis_payment'] = $payment_price;
					$arBasket['sum']['preis_payment_brutto'] = $payment_price;
					$arBasket['sum']['preis_payment_netto'] = $payment_price;

					$arBasket['payment']['mwst'] = 0;
					$this->shop->arPayment[$arBasket['checkout']['payment']]['mwst_value'] = 0;
						
					$arBasket['payment']['tax_rata'] = false;
					
				}
				else
				{
					
					// MwSt berechnen (Angaben im Backend sind immer Brutto)
					$this->setPaymentKosten($arBasket, $payment_price, $this->shop->get_option('wpsg_mod_klarna_mwst'));

				}
								
			}
			
		} // public function calcPayment(&$arBasket) 
		
		public function basket_save_done_array(&$order_id, &$kunde_id, &$arBasket)
		{
			
			return;
			
			$k = $this->initKlarna();
			
			foreach ($arBasket['produkte'] as $p)
			{
				
				$k->addArticle(  
				    $p['menge'],                      // Quantity  
				    $p['id'],             // Article number  
				    $p['name'],      // Article name/title  
				    $p['preis_brutto'],                 // Price  
				    $p['mwst_value'],                     // 25% VAT  
				    0,                      // Discount  
				    KlarnaFlags::INC_VAT    // Price is including VAT.  
				);
				
			}
			 
			// Versandgebühren
			$k->addArticle(  
			    1,  
			    "",  
			    __('Versandkosten', 'wpsg'),  
			    (($arBasket['sum']['preis_shipping_brutto'] > 0)?$arBasket['sum']['preis_shipping_brutto']:0),  
			    0, // MWST ?  
			    0,  
			    // Price is including VAT and is shipment fee  
			    KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT  
			);  
			
			// Zahlungsgebühren
			$k->addArticle(  
			    1,  
			    "",  
			    __('Zahlungsgebühren', 'wpsg'),  
			    (($arBasket['sum']['preis_payment_brutto'] > 0)?$arBasket['sum']['preis_payment_brutto']:0),
			    0, // MWST ?  
			    0,  
			    // Price is including VAT and is handling/invoice fee  
			    KlarnaFlags::INC_VAT | KlarnaFlags::IS_HANDLING  
			);  
			 
			// Create the address object and specify the values.  
			$addr_invoice = new KlarnaAddr(  
			    $arBasket['checkout']['email'], // email  
			    '',            // Telno, only one phone number is needed.  
			    $arBasket['checkout']['tel'],                 // Cellno  
			    $arBasket['checkout']['vname'],              // Firstname  
			    $arBasket['checkout']['name'],                   // Lastname  
			    '',                           // No care of, C/O.  
			    $arBasket['checkout']['strasse'],                // Street  
			    $arBasket['checkout']['plz'],                      // Zip Code  
			    $arBasket['checkout']['ort'],                   // City  
			    KlarnaCountry::SE,            // Country  
			    null,                         // HouseNo for German and Dutch customers.  
			    null                          // House Extension. Dutch customers only.  
			);  
			 
			$k->setAddress(KlarnaFlags::IS_BILLING, $addr_invoice);  // Billing / invoice address  
						
			if ($this->shop->callMod('wpsg_mod_shippingadress', 'check_different_shippingadress', array($k_id, $o_id)))
			{
				
				$addr_shipping = new KlarnaAddr(  
				    $arBasket['checkout']['email'], // email  
				    '',            // Telno, only one phone number is needed.  
				    $arBasket['checkout']['tel'],                 // Cellno  
				    $arBasket['checkout']['shipping_vname'],              // Firstname  
				    $arBasket['checkout']['shipping_name'],                   // Lastname  
				    '',                           // No care of, C/O.  
				    $arBasket['checkout']['shipping_strasse'],                // Street  
				    $arBasket['checkout']['shipping_plz'],                      // Zip Code  
				    $arBasket['checkout']['shipping_ort'],                   // City  
				    KlarnaCountry::SE,            // Country  
				    null,                         // HouseNo for German and Dutch customers.  
				    null                          // House Extension. Dutch customers only.  
				);
				
				$k->setAddress(KlarnaFlags::IS_SHIPPING, $addr_shipping); // Shipping / delivery address
				
			}
			else
			{
				
				$k->setAddress(KlarnaFlags::IS_SHIPPING, $addr_invoice); // Shipping / delivery address
				
			}
			 
			try 
			{  
				  
		        $result = $k->addTransaction(  
		            strtotime($arBasket['checkout']['geb']),             // PNO (Date of birth for DE and NL).  
		            null,                   // Gender.  
		            KlarnaFlags::NO_FLAG,   // Flags to affect behavior.  
		            // -1, notes that this is an invoice purchase, for part payment purchase  
		            // you will have a pclass object on which you use getId().  
		            KlarnaPClass::INVOICE  
		        );  
		      
		        // Check the order status  
		        if ($result[1] == KlarnaFlags::PENDING) 
		        {
		        	  
		            /* The order is under manual review and will be accepted or denied at a 
		               later stage. Use cronjob with checkOrderStatus() or visit Klarna 
		               Online to check to see if the status has changed. You should still 
		               show it to the customer as it was accepted, to avoid further attempts 
		               to fraud. 
		             */
		        	  
		        }  
		      
		        // Here we get the invoice number  
		        $invno = $result[0];  
		      
		        // Order is complete, store it in a database.  
		        echo "Status: {$result[1]}\nInvno: {$result[0]}\n";  
		        
		    } 
		    catch(Exception $e) 
		    {  
		    	  
		        echo "{$e->getMessage()} (#{$e->getCode()})\n";  
		        echo $e->getTraceAsString(); 
		         
		    }  
			 
		} // public function basket_save_done(&$order_id, &$kunde_id, &$oBasket)
		
		/* Modulfunktionen */
		
		/**
		 * Erstellt das KlarnaAPI Object
		 */
		private function initKlarna()
		{
			
			require_once(WPSG_PATH_MOD.'/mod_klarna/klarna_php_2.3.0/Klarna.php');
			require_once(WPSG_PATH_MOD.'/mod_klarna/klarna_php_2.3.0/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc');
			require_once(WPSG_PATH_MOD.'/mod_klarna/klarna_php_2.3.0/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc');
			
			$k = new Klarna();  
			
			$k->config(  
			    $this->shop->get_option('wpsg_mod_klarna_merchantID'),               // Merchant ID  
			    $this->shop->get_option('wpsg_mod_klarna_sharedSecret'),       // Shared Secret  
			    KlarnaCountry::SE,    // Country  
			    KlarnaLanguage::DE,   // Language  
			    KlarnaCurrency::SEK,  // Currency  
			    Klarna::BETA,         // Server  
			    'json',               // PClass Storage  
			    '/srv/pclasses.json', // PClass Storage URI path  
			    true,                 // SSL  
			    true                  // Remote logging of response times of xmlrpc calls  
			); 
			
			return $k;
			
		} // private function initKlarna()
		
	} // class wpsg_mod_klarna extends wpsg_mod_basic

?>