<?php


$platnoscipl_error_number = 0;
$platnoscipl_instance_id = time();


function platnoscipl_add_error_log($message) {
  global  $platnoscipl_instance_id;
  $fp = @fopen('includes/modules/payment/platnoscipl/logs/platnoscipl_' . $platnoscipl_instance_id . '.log', 'a');
  @fwrite($fp, date('Y-m-d H:i:s') . ' -- ' . $message . "\n\n");
  @fclose($fp);
} 

function platnoscipl_debug_email($message, $email_address = MODULE_PAYMENT_PLATNOSCIPL_DEBUG_EMAIL, $always_send = false) {
	if (MODULE_PAYMENT_PLATNOSCIPL_DEBUG == 'Plik i Email' || $always_send) {
		global $platnoscipl_error_number, $platnoscipl_instance_id;
		$platnoscipl_error_number ++;
		mail($email_address,'Platnosci.pl DEBUG instance (' . $platnoscipl_instance_id . ') #' . $platnoscipl_error_number, $message);
	}
	if (MODULE_PAYMENT_PLATNOSCIPL_DEBUG == 'Plik i Email' || MODULE_PAYMENT_PLATNOSCIPL_DEBUG == 'Plik') 
		platnoscipl_add_error_log($message);
	if(MODULE_PAYMENT_PLATNOSCIPL_DIAG == 'Tak') {
		$pos = strpos($message,"\n");
		$pos = (($pos<50) ? $pos : 80);
		print substr($message,0, $pos)."\n";
	}
}

function platnoscipl_get_stored_session($session_stuff) {
	global $db;
	
	if (!preg_match('/[a-z0-9]{32}/',$session_stuff)) {
		platnoscipl_debug_email('platnoscipl_get_stored_session:ERROR:: Nieprawidłowy identyfikator w otrzymanych danych, nie mogę odtworzyć sesji.'."\n\nSession stuff=".print_r($session_stuff,true));
		return false;
	}
	$sql = "SELECT * FROM " . TABLE_PLATNOSCIPL_SESSION . " WHERE session_id = :sessionID";
	$sql = $db->bindVars($sql, ':sessionID', $session_stuff, 'string');
	$stored_session = $db->Execute($sql);
	platnoscipl_debug_email('platnoscipl_get_stored_session:INFO::'."\n\n".'Session Query='.$sql."\n\nSession_stuff = ".print_r($session_stuff, true));
	if ($stored_session->recordCount() < 1) {
		platnoscipl_debug_email('platnoscipl_get_stored_session:ERROR:: Nie mogę znaleźć sesji o podanym identyfikatorze w bazie, nie mogę odtworzyć sesji.'."\n\nSession stuff=".print_r($session_stuff,true));
		return false;
	}
	$_SESSION = unserialize(base64_decode($stored_session->fields['saved_session']));
	return true;
} 

function platnoscipl_store_session($session_stuff) {
	global $db;
	
	if (!preg_match('/[a-z0-9]{32}/',$session_stuff)) {
		platnoscipl_debug_email('platnoscipl_store_session:ERROR:: Nieprawidłowy identyfikator w otrzymanych danych, nie mogę odtworzyć sesji.'."\n\nSession stuff=".print_r($session_stuff,true));
		return false;
	}
	
	$db->Execute("delete from " . TABLE_PLATNOSCIPL_SESSION . " where session_id = '" . $session_stuff . "'");
	$sql = "insert into " . TABLE_PLATNOSCIPL_SESSION . " (session_id, saved_session, expiry) values (
	        '" . $session_stuff . "',
	        '" . base64_encode(serialize($_SESSION)) . "',
	        '" . (time() + (1*60*60*24*2)) . "')";
	$db->Execute($sql);
	return true;
} 

function platnoscipl_get_status($data) {
	switch ($data[6]) {
			case 1: return array('code' => $data[6], 'message' => 'nowa'); break;
			case 2: return array('code' => $data[6], 'message' => 'anulowana'); break;
			case 3: return array('code' => $data[6], 'message' => 'odrzucona'); break;
			case 4: return array('code' => $data[6], 'message' => 'rozpoczęta'); break;
			case 5: return array('code' => $data[6], 'message' => 'oczekuje na odbiór'); break;
			case 6: return array('code' => $data[6], 'message' => 'odmowa autoryzacji'); break;
			case 7: return array('code' => $data[6], 'message' => 'płatność odrzucona'); break;
			case 99: return array('code' => $data[6], 'message' => 'zakończona'); break;
			case 888: return array('code' => $data[6], 'message' => 'błędny status'); break;
			default: return array('code' => false, 'message' => 'brak statusu'); break;
	}
} 

