<?php

include_once((IS_ADMIN_FLAG === true ? DIR_FS_CATALOG_MODULES : DIR_WS_MODULES) . 'payment/platnoscipl/platnoscipl_functions.php');


class platnoscipl extends base {
	
	var $code;

	var $title;

	var $description;
	
	var $enabled;
	
	var $insert_id;
	
	var $payment_currency;
	
	var $order_status;

	function platnoscipl() {
		global $order;

		$this->code = 'platnoscipl';
    	$this->payment_currency = 'PLN';
		if (IS_ADMIN_FLAG === true) {
			$this->title = MODULE_PAYMENT_PLATNOSCIPL_TEXT_TITLE; 
			if (MODULE_PAYMENT_PLATNOSCIPL_POS_ID == '(pos_id)' || MODULE_PAYMENT_PLATNOSCIPL_POS_ID == '') $this->title .= '<span class="alert"> (nie skonfigurowane - brak: Id punktu płatności)</span>';
			elseif (MODULE_PAYMENT_PLATNOSCIPL_POS_AUTH_KEY == '(pos_auth_key)' || MODULE_PAYMENT_PLATNOSCIPL_POS_AUTH_KEY == '') $this->title .= '<span class="alert"> (nie skonfigurowane - brak: Klucz autoryzacji płatności)</span>';
			elseif (MODULE_PAYMENT_PLATNOSCIPL_KEY1 == '(MD5)' || MODULE_PAYMENT_PLATNOSCIPL_KEY1 == '') $this->title .= '<span class="alert"> (nie skonfigurowane - brak: Klucz)</span>';
			elseif (MODULE_PAYMENT_PLATNOSCIPL_KEY2 == '(MD5)' || MODULE_PAYMENT_PLATNOSCIPL_KEY2 == '') $this->title .= '<span class="alert"> (nie skonfigurowane - brak: Drugi klucz)</span>';
			if (defined('MODULE_PAYMENT_PLATNOSCIPL_DEBUG') && MODULE_PAYMENT_PLATNOSCIPL_DEBUG != 'Nie') $this->title .= '<span class="alert"> (włączone logowanie)</span>';
			if (MODULE_PAYMENT_PLATNOSCIPL_DIAG == 'On') $this->title .= '<span class="alert"> (tryb diagnostyczny)</span>';
		} 
		else {
			$this->title = MODULE_PAYMENT_PLATNOSCIPL_TEXT_TITLE;
		}
		$this->description = MODULE_PAYMENT_PLATNOSCIPL_TEXT_DESCRIPTION.
							'<center><b>Szczegółowy opis konfiguracji modułu<br />'.
							'znajdziesz w instrukcji instalacji sklepu<br />' .
							'Przeczytaj koniecznie</b></center>';
		$this->sort_order = MODULE_PAYMENT_PLATNOSCIPL_SORT_ORDER;
		$this->enabled = ((MODULE_PAYMENT_PLATNOSCIPL_STATUS == 'True') ? true : false);
		$this->list_enabled = ((MODULE_PAYMENT_PLATNOSCIPL_LIST_STATUS == 'Lista') ? true : false);
		$this->list_on = ((MODULE_PAYMENT_PLATNOSCIPL_LIST_ON == 'Tak') ? true : false);
		if ((int)MODULE_PAYMENT_PLATNOSCIPL_PREPARE_ORDER_STATUS_ID > 0) {
			$this->order_status = MODULE_PAYMENT_PLATNOSCIPL_PREPARE_ORDER_STATUS_ID;
		}
		 
		$this -> form_action_url = 'https://www.platnosci.pl/paygw/UTF/NewPayment';

		$this->active_flag = "aktywny";
		$this->inactive_flag = "nieaktywny";

		if($this->list_on) {
			$pay_types_url = "https://www.platnosci.pl/paygw/UTF/xml/";
			$pay_types_url .= MODULE_PAYMENT_PLATNOSCIPL_POS_ID;
			$pay_types_url .= "/";
			$pay_types_url .= substr(MODULE_PAYMENT_PLATNOSCIPL_KEY1,0,2);
			$pay_types_url .= "/paytype.xml";

			$ch = curl_init();  		
			curl_setopt($ch, CURLOPT_URL, $pay_types_url);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_TIMEOUT, 20);				
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$pay_types_response = curl_exec($ch);
			curl_close($ch);
	
			$parser = xml_parser_create();
			xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
			xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
			xml_parse_into_struct($parser, $pay_types_response, $values, $tags);
			xml_parser_free($parser);
	
			foreach ($tags as $key=>$val) {
				if ($key == "paytype") {
					$paytypes = $val;
					for ($i=0; $i < count($paytypes); $i+=2) {
						$offset = $paytypes[$i] + 1;
						$len = $paytypes[$i + 1] - $offset;
						$payvalues = array_slice($values, $offset, $len);
						for ($j=0; $j < count($payvalues); $j++) {
							$pay_item[$payvalues[$j]["tag"]] = $this -> utf82iso88592($payvalues[$j]["value"]);
						}
						$this->payment_types[] = array(
													'pay_type' => $pay_item['type'],
													'enabled' => $pay_item['enable'],
													'img_url'	=> $pay_item['img'],
													'title'	=> $pay_item['name'],
													'description'	=> $pay_item['name']
												);
					}
				}
				else {
	        	    continue;
				}
			}
		}
  						
