<?php

	/**
	 * Dieses Modul erlaubt die Zahlungsart "Bankeinzug"
	 * @author daniel 
	 */
	class wpsg_mod_autodebit extends wpsg_mod_basic
	{
		
		var $lizenz = 2;
		var $id = 20;
		var $hilfeURL = 'http://wpshopgermany.de/?p=3879';
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('Bankeinzug', 'wpsg');
			$this->group = __('Zahlungsarten', 'wpsg');
			$this->desc = __('Ermöglicht die Zahlungsart Bankeinzug.', 'wpsg');
						
		} // public function __construct()
		
		public function install()
		{
			 
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			/**
			 * Bestelltabelle erweitern
			 */ 
			$sql = "CREATE TABLE ".WPSG_TBL_ORDER." (
		   		mod_autodebit_name VARCHAR(255) NOT NULL,
		   		mod_autodebit_blz VARCHAR(255) NOT NULL,
				mod_autodebit_bic VARCHAR(11) NOT NULL,
		   		mod_autodebit_inhaber VARCHAR(255) NOT NULL,
		   		mod_autodebit_knr VARCHAR(255) NOT NULL,
				mod_autodebit_iban VARCHAR(255) NOT NULL
		   	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
   	   	 
   			dbDelta($sql);
   			
   			$this->shop->checkDefault('wpsg_mod_autodebit_bezeichnung', $this->name, false, true);
   			$this->shop->checkDefault('wpsg_mod_autodebit_aktiv', '1');
   			$this->shop->checkDefault('wpsg_mod_autodebit_hint', __('Wählen Sie diese Zahlungsart wenn sie uns eine Einzugsermächtigung für ihr Konto erteilen möchten. Wir benötigen dazu folgende Angaben:', 'wpsg'), false, true);
   			$this->shop->checkDefault('wpsg_mod_autodebit_gebuehr', '0');
   			$this->shop->checkDefault('wpsg_mod_autodebit_mwst', '0');
   			$this->shop->checkDefault('wpsg_mod_autodebit_mwstland', '0');
   			$this->shop->checkDefault('wpsg_mod_autodebit_iban', '1');
			
		} // public function install()
		
		public function settings_edit()
		{
									
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_autodebit/settings_edit.phtml');
			
		}
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_autodebit_bezeichnung', $_REQUEST['wpsg_mod_autodebit_bezeichnung']);
			$this->shop->update_option('wpsg_mod_autodebit_aktiv', $_REQUEST['wpsg_mod_autodebit_aktiv']);
			$this->shop->update_option('wpsg_mod_autodebit_hint', $_REQUEST['wpsg_mod_autodebit_hint']);
			$this->shop->update_option('wpsg_mod_autodebit_gebuehr', $_REQUEST['wpsg_mod_autodebit_gebuehr']);
			$this->shop->update_option('wpsg_mod_autodebit_mwst', $_REQUEST['wpsg_mod_autodebit_mwst']);
			$this->shop->update_option('wpsg_mod_autodebit_mwstland', $_REQUEST['wpsg_mod_autodebit_mwstland']);
			$this->shop->update_option('wpsg_mod_autodebit_iban', $_REQUEST['wpsg_mod_autodebit_iban']);
			
		} // public function settings_save()
		
		public function be_ajax()
		{
		
			if ($_REQUEST['wpsg_mod_autodebit_bicibanconverter'] == '1')
			{
		
				$arOrder_bankeinzug = $this->db->fetchAssoc("
					SELECT
						O.`id` AS `order_id`, O.`custom_data`,
						K.`id` AS `customer_id`,
						L.`kuerzel` AS `land_kuerzel`						
					FROM
						`".WPSG_TBL_ORDER."` AS O
							LEFT JOIN `".WPSG_TBL_KU."` AS K ON (K.`id` = O.`k_id`)
							LEFT JOIN `".WPSG_TBL_LAND."` AS L ON (K.`land` = L.`id`) 
					WHERE
						O.`type_payment` = '20'
				");
				
				foreach ($arOrder_bankeinzug as $order)
				{
										
					$custom_data = @unserialize($order['custom_data']);
					
					$knr = $custom_data['checkout']['mod_autodebit_knr'];
					$blz = $custom_data['checkout']['mod_autodebit_blz'];
					
					if (!wpsg_isSizedString($knr) || !wpsg_isSizedString($blz)) continue;
					
					$iban = $this->make_iban($blz, $knr, $order['land_kuerzel']);
					
					if ($this->test_iban($iban))
					{
						
						$custom_data['checkout']['mod_autodebit_iban'] = $iban;
						
					}
					
					$this->db->UpdateQuery(WPSG_TBL_ORDER, array('custom_data' => serialize($custom_data)), " `id` = '".M1::q($order['order_id'])."' ");
															
					
				}
				die("1");
		
			}
				
		} // public function be_ajax()
		
		public function addPayment(&$arPayment) 
		{ 
			
			if (!is_admin() && $this->shop->get_option('wpsg_mod_autodebit_aktiv') != '1');
			
			$mwst_value = $this->getTaxValue($this->shop->get_option('wpsg_mod_autodebit_mwst'), $this->shop->getDefaultCountry());			
			
			$arPayment[$this->id] = array(
				'id' => $this->id,
				'name' => __($this->shop->get_option('wpsg_mod_autodebit_bezeichnung'), 'wpsg'),
				'preis' => $this->shop->get_option('wpsg_mod_autodebit_gebuehr'),
				'mwst_key' => $this->shop->get_option('wpsg_mod_autodebit_mwst'),
				'mwst_value' => $mwst_value,
				'mwst_null' => $this->shop->get_option('wpsg_mod_autodebit_mwstland'),
				'hint' => __($this->shop->get_option('wpsg_mod_autodebit_hint'))
			);
			
			// Ging leider nicht anders, da die ID der onepagecheckoutseite noch nicht abgefragt werden kann
			// Sollte denk ich nicht zu problemen führen wenn die Abfrage immer im hint drin ist, er wird ohnehin nur im checkout verwendet
			if (	
					isset($_REQUEST['wpsg_checkout2']) || 
					(isset($_REQUEST['wpsg_checkout']) && $this->shop->hasMod('wpsg_mod_onepagecheckout')) || 
					true
			)
			{

				$this->shop->view['error'] = $_SESSION['wpsg']['errorFields'];
				$this->shop->view['wpsg_mod_autodebit']['name'] = $_SESSION['wpsg']['checkout']['mod_autodebit_name'];
				$this->shop->view['wpsg_mod_autodebit']['blz'] = $_SESSION['wpsg']['checkout']['mod_autodebit_blz'];
				$this->shop->view['wpsg_mod_autodebit']['bic'] = $_SESSION['wpsg']['checkout']['mod_autodebit_bic'];
				$this->shop->view['wpsg_mod_autodebit']['inhaber'] = $_SESSION['wpsg']['checkout']['mod_autodebit_inhaber'];
				$this->shop->view['wpsg_mod_autodebit']['knr'] = $_SESSION['wpsg']['checkout']['mod_autodebit_knr'];
				$this->shop->view['wpsg_mod_autodebit']['iban'] = $_SESSION['wpsg']['checkout']['mod_autodebit_iban'];
				
				$arPayment[$this->id]['hint'] .= $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_autodebit/paymenthint.phtml', false);
				
				$arBasket = $this->shop->basket->toArray();
				
				if ($this->shop->get_option('wpsg_preisangaben') == WPSG_NETTO || $arBasket['noMwSt'])
				{
						
					$payment_netto = $this->getPreis($this->shop->get_option('wpsg_mod_autodebit_gebuehr'), $arBasket['sum']['preis']);
					$payment_brutto = wpsg_calculatePreis($payment_netto, WPSG_BRUTTO, $mwst_value);
						
				}
				else
				{
												
					$payment_brutto = $this->getPreis($this->shop->get_option('wpsg_mod_autodebit_gebuehr'), $arBasket['sum']['preis']);																								
					$payment_netto = wpsg_calculatePreis($payment_brutto, WPSG_NETTO, $mwst_value);						
						
				}
				
				// Entsprechenden Preis anzeigen
				if ($this->shop->getFrontendTaxview() == WPSG_NETTO)
				{
					
					$arPayment[$this->id]['price'] = $payment_netto;
					
				}
				else 
				{
					
					$arPayment[$this->id]['price'] = $payment_brutto;
					
				}
				
			}
			
		} // public function addPayment(&$arPayment)
		
		public function calcPayment(&$arBasket) 
		{ 
			
			if ($arBasket['checkout']['payment'] == $this->id)
			{
			 
				$payment_price = $this->getPreis($this->shop->get_option('wpsg_mod_autodebit_gebuehr'), $arBasket['sum']['preis']);
				
				if ($this->shop->get_option('wpsg_mod_autodebit_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_autodebit_mwst'));

				}
								
			}
			
		} // public function calcPayment(&$arBasket) 
		
		public function order_done(&$order_id, &$done_view)
		{
		
			// Bestellungen mit 0 geben nix aus
			if ($done_view['basket']['sum']['preis_gesamt_brutto'] <= 0) return;

			if ($this->shop->view['basket']['checkout']['payment'] == $this->id)
			{
					 
				echo $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_autodebit/order_done.phtml', false);
			
			}
			
		} // public function order_done(&$order_id, &$done_view)
		
		public function checkCheckout(&$state, &$error, &$arCheckout) 
		{ 
	 
			if ($arCheckout['payment'] != $this->id) return;
	 
			// Werte in die Session und den Checkout schreiben schreiben
			if (
					(isset($_REQUEST['wpsg_checkout']) && wpsg_isSizedArray($_REQUEST['wpsg_mod_autodebit'])) || 
					(isset($_REQUEST['wpsg_checkout2']) && wpsg_isSizedArray($_REQUEST['wpsg_mod_autodebit']))
			)
			{
		 
				$_SESSION['wpsg']['checkout']['mod_autodebit_name'] = wpsg_xss($_REQUEST['wpsg_mod_autodebit']['name']);
				$_SESSION['wpsg']['checkout']['mod_autodebit_blz'] = wpsg_xss($_REQUEST['wpsg_mod_autodebit']['blz']);
				$_SESSION['wpsg']['checkout']['mod_autodebit_bic'] = wpsg_xss($_REQUEST['wpsg_mod_autodebit']['bic']);
				$_SESSION['wpsg']['checkout']['mod_autodebit_inhaber'] = wpsg_xss($_REQUEST['wpsg_mod_autodebit']['inhaber']);
				$_SESSION['wpsg']['checkout']['mod_autodebit_knr'] = wpsg_xss($_REQUEST['wpsg_mod_autodebit']['knr']);
				$_SESSION['wpsg']['checkout']['mod_autodebit_iban'] = wpsg_xss($_REQUEST['wpsg_mod_autodebit']['iban']);
				
				$arCheckout['mod_autodebit_name'] = $_SESSION['wpsg']['checkout']['mod_autodebit_name'];
				$arCheckout['mod_autodebit_blz'] = $_SESSION['wpsg']['checkout']['mod_autodebit_blz'];
				$arCheckout['mod_autodebit_bic'] = $_SESSION['wpsg']['checkout']['mod_autodebit_bic'];
				$arCheckout['mod_autodebit_inhaber'] = $_SESSION['wpsg']['checkout']['mod_autodebit_inhaber'];
				$arCheckout['mod_autodebit_knr'] = $_SESSION['wpsg']['checkout']['mod_autodebit_knr'];
				$arCheckout['mod_autodebit_iban'] = $_SESSION['wpsg']['checkout']['mod_autodebit_iban'];

			}
						 
			if ( 
					($state > 1) ||
					($state >= 1 && $this->shop->hasMod('wpsg_mod_onepagecheckout'))
				)
			{
						
				if (trim($arCheckout['mod_autodebit_name']) == '') { $_SESSION['wpsg']['errorFields'][] = 'mod_autodebit_name'; $this->shop->addFrontendError(__('Bitte den Namen der Bank kontrollieren (Bankeinzug)', 'wpsg')); $error = true; }
				if (trim($arCheckout['mod_autodebit_inhaber']) == '') { $_SESSION['wpsg']['errorFields'][] = 'mod_autodebit_inhaber'; $this->shop->addFrontendError(__('Bitte den Inhaber des Kontos kontrollieren (Bankeinzug)', 'wpsg')); $error = true; }
				
				if ($this->shop->get_option('wpsg_mod_autodebit_iban') == '1')
				{

					if (trim($arCheckout['mod_autodebit_bic']) == '') { $_SESSION['wpsg']['errorFields'][] = 'mod_autodebit_bic'; $this->shop->addFrontendError(__('Bitte die BIC der Bank kontrollieren (Bankeinzug)', 'wpsg')); $error = true; }
					if (trim($arCheckout['mod_autodebit_iban']) == '') { $_SESSION['wpsg']['errorFields'][] = 'mod_autodebit_iban'; $this->shop->addFrontendError(__('Bitet die IBAN Nr überprüfen (Bankeinzug)', 'wpsg')); $error = true; }
					
				}
				else 
				{

					if (trim($arCheckout['mod_autodebit_blz']) == '') { $_SESSION['wpsg']['errorFields'][] = 'mod_autodebit_blz'; $this->shop->addFrontendError(__('Bitte die BLZ der Bank kontrollieren (Bankeinzug)', 'wpsg')); $error = true; }
					if (trim($arCheckout['mod_autodebit_knr']) == '') { $_SESSION['wpsg']['errorFields'][] = 'mod_autodebit_knr'; $this->shop->addFrontendError(__('Bitte die Kontonummer überprüfen (Bankeinzug)', 'wpsg')); $error = true; }
					
				}
 						
			}
			
		} // public function checkCheckout(&$state, &$error, &$arCheckout)
		
		public function basket_save_order(&$data, &$checkout, &$arBasket, $finish_order) 
		{ 
			 
			if ($checkout['payment'] == $this->id)
			{
				
				// Daten in die Bestelltabelle hinzutragen
				$data['mod_autodebit_name'] = $checkout['mod_autodebit_name'];
				$data['mod_autodebit_blz'] = $checkout['mod_autodebit_blz'];
				$data['mod_autodebit_bic'] = $checkout['mod_autodebit_bic'];
				$data['mod_autodebit_inhaber'] = $checkout['mod_autodebit_inhaber'];
				$data['mod_autodebit_knr'] = $checkout['mod_autodebit_knr'];
				$data['mod_autodebit_iban'] = $checkout['mod_autodebit_iban'];
				
			}
			
		} // public function basket_save_order(&$data, &$checkout, &$arBasket, $finish_order)
		
		public function order_view_afterpayment(&$order_id) 
		{ 
			
			$order_data = $this->shop->cache->loadOrder($order_id);
			
			if ($order_data['type_payment'] != $this->id) return;
			
			$this->shop->view['wpsg_mod_autodebit']['name'] = $order_data['mod_autodebit_name'];
			$this->shop->view['wpsg_mod_autodebit']['blz'] = $order_data['mod_autodebit_blz'];
			$this->shop->view['wpsg_mod_autodebit']['bic'] = $order_data['mod_autodebit_bic'];
			$this->shop->view['wpsg_mod_autodebit']['inhaber'] = $order_data['mod_autodebit_inhaber'];
			$this->shop->view['wpsg_mod_autodebit']['knr'] = $order_data['mod_autodebit_knr'];
			$this->shop->view['wpsg_mod_autodebit']['iban'] = $order_data['mod_autodebit_iban'];
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_autodebit/order_view_afterpayment.phtml');
			
		} // public function order_view_afterpayment(&$order_id)
		
		public function mail_payment() 
		{ 
			
			if ($this->shop->view['basket']['checkout']['payment'] != $this->id) return;
			
			$this->shop->view['wpsg_mod_autodebit']['name'] = $this->shop->view['basket']['checkout']['mod_autodebit_name'];
			$this->shop->view['wpsg_mod_autodebit']['blz'] = $this->shop->view['basket']['checkout']['mod_autodebit_blz'];
			$this->shop->view['wpsg_mod_autodebit']['bic'] = $this->shop->view['basket']['checkout']['mod_autodebit_bic'];
			$this->shop->view['wpsg_mod_autodebit']['inhaber'] = $this->shop->view['basket']['checkout']['mod_autodebit_inhaber'];
			$this->shop->view['wpsg_mod_autodebit']['knr'] = $this->shop->view['basket']['checkout']['mod_autodebit_knr'];
			$this->shop->view['wpsg_mod_autodebit']['iban'] = $this->shop->view['basket']['checkout']['mod_autodebit_iban'];
			
			if ($this->shop->htmlMail === true)
			{

				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_autodebit/mail_html.phtml');
				
			}			
			else
			{
			
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_autodebit/mail.phtml');
				
			}
			
		} // public function mail_payment()
				
		public function make_iban($blz, $kontonr, $land_kuerzel) 
		{
			
  			$blz8 = str_pad ( $blz, 8, "0", STR_PAD_RIGHT);
  			$kontonr10 = str_pad ( $kontonr, 10, "0", STR_PAD_LEFT);
  			$bban = $blz8 . $kontonr10;
  			$pruefsumme = $bban."131400";
  			$modulo = (bcmod($pruefsumme,"97"));
  			$pruefziffer =str_pad ( 98 - $modulo, 2, "0",STR_PAD_LEFT);
  			$iban = $land_kuerzel.$pruefziffer.$bban;
  
  			return $iban;

		} // public function make_iban($blz, $kontonr) 
		
		public function test_iban($iban) 
		{
			
			$iban = str_replace(' ', '', $iban);
			$iban1 = substr($iban, 4).strval(ord($iban{0}) - 55).strval(ord($iban{1}) - 55). substr($iban, 2, 2);
		
			for ($i = 0; $i < strlen($iban1); $i++) 
			{
				
				if(ord($iban1{$i}) > 64 && ord($iban1{$i}) < 91) 
				{
					
					$iban1 = substr($iban1, 0, $i).strval(ord($iban1{$i}) - 55).substr($iban1, $i + 1);
					
				}
				
			}
			
			$rest = 0;
			
			for ($pos=0; $pos < strlen($iban1); $pos += 7) 
			{
				
				$part = strval($rest).substr($iban1, $pos, 7);
				$rest = intval($part) % 97;
				
			}
			
			$pz = sprintf("%02d", 98-$rest);
		
			if (substr($iban, 2, 2) == '00')
			{
			
				return substr_replace($iban, $pz, 2, 2);
				
			} 
			else 
			{
			
				return ($rest == 1)?true:false;
				
			}
		
		} // public function test_iban( $iban )
		
	} // class wpsg_mod_autodebit extends wpsg_mod_basic

?>