function platnoscipl_validate_UrlOnline() {
	if($_POST['pos_id'] != MODULE_PAYMENT_PLATNOSCIPL_POS_ID) {
		platnoscipl_debug_email('platnoscipl_validate_UrlOnline: ERROR:: Błędny identyfikator punktu sprzedaży.'."\n\nPOST=".print_r($_POST,true));
		return false;
	}
	if(md5($_POST['pos_id'].$_POST['session_id'].$_POST['ts'].MODULE_PAYMENT_PLATNOSCIPL_KEY2) == $_POST['sig']) {
		platnoscipl_debug_email('platnoscipl_validate_UrlOnline: SUCCESS:: Otrzymane dane zostały poprawnie zwalidowane.'."\n\nPOST=".print_r($_POST,true));
		return true;
	}
	platnoscipl_debug_email('platnoscipl_validate_UrlOnline: ERROR:: Otrzymane dane nie przeszły walidacji.'."\n\nPOST=".print_r($_POST,true));
	return false;
} 

function platnoscipl_validate_PaymentGet($data) {
	if($_POST['pos_id'] != MODULE_PAYMENT_PLATNOSCIPL_POS_ID) {
		platnoscipl_debug_email('platnoscipl_validate_PaymentGet: ERROR:: Błędny identyfikator punktu sprzedaży.'."\n\ndata=".print_r($data,true));
		return false;
	}
	if(md5($data[2].$data[3].$data[4].$data[6].$data[5].$data[8].$data[9].MODULE_PAYMENT_PLATNOSCIPL_KEY2) == $data[10]) {
		platnoscipl_debug_email('platnoscipl_validate_PaymentGet: SUCCESS:: Otrzymane dane zostały poprawnie zwalidowane.'."\n\ndata=".print_r($data,true));
		return true;
	}
	platnoscipl_debug_email('platnoscipl_validate_PaymentGet: ERROR:: Otrzymane dane nie przeszły walidacji.'."\n\ndata=".print_r($data,true));
	return false;
} 

function platnoscipl_get_transaction($ref_id) {
	global $db;
	$sql = "SELECT * FROM " . TABLE_PLATNOSCIPL . " WHERE ref_id = :refID LIMIT 1";
	$sql = $db->bindVars($sql, ':refID', $ref_id, 'string');
	$stored_transaction = $db->Execute($sql);
	platnoscipl_debug_email('platnoscipl_get_transaction:INFO::'."\n\n".'Query='.$sql);
	if ($stored_transaction->recordCount() < 1) {
		platnoscipl_debug_email('platnoscipl_get_transaction:ERROR:: Nie mogę znaleźć transakcji o podanym ref_id w bazie.');
		return false;
	}
	$platnoscipl_transaction = $stored_transaction->fields;
	platnoscipl_debug_email('platnoscipl_get_transaction:SUCCESS:: Znaleziono transakcję o podanym ref_id.'."\n\n".'platnoscipl_transaction='.$platnoscipl_transaction);
	return $platnoscipl_transaction;
} 

function platnoscipl_get_orders_id($ref_id) {
	global $db;

	$sql = "SELECT * FROM " . TABLE_PLATNOSCIPL . " WHERE ref_id = :refID  LIMIT 1";
	$sql = $db->bindVars($sql, ':refID', $ref_id, 'string');
	$stored_transaction = $db->Execute($sql);
	platnoscipl_debug_email('platnoscipl_get_orders_id:INFO::'."\n\n".'Query='.$sql);
	if ($stored_transaction->recordCount() < 1) {
		platnoscipl_debug_email('platnoscipl_get_orders_id:ERROR:: Nie mogę znaleźć transakcji o podanym ref_id w bazie.');
		return false;
	}
	$orders_id = $stored_transaction->fields['orders_id'];
	if(empty($orders_id)) {
			platnoscipl_debug_email('platnoscipl_get_orders_id:ERROR:: Znaleziono transakcję o podanym ref_id, ale orders_id nie jest ustawiony.');
		return false;
	}
	platnoscipl_debug_email('platnoscipl_get_orders_id:SUCCESS:: Znaleziono transakcję o podanym ref_id.'."\n\n".'orders_id='.$orders_id);
	return $orders_id;
} 

function platnoscipl_store_orders_id($ref_id, $orders_id) {
	global $db;
	
	$sql = "UPDATE " . TABLE_PLATNOSCIPL . " SET orders_id = :ordID WHERE ref_id = :refID";
	$sql = $db->bindVars($sql, ':refID', $ref_id, 'string');
	$sql = $db->bindVars($sql, ':ordID', $orders_id, 'string');
	$db->Execute($sql);
	return true;
} 