		$this->platnoscipl_status = array(
										
										'99' => array('desc'=>'zakończona', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_99'),
										'1' => array('desc'=>'nowa', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_1'),
										'2' => array('desc'=>'anulowana', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_2'),
										'3' => array('desc'=>'odrzucona', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_3'),
										'4' => array('desc'=>'rozpoczęta', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_4'),
										'5' => array('desc'=>'oczekuje na odbiór', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_5'),
										'6' => array('desc'=>'odmowa autoryzacji', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_6'),
										'7' => array('desc'=>'zwrot środków', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_7'),
										'888' => array('desc'=>'błędny status', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_STATUS_888'),
										'KWOTA' => array('desc'=>'zła kwota', 'conf_key'=>'MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_KWOTA')
									);
						
			$this->error_message = array(
										"100" => "brak parametru pos id",
										"101" => "brak parametru session id",
										"102" => "brak parametru ts",
										"103" => "brak parametru sig",
										"104" => "brak parametru desc",
										"105" => "brak parametru client ip",
										"106" => "brak parametru first name",
										"107" => "brak parametru last name",
										"108" => "brak parametru street",
										"109" => "brak parametru city",
										"110" => "brak parametru post code",
										"111" => "brak parametru amount",
										"112" => "błędny numer konta bankowego",
										"200" => "inny chwilowy błąd",
										"201" => "inny chwilowy błąd bazy danych",
										"202" => "POS o podanym identyfikatorze jest zablokowany",
										"203" => "niedozwolona wartość pay_type dla danego pos_id",
										"204" => "podana metoda płatności (wartość pay_type) jest chwilowo zablokowana dla danego pos_id, np. przerwa konserwacyjna bramki płatniczej",
										"205" => "kwota transakcji mniejsza od wartości minimalnej",
										"206" => "kwota transakcji większa od wartości maksymalnej",
										"207" => "przekroczona wartość wszystkich transakcji dla jednego klienta w ostatnim przedziale czasowym",
										"208" => "POS działa w wariancie ExpressPayment lecz nie nastapiła aktywacja tego wariantu współpracy (czekamy na zgode działu obsługi klienta)",
										"209" => "błedny numer pos_id lub pos_auth_key",
										"500" => "transakcja nie istnieje",
										"501" => "brak autoryzacji dla danej transakcji",
										"502" => "transakcja rozpoczęta wcześniej",
										"503" => "autoryzacja do transakcji była juz przeprowadzana",
										"504" => "transakcja anulowana wczesniej",
										"505" => "transakcja przekazana do odbioru wcześniej",
										"506" => "transakcja już odebrana",
										"507" => "błąd podczas zwrotu środków do klienta",
										"599" => "błędny stan transakcji, np. nie można uznać transakcji kilka razy lub inny, prosimy o kontakt",
										"999" => "inny błąd krytyczny - prosimy o kontakt	"
									);
		if (is_object($order)) 
			$this->update_status();
	} 

	function update_status() {
		global $order;
		global $db;

		if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_PLATNOSCIPL_ZONE > 0) ) {
			$check_flag = false;
			$check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_PLATNOSCIPL_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
			while (!$check->EOF) {
				if ($check->fields['zone_id'] < 1) {
					$check_flag = true;
					break;
				}
				elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
					$check_flag = true;
					break;
				}
				$check->MoveNext();
			}

			if ($check_flag == false) {
				$this->enabled = false;
			}
		}
	}

	function javascript_validation() {
		
		$js = '//platnoscipl' . "\n";
		if (MODULE_PAYMENT_PLATNOSCIPL_LIST_ON == 'Tak') {
			$js = '  if (payment_value == "' . $this->code . '") {' . "\n" .
				  '    var pay_type = document.checkout_payment.pay_type.value;' . "\n" .
				  '    if ((pay_type == undefined) || (pay_type == "") ) {' . "\n" .
				  '      error_message = error_message + "' . TEXT_PLATNOSCIPL_VAL_ERROR_PAY_TYPE_NOT_SELECTED . '";' . "\n" .
				  '      error = 1;' . "\n" .
				  '    }' . "\n" .
				  '  }' . "\n";
		}
			
		return $js;
	} 

	function selection() {

		if(($_GET['payment_error'] == 'platnoscipl') && ($_GET['session_id'] == session_id()))
			session_regenerate_id();
 
		if($this->list_on) {
			$ALLOWED_PAY_TYPE_ARRAY =	array();
			$ALLOWED_PAY_TYPE_ARRAY_IMG =	array();
			foreach ($this->payment_types as $key=>$value) {
				if ($value['enabled']=="true") {
					$ALLOWED_PAY_TYPE_ARRAY[] = array('id' => $value['pay_type'], 'text' => $value['title']);
					$ALLOWED_PAY_TYPE_ARRAY_IMG[$value['pay_type']] = $value['img_url'];
				}
			}
	
			$fields = array();
	
			if ($this->list_enabled) {
				$default='';
				if ($_SESSION['platnoscipl_pay_type']) 
					$default = $_SESSION['platnoscipl_pay_type'];
				$ALLOWED_PAY_TYPE_ARRAY[] = array('id' => '', 'text' => "-- wybierz typ --");
				$fields[] = array(
									'title' => MODULE_PAYMENT_PLATNOSCIPL_TEXT_PAYMENT_TYPE,
									'field' => zen_draw_pull_down_menu('pay_type', $ALLOWED_PAY_TYPE_ARRAY, $default)
								);
			}
			else {
				$script = "<script language='JavaScript' type='text/JavaScript'>\n".
						"function radio_button_sel(i) {\n".
						"if (document.getElementById && !document.all && document.getElementById(i)){\n".
						"document.getElementById(i).checked=true;\n".
						"}\n".
						"if (document.all && document.all[i]){\n".
						"document.all[i].checked=true;\n".
						"}}\n</script> \n";
				echo $script;        
	
				foreach ($ALLOWED_PAY_TYPE_ARRAY as $key => $payment) {
					if ($_SESSION['platnoscipl_pay_type']) {   
						if ($payment['id'] == $_SESSION['platnoscipl_pay_type']) {
							$checked=true;    
						}
						else {
							$checked=false;    
						}
					}
					else 
						$checked=false;
					$img_file = $ALLOWED_PAY_TYPE_ARRAY_IMG[$payment['id']];
					$display_image = '<img src="'.$img_file.'" alt="'.$payment['text'].'" title="'.$payment['text'].'" onclick="javascript:radio_button_sel(\''.$payment['id'].'\')">';          
					$fields[] = array(
										'title' => $display_image,
										'field' => zen_draw_radio_field('pay_type', $value = $payment['id'], $checked, 'id="'.$payment['id'].'"') 
									);
				}
			}
		}

		if (MODULE_PAYMENT_PLATNOSCIPL_PAYBACK == 'Tak')
			$fields[] = array(
							'title' => MODULE_PAYMENT_PLATNOSCIPL_TEXT_PAYBACK_LOGIN,
							'field' => zen_draw_input_field('payback_login', $this->payback_login)
						);

		$image_link = '<div id="platnosciplLink"><a href="http://www.platnosci.pl" target="_blank"><img src="/images/platnoscipl/akceptujemy_platnosci_4.gif" border="0"></a></div>';
		$title = '<div id="platnosciplTitle">'.$this->title.'</div>';
		return array(
						'id' => $this->code,
						'module' => '<div id="platnoscipl"><div id="platnosciplRow">'.$title.$image_link.'</div></div>',
						'fields' => $fields
					);
	} 

 
	function pre_confirmation_check() {

		include(DIR_WS_CLASSES . 'platnoscipl_validation.php');

		$platnoscipl_validation = new platnoscipl_validation();
		$result = $platnoscipl_validation->validate($_POST['payback_login']);

		$error = '';
		switch ($result) {
			case -1:
					$error = sprintf(TEXT_PLATNOSCIPL_VAL_ERROR_PAYBACKLOGIN_WRONG_FORMAT, $platnoscipl_validation->payback_login);
				break;
		}

		$this->payback_login = $platnoscipl_validation->payback_login;
		if ( ($result == false) || ($result < 1) ) {
			$payment_error_return = 'payback_login=' . urlencode($this->payback_login) . '&payment_error=' . $this->code . '&error=' . urlencode($error) . '&pay_type=' . urlencode($_POST['pay_type']);
			zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true));
		}

		if ( (strlen(urlencode($_POST['pay_type'])) < 1) && $this->list_on ) {
			$error = sprintf(TEXT_PLATNOSCIPL_VAL_ERROR_PAY_TYPE_NOT_SELECTED);
			$payment_error_return = 'payback_login=' . urlencode($this->payback_login) . '&payment_error=' . $this->code . '&error=' . urlencode($error) . '&pay_type=' . urlencode($_POST['pay_type']);
			zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true));
		}
		else {
			$_SESSION['platnoscipl_pay_type'] = urlencode($_POST['pay_type']);
		}
	} 

	function confirmation() {
		global $languages_id, $order, $order_total_modules, $currencies;
		global $db;

	    $last_order_id = $db->Execute("select * from " . TABLE_ORDERS . " order by orders_id desc limit 1");
	    $new_order_id = $last_order_id->fields['orders_id'];
	    $new_order_id = ($new_order_id + 1);
	    $_SESSION['new_order_id'] = $new_order_id;
	    $new_order_id = (string)$new_order_id . '-' . zen_create_random_value(6);
	    $_SESSION['platnoscipl_ref_id'] = $new_order_id;
		
		$fields[] = array(
							'title' => MODULE_PAYMENT_PLATNOSCIPL_TEXT_REF_ID,
							'field' => $new_order_id
						);

		if($this->payment_currency != $order->info['currency']) {
			
			$fields[] = array (
							'title' => sprintf(MODULE_PAYMENT_PLATNOSCIPL_TEXT_CURRENCY, $this->payment_currency),
							'field' => ''
						);
			$fields[] = array (
							'title' => sprintf(MODULE_PAYMENT_PLATNOSCIPL_TEXT_TO_PAY, $currencies->format($order->info['total'], true, $this->payment_currency), $this->payment_currency),
							'field' => ''
						);
		}
		
		if (MODULE_PAYMENT_PLATNOSCIPL_PAYBACK == 'Tak')
			$fields[] = array(
								'title' => MODULE_PAYMENT_PLATNOSCIPL_TEXT_PAYBACK_LOGIN,
								'field' => $_POST['payback_login']?$_POST['payback_login']:'nie podano'
							);
		
         return array('id' => $this->code,
				'module' => $this->title,
				'fields' => $fields
		);

	} 

	function process_button() {
		global $db, $order, $currencies, $currency;
		global $customer_id;

		platnoscipl_store_session(session_id());

		switch($_SESSION['language']) {
			case "english"	: $mylang = "EN"; break;
			case "polish"	: 
			default : $mylang = "PL";
		}

		$payment_total = $order->info['total'] * $currencies->get_value($this->payment_currency);
		
		$parameters = array();

		$parameters['pos_id'] = MODULE_PAYMENT_PLATNOSCIPL_POS_ID;
		$parameters['pos_auth_key'] = MODULE_PAYMENT_PLATNOSCIPL_POS_AUTH_KEY;
		
		if($this->list_on)
			$parameters['pay_type'] = urlencode($_POST['pay_type']); //opcjonalne
		$parameters['session_id'] = session_id();
		
		$parameters['amount'] = number_format($payment_total, 2, ".", "")*100;
		$parameters['desc'] = 'Zam: '.$_SESSION['new_order_id'].'. ' . $order->billing['firstname'] . ' ' . $order->billing['lastname'];
		$parameters['order_id'] = $_SESSION['platnoscipl_ref_id'];
		$parameters['desc2'] = $order->billing['street_address'].'; '.(empty($order->billing['suburb']) ? '' : $order->billing['suburb'].'; ' ).
								$order->billing['city'].'; '.$order->billing['country']['iso_code_2'];	
		$parameters['first_name'] = $order->billing['firstname'];
		$parameters['last_name'] = $order->billing['lastname'];
		$parameters['street'] = $order->billing['street_address']; 
		$parameters['street_hn'] = $order->billing['suburb']; 
		$parameters['city'] = $order->billing['city'];
		$parameters['post_code'] = $order->billing['postcode'];
		$parameters['country'] = $order->billing['country']['iso_code_2'];
		$parameters['email'] = $order->customer['email_address'];
		$parameters['phone'] = $order->customer['telephone'];
		$parameters['language'] = $mylang;
		$parameters['client_ip'] = $_SERVER["REMOTE_ADDR"];
		$parameters['js'] = 0;
		$parameters['payback_login'] = urlencode($_POST['payback_login']);
		if(MODULE_PAYMENT_PLATNOSCIPL_SIG == 'Tak') {
			$parameters['ts'] = time();
			$signed_str = zen_output_string($parameters['pos_id']).zen_output_string($parameters['pay_type']).
							zen_output_string($parameters['session_id']).zen_output_string($parameters['pos_auth_key']).
							zen_output_string($parameters['amount']).zen_output_string($parameters['desc']).
							zen_output_string($parameters['desc2']).zen_output_string($parameters['trsDsc']).
							zen_output_string($parameters['order_id']).zen_output_string($parameters['first_name']).
							zen_output_string($parameters['last_name']).zen_output_string($parameters['payback_login']).
							zen_output_string($parameters['street']).zen_output_string($parameters['street_hn']).
							zen_output_string($parameters['srteet_an']).zen_output_string($parameters['city']).
							zen_output_string($parameters['post_code']).zen_output_string($parameters['country']).
							zen_output_string($parameters['email']).zen_output_string($parameters['phone']).
							zen_output_string($parameters['language']).zen_output_string($parameters['client_ip']).
							zen_output_string($parameters['ts']).MODULE_PAYMENT_PLATNOSCIPL_KEY1;
			$parameters['sig'] = md5($signed_str);
		}

		$process_button_string='';    
		while (list($key, $value) = each($parameters)) {
			$process_button_string .= zen_draw_hidden_field($key, $value);
		}
        
		return $process_button_string;
	} 

	function before_process() {
    global $order_total_modules;

		if (isset($_GET['referer']) && $_GET['referer'] == 'platnoscipl') {
			$this->notify('NOTIFY_PAYMENT_PLATNOSCIPL_RETURN_TO_STORE');
			
			if(($orders_id = platnoscipl_get_orders_id($_GET['ref_id'])) !== false) {
				
		        $_SESSION['cart']->reset(true);
		        unset($_SESSION['sendto']);
		        unset($_SESSION['billto']);
		        unset($_SESSION['shipping']);
		        unset($_SESSION['payment']);
		        unset($_SESSION['comments']);
		        unset($_SESSION['cot_gv']);
		        $order_total_modules->clear_posts();
				zen_session_recreate();
				
		        zen_redirect(zen_href_link(FILENAME_CHECKOUT_SUCCESS, '', 'SSL', true));
			}
		}
	} 

	
	function after_order_create($insert_id) {
		$this->insert_id = $insert_id;
	} 

	
	function after_process() {
		global $db;
		
		$platnoscipl_info  =      '     Kwota płatności : '.zen_db_input($_GET['amount']);
		$platnoscipl_info .= "\n".'  Numer referencyjny : '.zen_db_input($_GET['ref_id']);
		$platnoscipl_info .= "\n".'     Id platnosci.pl : '.zen_db_input($_GET['trans_id']);
		$platnoscipl_info .= "\n".'     Kanał płatności : '.zen_db_input($_GET['pay_type']);
				
		$const_name = 'MODULE_PAYMENT_PLATNOSCIPL_PREPARE_ORDER_STATUS_ID';
		$order_status_id = defined($const_name)?constant($const_name):DEFAULT_ORDERS_STATUS_ID;

		platnoscipl_store_orders_status_history($this->insert_id, MODULE_PAYMENT_PLATNOSCIPL_PREPARE_ORDER_STATUS_ID, 0, $platnoscipl_info);

		platnoscipl_store_transaction($this->insert_id, $_GET['session_id'], $_GET['pay_type'], $_GET['ref_id'],$_GET['trans_id'], $_GET['pos_id'], $_GET['amount']);

		zen_session_recreate();
	} 

	function get_error() {
		if (isset($_GET['ErrMsg']) && zen_not_null($_GET['ErrMsg'])) {
			$error = stripslashes(urldecode($_GET['ErrMsg']));
		}
		elseif (isset($_GET['Err']) && zen_not_null($_GET['Err'])) {
			$error = stripslashes(urldecode($_GET['Err']));
		}
		elseif (isset($_GET['error']) && zen_not_null($_GET['error'])) {
			$error = stripslashes(urldecode($_GET['error']));
		}
		else {
			$error = MODULE_PAYMENT_PLATNOSCIPL_TEXT_ERROR_MESSAGE;
		}
		$errormsg = isset($this->error_message[$error])?$this->error_message[$error]:$error;
		return array(
					'title' => MODULE_PAYMENT_PLATNOSCIPL_TITLE_ERROR_MESSAGE,
		   			'error' => $errormsg
		   			);
	}

	function check() {
		global $db;
		
		if (!isset($this->_check)) {
			$check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PLATNOSCIPL_STATUS'");
			$this->_check = $check_query->RecordCount();
		}
		return $this->_check;
	}

	function install() {
		global $db, $messageStack;
		
		if(!defined('TABLE_PLATNOSCIPL')) {
		    $messageStack->add_session(sprintf('Niezdefiniowana nazwa tabeli: ', TABLE_PLATNOSCIPL), 'error');
			return 'failed';
		}
		if(!defined('TABLE_PLATNOSCIPL_SESSION')) {
		    $messageStack->add_session(sprintf('Niezdefiniowana nazwa tabeli: ', TABLE_PLATNOSCIPL_SESSION), 'error');
			return 'failed';
		}
		
		$db->Execute("CREATE TABLE IF NOT EXISTS ".TABLE_PLATNOSCIPL." ( " .
						
						"platnoscipl_id int(11) unsigned NOT NULL auto_increment, " .
						"orders_id int(11) unsigned NOT NULL default '0', " . 
						"payback_login varchar(30), " . 
						"session_id text NOT NULL, " . 
						"pay_type varchar(30), " .
						"ref_id varchar(30), " . 
						"trans_id varchar(30) NOT NULL, " . 
						"pos_id varchar(30), " . 
						"amount varchar(30), " . 
						"last_modified datetime NOT NULL default '0001-01-01 00:00:00', " .
						"date_added timestamp NOT NULL default CURRENT_TIMESTAMP, " .
						"PRIMARY KEY  (platnoscipl_id), " .
						"KEY idx_orders_id_zen (orders_id), " .
						"KEY idx_session_id_zen (session_id(36))" .
					") ENGINE=MyISAM DEFAULT CHARSET=utf8"
				);
		$db->Execute("CREATE TABLE IF NOT EXISTS ".TABLE_PLATNOSCIPL_SESSION." ( " .
						"unique_id int(11) NOT NULL auto_increment, " . 
						"session_id text NOT NULL, " . 
						"saved_session mediumblob NOT NULL, " . 
						"expiry int(17) NOT NULL default '0', " . 
						"PRIMARY KEY  (`unique_id`), " .
						"KEY `idx_session_id_zen` (`session_id`(36))" .
					") ENGINE=MyISAM DEFAULT CHARSET=utf8"
				);

		foreach ($this->platnoscipl_status as $key=>$value) {
			$orders_status_name = 'platnosci.pl: ' . $value['desc'];
			$check_query = $db->Execute("select orders_status_id from " . TABLE_ORDERS_STATUS . " where orders_status_name = '" . $orders_status_name . "' limit 1");
			if ($check_query->RecordCount() < 1) {
				$status_query = $db->Execute("select max(orders_status_id) as status_id from " . TABLE_ORDERS_STATUS);
				$status = $status_query->fields;
				$status_id = $status['status_id']+1;
				if ($key == 1) {
					
					$status_new = $status_id;
				}
				if ($key == 99) {
					
					$status_processing = $status_id;
				}
				if ($key == 'KWOTA') {
					
					$status_kwota = $status_id;
				}
				$languages = zen_get_languages();
				foreach ($languages as $lang) {
//					$db->Execute("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . $status_id . "', '" . $lang['id'] . "', '" . $orders_status_name . "')");
            $db->Execute("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . $status_id . "', '" . $lang['id'] . "', '" . $orders_status_name . "') on duplicate key update orders_status_name=values(orders_status_name)");
				}
			}
			else {
				$check = $check_query->fields;
				$status_id = $check['orders_status_id'];
				if ($key == 1) {
					
					$status_new = $status_id;
				}
				if ($key == 99) {
					
					$status_processing = $status_id;
				}
				if ($key == 'KWOTA') {
					
					$status_kwota = $status_id;
				}
			}
			if ($key != 'KWOTA') {
				$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, date_added) values ('Status - " . $orders_status_name . "', '" . $value['conf_key'] . "', '" . $status_id . "', 'Status obsługi płatności zamówienia w systemie platnosci.pl', '6', now())");
			}
		};

		//--- Create configuration keys
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Aktywny moduł platnosci.pl', 'MODULE_PAYMENT_PLATNOSCIPL_STATUS', 'True', 'Czy chcesz uruchomić płatności poprzez platnosci.pl?', '6', '1', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Identyfikator Punktu Płatności w serwisie platnosci.pl (pos_id)', 'MODULE_PAYMENT_PLATNOSCIPL_POS_ID', '(pos_id)', 'Identyfikator twojego Punktu Płatności w serwisie platnosci.pl (dostępny w panelu administracyjnym platnosci.pl)', '6', '2', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Klucz autoryzacji płatności w serwisie platnosci.pl (pos_auth_key)', 'MODULE_PAYMENT_PLATNOSCIPL_POS_AUTH_KEY', '(pos_auth_key)', 'Klucz autoryzacji płatności w serwisie platnosci.pl (dostępny w panelu administracyjnym platnosci.pl)', '6', '3', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Klucz (MD5)', 'MODULE_PAYMENT_PLATNOSCIPL_KEY1', '(MD5)', 'Klucz podpisu Punktu Płatności. Dostępny w Panelu Admistracyjnym Płatności (\"Konfiguracja Punktu Płatności\")', '6', '4', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Drugi klucz (MD5)', 'MODULE_PAYMENT_PLATNOSCIPL_KEY2', '(MD5)', 'Drugi klucz podpisu Punktu Płatności. Dostępny w Panelu Admistracyjnym Płatności (\"Konfiguracja Punktu Płatności\")', '6', '5', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Podpisuj płatności', 'MODULE_PAYMENT_PLATNOSCIPL_SIG', 'Tak', 'Dołączaj podpis do danych wysyłanych do platnosci.pl przy zakładaniu nowej płatności', '6', '5', 'zen_cfg_select_option(array(\'Tak\', \'Nie\'), ', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Aktywny program lojalnościowy PayBACK', 'MODULE_PAYMENT_PLATNOSCIPL_PAYBACK', 'Nie', 'Czy chcesz nagradzać punktami PayBACK (<a href=\"http://www.payback.pl\" target=\"_blank\">www.payback.pl</a>) transakcje dokonywane za pośrednictwem platnosci.pl?', '6', '6', 'zen_cfg_select_option(array(\'Tak\', \'Nie\'), ', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Wstępny status zamówień', 'MODULE_PAYMENT_PLATNOSCIPL_PREPARE_ORDER_STATUS_ID', '" . $status_new . "', 'Wstępny status zamówień przygotowywanych przez tą metodę płatności', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Status zamówień potwierdzonych', 'MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_ID', '" . $status_processing . "', 'Status zamówień opłaconych tą metodą i potwierdzonych przez Płatności', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Mail dla zamówień potwierdzonych', 'MODULE_PAYMENT_PLATNOSCIPL_MAIL_STATUS_ID', 'Tak', 'Czy informować klienta mailem o potwierdzeniu płatności?', '6', '0', 'zen_cfg_select_option(array(\'Tak\', \'Nie\'), ', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Status przy złej kwocie zapłaty', 'MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_KWOTA', '" . $status_kwota . "', 'Status zamówień, których kwota zapłaty zaraportowana przez Płatności jest różna od kwoty zamówienia', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Mail przy złej kwocie zapłaty', 'MODULE_PAYMENT_PLATNOSCIPL_MAIL_STATUS_KWOTA', 'Nie', 'Czy informować klienta mailem o błędnej kwocie płatności?', '6', '0', 'zen_cfg_select_option(array(\'Tak\', \'Nie\'), ', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Strefa', 'MODULE_PAYMENT_PLATNOSCIPL_ZONE', '0', 'Jeżeli strefa zostanie wybrana, to ten sposób płatności będzie dostępny tylko dla klientów z tej strefy.', '6', '4', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('E-Mail dla błędnych transakcji', 'MODULE_PAYMENT_PLATNOSCIPL_DEBUG_EMAIL', '', 'Adres email, na który będą wysyłane parametry błędnych transakcji (możesz pozostawić to pole puste)', '6', '0', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Powiadamianie o zamówieniach', 'MODULE_PAYMENT_PLATNOSCIPL_ORDER_NOTIFICATION', 'Tak', 'Powiadamianie właściciela sklepu o nowych zamówieniach (na adres email Administaratora, podany w konfiguracji sklepu)', '6', '1', 'zen_cfg_select_option(array(\'Tak\', \'Nie\'), ', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Kolejność wyświetlania.', 'MODULE_PAYMENT_PLATNOSCIPL_SORT_ORDER', '0', 'Kolejność metod płatności - pierwsze wyświetlane są te z mniejszą wartością w tym polu.', '6', '0', now())");
		
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Sposób prezentacji listy kanałów płatności w sklepie', 'MODULE_PAYMENT_PLATNOSCIPL_LIST_STATUS', 'Lista', 'Czy chcesz wyświetlać liste kanałów płatności jako liste wybieralną (Lista) czy opcje typu radiobutton (Radio)?', '6', '0', 'zen_cfg_select_option(array(\'Lista\', \'Radio\'), ', now())");
		 
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Czy wybierać kanał płatności w sklepie?', 'MODULE_PAYMENT_PLATNOSCIPL_LIST_ON', 'Nie', 'Wybierz kanał płatności w sklepie (Tak) lub po przejściu na stronę platnosci.pl (Nie)', '6', '0', 'zen_cfg_select_option(array(\'Tak\', \'Nie\'), ', now())");
		
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Zapis operacji', 'MODULE_PAYMENT_PLATNOSCIPL_DEBUG', 'Nie', 'Włączyć zapis operacji? <br />PLik logu znajdziesz w: /includes/modules/payment/platnoscipl/logs<br />Jeżeli wybierzesz \"Plik i Email\" to raporty są wysyłane również na podany wyżej E-Mail blędnych transakcji.<br />UWAGA: To naprawde może Ci zapchać skrzynkę emailową!<br /><strong>Należy używać tylko do celów analizy błędów i uruchomienia modułu!<br />Ustaw na \'Nie\' w trakcie normalnej pracy sklepu.</strong>', '6', '44', 'zen_cfg_select_option(array(\'Nie\',\'Plik\',\'Plik i Email\'), ', now())");
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Tryb diagnostyczny', 'MODULE_PAYMENT_PLATNOSCIPL_DIAG', 'Nie', 'Włączyć tryb diagnostyczny? <br />UWAGA: \"Historia raportów\" w panelu administracyjnym platnosci.pl bedzie zawierać komunikaty diagnostyczne. W związku z tym żaden raport nie zostanie przez serwis płatności uznany za odebrany przez sklep.<br />.<br /><strong>Należy używać tylko do celów analizy błędów i uruchomienia modułu!<br />Ustaw na \'Nie\' w trakcie normalnej pracy sklepu.</strong>', '6', '44', 'zen_cfg_select_option(array(\'Nie\',\'Tak\'), ', now())");

		$this->notify('NOTIFY_PAYMENT_PLATNOSCIPL_INSTALLED');
	} 

	
	function remove() {
		global $db;
	
		$db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");

		foreach ($this->platnoscipl_status as $key=>$value) 
			$db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key = '" . $value['conf_key'] . "'");
		
	    $this->notify('NOTIFY_PAYMENT_PLATNOSCIAL_UNINSTALLED');
	} 

	
	function keys() {
		$keys =  array(
					'MODULE_PAYMENT_PLATNOSCIPL_STATUS',
					'MODULE_PAYMENT_PLATNOSCIPL_POS_ID',
					'MODULE_PAYMENT_PLATNOSCIPL_POS_AUTH_KEY',
					'MODULE_PAYMENT_PLATNOSCIPL_PREPARE_ORDER_STATUS_ID',
					'MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_ID',
					'MODULE_PAYMENT_PLATNOSCIPL_MAIL_STATUS_ID',
					'MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_KWOTA',
					'MODULE_PAYMENT_PLATNOSCIPL_MAIL_STATUS_KWOTA',
					'MODULE_PAYMENT_PLATNOSCIPL_PAYBACK',
					'MODULE_PAYMENT_PLATNOSCIPL_KEY1',
					'MODULE_PAYMENT_PLATNOSCIPL_KEY2',
					'MODULE_PAYMENT_PLATNOSCIPL_SIG',
					'MODULE_PAYMENT_PLATNOSCIPL_ZONE',
					'MODULE_PAYMENT_PLATNOSCIPL_DEBUG_EMAIL',
					'MODULE_PAYMENT_PLATNOSCIPL_ORDER_NOTIFICATION',
					'MODULE_PAYMENT_PLATNOSCIPL_SORT_ORDER',
					'MODULE_PAYMENT_PLATNOSCIPL_LIST_STATUS',
					'MODULE_PAYMENT_PLATNOSCIPL_LIST_ON',
					'MODULE_PAYMENT_PLATNOSCIPL_DEBUG',
					'MODULE_PAYMENT_PLATNOSCIPL_DIAG',
					);
		return $keys;
	} 

}
