<?php

	/**
	 * Ermöglicht die Zahlungsabwicklung über SecurePay
	 * @author daniel
	 */
	class wpsg_mod_securepay extends wpsg_mod_basic
	{
		
		var $lizenz = 2;
		var $id = 3060;
		var $hilfeURL = 'http://wpshopgermany.maennchen1.de/?p=3847';
		var $currency = 'EUR';
		var $version = "9.9.9";
		var $free = true;
		
		var $curl_options = array(
			CURLINFO_HEADER_OUT => true,
			CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded;charset=UTF-8'),
			CURLOPT_FOLLOWLOCATION => 0,
			/*CURLOPT_SSL_VERIFYPEER => false*/
		);
		
		var $api_url = array(
			'generateToken' => array(
				'live' => 'https://ctpe.net/frontend/GenerateToken',
				'test' => 'https://test.ctpe.net/frontend/GenerateToken'		
			),
			'widgetjs' => array(
				'live' => 'https://ctpe.net/frontend/widget/v3/widget.js',
				'test' => 'https://test.ctpe.net/frontend/widget/v3/widget.js'
			),
			'GetStatus' => array(
				'live' => 'https://ctpe.net/frontend/GetStatus;jsessionid=',
				'test' => 'https://test.ctpe.net/frontend/GetStatus;jsessionid=',
			)
		);
		
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('SecurePay IW-Systeme', 'wpsg');
			$this->group = __('Zahlungsarten', 'wpsg');
			$this->desc = __('Ermöglicht die Zahlung über SecurePay IW-Systeme.', 'wpsg');
			
		} // public function __construct()
		
		public function install()
		{
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			$sql = "CREATE TABLE ".WPSG_TBL_ORDER." (
		   		wpsg_mod_securepay_ident VARCHAR(255) NOT NULL
		   	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);

			$this->shop->checkDefault('wpsg_mod_securepay_sandbox', '0');
			
			$this->shop->checkDefault('wpsg_mod_securepay_activ', '0');
			$this->shop->checkDefault('wpsg_mod_securepay_paymenttypes', 'MASTER VISA');
			$this->shop->checkDefault('wpsg_mod_securepay_name', __('SecurePay IW-Systeme', 'wpsg'), false, true);
			$this->shop->checkDefault('wpsg_mod_securepay_hint', __('SecurePay IW-Systeme bietet eine sichere Art der Zahlung und unterstützt dabei verschiedene Zahlungsmöglichkeiten.', 'wpsg'), false, true);
			$this->shop->checkDefault('wpsg_mod_securepay_language', 'de');
						
		} // 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['wpsg_mod_securepay']['arPages'] = $arPages;
				
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_securepay/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function settings_save()
		{
						
			$this->shop->update_option('wpsg_mod_securepay_sandbox', $_REQUEST['wpsg_mod_securepay_sandbox']);
			$this->shop->update_option('wpsg_mod_securepay_sender', $_REQUEST['wpsg_mod_securepay_sender']);
			$this->shop->update_option('wpsg_mod_securepay_channelid', $_REQUEST['wpsg_mod_securepay_channelid']);
			$this->shop->update_option('wpsg_mod_securepay_userid', $_REQUEST['wpsg_mod_securepay_userid']);
			$this->shop->update_option('wpsg_mod_securepay_password', $_REQUEST['wpsg_mod_securepay_password']);
			
			$this->shop->update_option('wpsg_mod_securepay_activ', $_REQUEST['wpsg_mod_securepay_activ']);
			$this->shop->update_option('wpsg_mod_securepay_paymenttypes', $_REQUEST['wpsg_mod_securepay_paymenttypes']);
			$this->shop->update_option('wpsg_mod_securepay_name', $_REQUEST['wpsg_mod_securepay_name']); $this->shop->addTranslationString('wpsg_mod_securepay_name', $_REQUEST['wpsg_mod_securepay_name']);
			$this->shop->update_option('wpsg_mod_securepay_hint', $_REQUEST['wpsg_mod_securepay_hint']); $this->shop->addTranslationString('wpsg_mod_securepay_hint', $_REQUEST['wpsg_mod_securepay_hint']);
			$this->shop->update_option('wpsg_mod_securepay_logo', $_REQUEST['wpsg_mod_securepay_logo']);			
			$this->shop->update_option('wpsg_mod_securepay_language', $_REQUEST['wpsg_mod_securepay_language']);
			$this->shop->update_option('wpsg_mod_securepay_gebuehr', $_REQUEST['wpsg_mod_securepay_gebuehr']);
			$this->shop->update_option('wpsg_mod_securepay_mwst', $_REQUEST['wpsg_mod_securepay_mwst']);
			$this->shop->update_option('wpsg_mod_securepay_mwstland', $_REQUEST['wpsg_mod_securepay_mwstland']);
			
			$this->shop->createPage(__('Erfolgreiche Zahlung', 'wpsg'), 'wpsg_mod_securepay_successPage', $_REQUEST['wpsg_mod_securepay_successPage']);
			$this->shop->createPage(__('Fehlerhafte Zahlung', 'wpsg'), 'wpsg_mod_securepay_errorPage', $_REQUEST['wpsg_mod_securepay_errorPage']);
			
		} // public function settings_save()
		
		public function addPayment(&$arPayment)
		{
				
			if (is_admin() || $this->shop->get_option('wpsg_mod_securepay_activ') == '1')
			{
		
				$mwst_value = $this->getTaxValue($this->shop->get_option('wpsg_mod_securepay_mwst'), $this->shop->getDefaultCountry());
		
				$arPayment[$this->id] = array(
					'id' => $this->id,
					'name' => __($this->shop->get_option('wpsg_mod_securepay_name'), 'wpsg'),
					'preis' => $this->shop->get_option('wpsg_mod_securepay_gebuehr'),
					'mwst' => $this->shop->get_option('wpsg_mod_securepay_mwst'),
					'mwst_value' => $mwst_value,
					'mwst_null' => $this->shop->get_option('wpsg_mod_securepay_mwstland'),
					'hint' => __($this->shop->get_option('wpsg_mod_securepay_hint'), 'wpsg'),
					'logo' => ((wpsg_isSizedString($this->shop->get_option('wpsg_mod_securepay_logo')))?$this->shop->get_option('wpsg_mod_securepay_logo'):$this->shop->getRessourceURL('mods/mod_securepay/gfx/securepay.png')),
					'logo_100x25' => $this->shop->getRessourceURL('mods/mod_securepay/gfx/logo_100x25.png')
				);
		
				$this->setPayShipPrice($this->shop->get_option('wpsg_mod_securepay_gebuehr'), $mwst_value, $arPayment, $this->id);
		
			}
			
		} // public function addPayment(&$arPayment)
		
		public function calcPayment(&$arBasket)
		{
		
			if ($this->id == $arBasket['checkout']['payment'])
			{
				
				$payment_price = $this->getPreis($this->shop->get_option('wpsg_mod_securepay_gebuehr'), $arBasket['sum']['preis']);
				$mwstland = $this->shop->get_option('wpsg_mod_securepay_mwstland');
				$mwst = $this->shop->get_option('wpsg_mod_securepay_mwst');

				if ($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, $mwst);
				
				}
				
			}
			
		} // public function calcPayment(&$arBasket)
		
		public function order_done(&$order_id, &$done_view)
		{
		
			global $q_config;
			
			// Bestellungen mit 0 geben nix aus
			if ($done_view['basket']['sum']['preis_gesamt_brutto'] <= 0) return;
			
			if ($this->id == $this->shop->view['basket']['checkout']['payment'])
			{
			
				// Ident Request
				$ident = $this->getIdent($order_id);
 
				if ($ident !== false)
				{
					
					$this->shop->view['wpsg_mod_securepay']['ident'] = $ident;
					$this->shop->view['wpsg_mod_securepay']['statusURL'] = $this->getStatusUrl();		

					$widgetURL = $this->api_url['widgetjs']['live'];
					if ($this->shop->get_option('wpsg_mod_securepay_sandbox') === '1') $widgetURL = $this->api_url['widgetjs']['test'];
					
					$set_lang = $this->shop->get_option('wpsg_mod_securepay_language');
					if ($set_lang === 'auto')
					{
						
						$arLocales = $q_config['locale'];
						
						if (wpsg_isSizedArray($arLocales) && wpsg_isSizedString(get_locale()) && in_array(get_locale(), $arLocales))
						{
						
							$set_lang = array_search(get_locale(), $arLocales);
						
						}
						else
						{
						
							// Wenn Mehrsprachigkeit nicht korrekt konfiguriert oder ISO Code nicht ermittelt werden konnte
							// auf die schöne gute alte deutsche Sprache zurückgreifen
							$set_lang = "de";
						
						}
						
					}
					
					$set_lang = strtolower($set_lang);
					if (!in_array($set_lang, array('de', 'en'))) $set_lang = 'de';
					
					$widgetURL .= '?style=card&language='.$set_lang;
					
					$this->shop->view['wpsg_mod_securepay']['paymenttypes'] = $this->shop->get_option('wpsg_mod_securepay_paymenttypes');
					$this->shop->view['wpsg_mod_securepay']['widgetjs'] = $widgetURL;
					 
				}
				else
				{
					
					$log = array();
					$log[] = "Token konnte nicht gebildet werden.";
					$log[] = "\r\nCURL Error: ".$this->shop->last_curl_error;
					
					$log = implode("\r\n", $log);
					 					
					// Eintrag im Bestellprotokoll
					$this->db->ImportQuery(WPSG_TBL_OL, array(
						"title" => __("SecurePay IW-Systeme Fehler", "wpsg"),
						"cdate" => "NOW()",
						"o_id" => wpsg_q($order_id),
						"mailtext" => wpsg_q($log_txt)
					));
										
					$this->shop->view['wpsg_mod_securepay']['ident'] = false;
					
				}
			 
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_securepay/order_done.phtml');
			
			}
			
		} // public function order_done(&$order_id, &$done_view)
			
		public function wp_loaded()
		{
		
			if ($_REQUEST['wpsg_plugin'] != 'wpsg_mod_securepay') return;
			
			if ($_REQUEST['wpsg_action'] === 'checkStatus')
			{
				
				$arParam = array();
				
				$url = $this->api_url['GetStatus']['live'];
				if ($this->shop->get_option('wpsg_mod_securepay_sandbox') === '1') $url = $this->api_url['GetStatus']['test']; 
				
				$url .= $_REQUEST['token'];
				
				$result = $this->shop->get_url_post_content($url, $arParam, $this->curl_options);
				$resultJson = json_decode($result, true);
				
				if (	strstr($resultJson['transaction']['processing']['result'], "ACK") && 
						wpsg_isSizedInt($resultJson['transaction']['identification']['shopperid']) &&
						wpsg_isSizedString($resultJson['transaction']['payment']['clearing']['amount'])
					)
				{
					
					$order_id = $resultJson['transaction']['identification']['shopperid'];
					$payed_amount = wpsg_tf($resultJson['transaction']['payment']['clearing']['amount']);
					
					$log = print_r($resultJson, 1);
					
					$this->db->ImportQuery(WPSG_TBL_OL, array(
						"title" => __("SecurePay IW-Systeme Zahlung erfolgt", "wpsg"),
						"cdate" => "NOW()",
						"o_id" => wpsg_q($order_id),
						"mailtext" => wpsg_q($log)
					));
						
					if ($this->shop->setPayMent($order_id, $payed_amount))
					{
							
						$this->shop->setOrderStatus($order_id, 100, true);

						// Zahlung erfolgreich
						$this->shop->redirect(get_permalink($this->shop->get_option('wpsg_mod_securepay_successPage')));
						
					}
					else
					{
						
						// Zahlung fehlgeschlagen / Betrag war nicht korrekt
						$this->shop->redirect(get_permalink($this->shop->get_option('wpsg_mod_securepay_errorPage')));
						
					}
					
				}
				else
				{

					// Zahlung fehlgeschlagen
					$this->shop->redirect(get_permalink($this->shop->get_option('wpsg_mod_securepay_errorPage')));
					
				} 
								
			}		
				
		} // public function wp_loaded()
		
		public function mail_payment()
		{
		
			if ($this->id != $this->shop->view['basket']['checkout']['payment']) return;
		
			if ($this->shop->htmlMail === true)
			{
				
				echo '<a href="'.$this->shop->getDoneURL($this->shop->view['o_id']).'">'.__('Zahlungslink', 'wpsg').'</a>'.__(', um die Zahlung durchzuführen', 'wpsg');
				
			}
			else
			{
			
				echo wpsg_pad_right(__('Zahlungslink', 'wpsg').':', 35).$this->shop->getDoneURL($this->shop->view['o_id']);
				
			}
		
		} // public function mail_payment()
				
		/* Modulfunktionen */
		
		/**
		 * URL für die Statusabfrage
		 */
		public function getStatusUrl()
		{
			
			$basket_link = get_permalink($this->shop->get_option('wpsg_page_basket'));
				
			if (strpos($basket_link, "?") > 0)
			{
				$basket_link .= "&wpsg_plugin=wpsg_mod_securepay&wpsg_action=checkStatus";
			}
			else
			{
				$basket_link .= "?wpsg_plugin=wpsg_mod_securepay&wpsg_action=checkStatus";
			}
			
			return $basket_link;
			
		} // public function getStatusUrl()
		
		/**
		 * Initiiert den Zahlungsprozess und gibt die Ident zurück und speichert sie in der Bestellung
		 */
		public function getIdent($order_id)
		{
			
			$oOrder = $this->shop->cache->loadOrderObject($order_id);
			
			$arParam = array(
				'SECURITY.SENDER' => $this->shop->get_option('wpsg_mod_securepay_sender'),
				'TRANSACTION.CHANNEL' => $this->shop->get_option('wpsg_mod_securepay_channelid'),
				'TRANSACTION.MODE' => 'LIVE',
				'IDENTIFICATION.SHOPPERID' => $order_id,
				'USER.LOGIN' => $this->shop->get_option('wpsg_mod_securepay_userid'),
				'USER.PWD' => $this->shop->get_option('wpsg_mod_securepay_password'),
				'PAYMENT.TYPE' => 'DB',
				'PRESENTATION.AMOUNT' => $oOrder->getAmount(),
				'PRESENTATION.CURRENCY' => 'EUR'
			);
			
			if ($this->shop->get_option('wpsg_mod_securepay_sandbox') === '1') $arParam['TRANSACTION.MODE'] = 'CONNECTOR_TEST'; 
			
			$url = $this->api_url['generateToken']['live'];
			if ($this->shop->get_option('wpsg_mod_securepay_sandbox') === '1') $url = $this->api_url['generateToken']['test'];
			 
			$result = $this->shop->get_url_post_content($url, $arParam, $this->curl_options);
			$ident = json_decode($result);
		 
			$token = $ident->transaction->token;
			
			if (strpos($result, 'Erorr') !== false || !is_object($ident) || !wpsg_isSizedString($token))
			{
				
				return false;
				
			}
			else 
			{
				
				$oOrder->wpsg_mod_securepay_ident = $token;
				$oOrder->save();
				
				return $token;
				
			}
			
		} // public function getIdent($order_id)
				  
	} // class wpsg_mod_securepay extends wpsg_mod_basic

?>