function platnoscipl_read_stored_session($session_stuff) {
	global $db;
	
	if (!preg_match('/[a-z0-9]{32}/',$session_stuff)) {
		platnoscipl_debug_email('platnoscipl_read_stored_session:ERROR:: Nieprawidłowy identyfikator w otrzymanych danych, nie mogę odtworzyć sesji.'."\n\nSession stuff=".print_r($session_stuff,true));
		return false;
	}
	$sql = "SELECT * FROM " . TABLE_PLATNOSCIPL_SESSION . " WHERE session_id = :sessionID";
	$sql = $db->bindVars($sql, ':sessionID', $session_stuff, 'string');
	$stored_session = $db->Execute($sql);
	platnoscipl_debug_email('platnoscipl_read_stored_session:INFO::'."\n\n".'Session Query='.$sql."\n\nSession_stuff = ".print_r($session_stuff, true));
	if ($stored_session->recordCount() < 1) {
		platnoscipl_debug_email('platnoscipl_read_stored_session:ERROR:: Nie mogę znaleźć sesji o podanym identyfikatorze w bazie, nie mogę odtworzyć sesji.'."\n\nSession stuff=".print_r($session_stuff,true));
		return false;
	}
	return unserialize(base64_decode($stored_session->fields['saved_session']));;
} 

function platnoscipl_find_stored_session($session_stuff) {
	global $db;
	
	if (!preg_match('/[a-z0-9]{32}/',$session_stuff)) {
		platnoscipl_debug_email('platnoscipl_find_stored_session:ERROR:: Nieprawidłowy identyfikator w otrzymanych danych, nie mogę odtworzyć sesji.'."\n\nSession stuff=".print_r($session_stuff,true));
		return false;
	}
	$sql = "SELECT session_id FROM " . TABLE_PLATNOSCIPL_SESSION . " WHERE session_id = :sessionID";
	$sql = $db->bindVars($sql, ':sessionID', $session_stuff, 'string');
	$stored_session = $db->Execute($sql);
	platnoscipl_debug_email('platnoscipl_find_stored_session:INFO::'."\n\n".'Session Query='.$sql."\n\nSession_stuff = ".print_r($session_stuff, true));
	if ($stored_session->recordCount() < 1) {
		platnoscipl_debug_email('platnoscipl_find_stored_session:ERROR:: Nie mogę znaleźć sesji o podanym identyfikatorze w bazie, nie mogę odtworzyć sesji.'."\n\nSession stuff=".print_r($session_stuff,true));
		return false;
	}
	return true;
} 

function platnoscipl_get_orders_status_name($orders_status_id, $language_id = '') {
	global $db;
	
	if (!$language_id) $language_id = $_SESSION['languages_id'];
	$orders_status = $db->Execute("select orders_status_name
	                               from " . TABLE_ORDERS_STATUS . "
	                               where orders_status_id = '" . (int)$orders_status_id . "'
	                               and language_id = '" . (int)$language_id . "'");
	
	return $orders_status->fields['orders_status_name'];
} 

function platnoscipl_store_orders_status_history($orders_id, $orders_status_id, $customer_notified, $comments) {
	global $db;
	
	$check_status = $db->Execute("select customers_name, customers_email_address, orders_status,
	                              date_purchased from " . TABLE_ORDERS . "
	                              where orders_id = '" . (int)$orders_id . "'");
	
	if ( ($check_status->fields['orders_status'] != $orders_status_id)) {
		$db->Execute("update " . TABLE_ORDERS . " set orders_status = '" . $orders_status_id . "', last_modified = now() where orders_id = '" . (int)$orders_id . "'");
	
		$sql_data_array= array(
								array(
										'fieldName'=>'orders_id',
										'value'=>$orders_id, 
										'type'=>'integer'
									),
								array(
										'fieldName'=>'orders_status_id',
										'value'=>$orders_status_id,
										'type'=>'integer'
									),
								array(
										'fieldName'=>'date_added',
										'value'=>'now()',
										'type'=>'noquotestring'
									),
								array(
										'fieldName'=>'customer_notified',
										'value'=>$customer_notified,
										'type'=>'integer'
									),
								array(
										'fieldName'=>'comments',
										'value'=>$comments,
										'type'=>'string'
									)
							);
		$db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
	}
} 

function platnoscipl_store_transaction($orders_id, $session_id, $pay_type, $ref_id, $trans_id, $pos_id, $amount) {
	global $db;
	
	$sql_data_array = array (
							array(
								'fieldName' => 'orders_id',
								'value' => $orders_id,
								'type' => 'integer',
							),
							array(
								'fieldName' => 'session_id',
								'value' => zen_db_input($session_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'pay_type',
								'value' => zen_db_input($pay_type),
								'type' => 'string',
							),
							array(
								'fieldName' => 'ref_id',
								'value' => zen_db_input($ref_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'trans_id',
								'value' => zen_db_input($trans_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'pos_id',
								'value' => zen_db_input($pos_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'amount',
								'value' => zen_db_input(str_replace(',','.',$amount)),
								'type' => 'string',
							),
							array(
								'fieldName' => 'last_modified',
								'value'=>'now()',
								'type'=>'noquotestring'
							)
						);
	$db->perform(TABLE_PLATNOSCIPL, $sql_data_array);
}

