<?php

$loaderPrefix = 'platnoscipl';
require('includes/application_top.php');


if(!$platnosciplFoundSession) {
	die ('platnoscipl_handler: FATAL ERROR:: Nie odtworzono sesji.');
}


if (!platnoscipl_validate_UrlOnline()) {
	die ('platnoscipl_handler: FATAL ERROR:: Nieprawidłowe parametry wywołania UrlOnline.');
}

if(MODULE_PAYMENT_PLATNOSCIPL_DIAG == 'Tak') {
	error_reporting(E_ALL);
	@ini_set('display_errors', 1);
}
else {
	error_reporting(0);
	@ini_set('display_errors', 0);
}


$payment_currency = 'PLN';


$server = 'www.platnosci.pl';
$server_script = '/paygw/UTF/Payment/get';


$ts = time();
$sig = md5( MODULE_PAYMENT_PLATNOSCIPL_POS_ID . $_POST['session_id'] . $ts . MODULE_PAYMENT_PLATNOSCIPL_KEY1);
$parameters = "pos_id=" . MODULE_PAYMENT_PLATNOSCIPL_POS_ID . "&session_id=" . $_POST['session_id'] . "&ts=" . $ts . "&sig=" . $sig;


$fsocket = false;
$curl = false;

if (function_exists('curl_exec')) {
	$curl = true;
} elseif ( (PHP_VERSION >= 4.3) && ($fp = @fsockopen('ssl://' . $server, 443, $errno, $errstr, 30)) ) {
	$fsocket = true;
} elseif ($fp = @fsockopen($server, 80, $errno, $errstr, 30)) {
	$fsocket = true;
}
else {
	die ('platnoscipl_handler: FATAL ERROR:: Brak możliwości wywołania zwrotnego.');
}

$result = false;
if ($curl) {
	
	$ch = curl_init();  		
	curl_setopt($ch, CURLOPT_URL, 'https://' . $server . $server_script);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, 20);				
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$platnosci_response = curl_exec($ch);
	curl_close($ch);
} elseif ($fsocket) {
	$header = 'POST ' . $server_script . ' HTTP/1.0' . "\r\n" .
			  'Host: ' . $server . "\r\n" .
			  'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
			  'Content-Length: ' . strlen($parameters) . "\r\n" .
			  'Connection: close' . "\r\n\r\n";
	@fputs($fp, $header . $parameters);
	$platnosci_response = '';
	while (!@feof($fp)) {
		$res = @fgets($fp, 1024);
		$platnosci_response .= $res;
	}
	@fclose($fp);
}


if (eregi("<trans>.*<id>([0-9]+)</id>.*<pos_id>([0-9]+)</pos_id>.*<session_id>([a-z0-9-]+)</session_id>.*<order_id>([a-z0-9-]+)</order_id>.*<amount>([0-9]+)</amount>.*<status>([0-9]+)</status>.*<pay_type>(.*)</pay_type>.*<desc>(.*)</desc>.*<ts>([0-9]*)</ts>.*<sig>([a-z0-9]*)</sig>.*</trans>", $platnosci_response, $parts)) {
	
	
	if (!platnoscipl_validate_PaymentGet($parts)) {
		die ('platnoscipl_handler: FATAL ERROR:: Nieprawidłowe parametry otrzymane w odpowiedzi na Payment/get.');
	}

	$result = platnoscipl_get_status($parts);

	if ($result['code'] == 99 || ($result['code'] >0 && $result['code'] <=7 )) {
		
		platnoscipl_debug_email('platnoscipl_handler:SUCCESS:: Rozpoznany status transakcji : '.$result['code']."\n\nResponse".print_r($platnosci_response,true));
		
		$orders_id = platnoscipl_get_orders_id($parts[4]);
		if(!$orders_id) {
			if (platnoscipl_find_stored_session($parts[3]) === false) {
				
				platnoscipl_debug_email('platnoscipl_handler:ERROR:: Brak zapisanej sesji dla podanego przez platnosci.pl session_id: '.$parts[3].'. Podane ref_id: '.$parts[4]."\n\nResponse".print_r($platnosci_response,true));
				die ('platnoscipl_handler: FATAL ERROR:: Brak zapisanej sesji dla podanego przez platnosci.pl session_id.');
			}
			else {

					platnoscipl_debug_email('platnoscipl_handler:INFO:: Płatnośc uznana za nową - rozpoczynam checkout process.');

					require(DIR_WS_CLASSES . 'payment.php');
					$payment_modules = new payment($_SESSION['payment']);
					platnoscipl_debug_email('platnoscipl_handler:INFO:: Załadowane payment_modules.');

					
					require(DIR_WS_CLASSES . 'shipping.php');
					$shipping_modules = new shipping($_SESSION['shipping']);
					platnoscipl_debug_email('platnoscipl_handler:INFO:: Załadowane shipping_modules.');
					
					require(DIR_WS_CLASSES . 'order.php');
					$order = new order;
					platnoscipl_debug_email('platnoscipl_handler:INFO:: New order.');
					
					require(DIR_WS_CLASSES . 'order_total.php');
					$order_total_modules = new order_total;
					platnoscipl_debug_email('platnoscipl_handler:INFO:: Załadowane order_total_modules.');
					
					$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_BEFORE_ORDER_TOTALS_PROCESS');
					platnoscipl_debug_email('platnoscipl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_BEFORE_ORDER_TOTALS_PROCESS.');

					$order_totals = $order_total_modules->process();
					$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_TOTALS_PROCESS');
					platnoscipl_debug_email('platnoscipl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_TOTALS_PROCESS.');
					
					
					$insert_id = $order->create($order_totals, 2);
					$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_CREATE');
					platnoscipl_debug_email('platnoscipl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_CREATE.');

						
						$platnoscipl_info  =      '     Kwota płatności : '.$currencies->format($parts[5]/100,false,$payment_currency);
						$platnoscipl_info .= "\n".'  Numer referencyjny : '.$parts[4];
						$platnoscipl_info .= "\n".'     Id platnosci.pl : '.$parts[1];
						$platnoscipl_info .= "\n".'Kod kanału płatności : '.$parts[7];
						
						
						$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($insert_id, $order_status_id, 0, $platnoscipl_info);
						platnoscipl_debug_email('platnoscipl_handler:INFO:: Zapisany stan zamówienia.');
	
						
						platnoscipl_store_transaction($insert_id, $parts[3], $parts[7], $parts[4], $parts[1], $parts[2], $parts[5]/100);
						platnoscipl_debug_email('platnoscipl_handler:INFO:: Zapisane dane transakcji platnosci.pl.');
	
						

					$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_PAYMENT_MODULES_AFTER_ORDER_CREATE');
					platnoscipl_debug_email('platnoscipl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_PAYMENT_MODULES_AFTER_ORDER_CREATE.');
					
					$order->create_add_products($insert_id);
					$_SESSION['order_number_created'] = $insert_id;
					$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_CREATE_ADD_PRODUCTS');
					platnoscipl_debug_email('platnoscipl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_CREATE_ADD_PRODUCTS.');
					
					$order->send_order_email($insert_id, 2);
					$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_SEND_ORDER_EMAIL');
					platnoscipl_debug_email('platnoscipl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_SEND_ORDER_EMAIL.');
					
					/**
					 * Calculate order amount for display purposes on checkout-success page as well as adword campaigns etc
					 * Takes the product subtotal and subtracts all credits from it
					 */

					$ototal = $order_subtotal = $credits_applied = 0;
					for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
						if ($order_totals[$i]['code'] == 'ot_subtotal') $order_subtotal = $order_totals[$i]['value'];
						if ($$order_totals[$i]['code']->credit_class == true) $credits_applied += $order_totals[$i]['value'];
						if ($order_totals[$i]['code'] == 'ot_total') $ototal = $order_totals[$i]['value'];
					}
					$commissionable_order = ($order_subtotal - $credits_applied);
					$commissionable_order_formatted = $currencies->format($commissionable_order);
					$_SESSION['order_summary']['order_number'] = $insert_id;
					$_SESSION['order_summary']['order_subtotal'] = $order_subtotal;
					$_SESSION['order_summary']['credits_applied'] = $credits_applied;
					$_SESSION['order_summary']['order_total'] = $ototal;
					$_SESSION['order_summary']['commissionable_order'] = $commissionable_order;
					$_SESSION['order_summary']['commissionable_order_formatted'] = $commissionable_order_formatted;
					$_SESSION['order_summary']['coupon_code'] = $order->info['coupon_code'];
					$_SESSION['order_summary']['currency_code'] = $order->info['currency'];
					$_SESSION['order_summary']['currency_value'] = $order->info['currency_value'];
					$_SESSION['order_summary']['payment_module_code'] = $order->info['payment_module_code'];
					$_SESSION['order_summary']['shipping_method'] = $order->info['shipping_method'];
					$_SESSION['order_summary']['orders_status'] = $order->info['orders_status'];
					$_SESSION['order_summary']['tax'] = $order->info['tax'];
					$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_HANDLE_AFFILIATES');
					platnoscipl_debug_email('platnoscipl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_HANDLE_AFFILIATES.');
					

        			$_SESSION['cart']->reset(true);

					
					platnoscipl_debug_email('platnoscipl_handler:INFO:: Płatnośc uznana za nową - wykonano checkout process i potwierdzono odbiór informacji z PłatnościPL.');
					die ("OK");
			}
		}
		$order = $db->Execute("select currency, currency_value from " . TABLE_ORDERS . " where orders_id = '" . $orders_id . "'");
		if ($order->RecordCount() > 0) {
			$order = $order->fields;
    
			$total = $db->Execute("select value from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $orders_id . "' and class = 'ot_total' limit 1");
			$total = $total->fields;
			
			if (MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_ID > 0 && $result['code'] == 99) {
				$order_status_id = MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_ID;
			}

			$order_total = $total['value'];
			$payment_total = round($order_total * $currencies->get_value($payment_currency), 2);

			$comment_status = 'Kwota płatności: ' . $currencies->format($parts[5]/100,false,$payment_currency);

			if($currencies->get_value($payment_currency) != $order['currency']) {
				$comment_status .= "\n".'Kurs: '.$currencies->format(1).' = '.$currencies->format(1,true,$payment_currency);
			}
			$const_name = 'MODULE_PAYMENT_PLATNOSCIPL_STATUS_' . $result['code'];
			$order_status_id = defined($const_name)?constant($const_name):DEFAULT_ORDERS_STATUS_ID;

			if (($result['code'] == 99 && ($payment_total != $parts[5]/100))) {
				$comment_status .= "\n".'Wartość zamówienia: '.$currencies->format($order_total);
				$comment_status .= "\n".'Wartość do płatnosci: '.$currencies->format($payment_total, false, $payment_currency);
				$order_status_id = MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_KWOTA;
			}

	        $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'] != $order_status_id)) {

				switch ($order_status_id) {
					case MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_ID :
							$notify = (MODULE_PAYMENT_PLATNOSCIPL_MAIL_STATUS_ID == 'Tak');
							$notify_comments = sprintf(MODULE_PAYMENT_PLATNOSCIPL_COMMENT_STATUS_ID, $orders_id);
						break;
					case MODULE_PAYMENT_PLATNOSCIPL_ORDER_STATUS_KWOTA :
							$notify = (MODULE_PAYMENT_PLATNOSCIPL_MAIL_STATUS_KWOTA == 'Tak');
							$notify_comments = sprintf(MODULE_PAYMENT_PLATNOSCIPL_COMMENT_STATUS_KWOTA, $orders_id);
						break;
					default :
						$notify = false;
				}

				$customer_notified = '0';

				if ($notify) {
					
					$orders_status_name = platnoscipl_get_orders_status_name($order_status_id);
	
					$message = STORE_NAME . "\n" . MODULE_PAYMENT_PLATNOSCIPL_EMAIL_SEPARATOR . "\n" .
					MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id . "\n\n" .
					MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($check_status->fields['date_purchased']) . "\n\n" .
					strip_tags($notify_comments) . "\n\n" .
					MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_STATUS_UPDATED . sprintf(MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_STATUS_LABEL, $orders_status_name ) .
					MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_STATUS_PLEASE_REPLY;
					
					$html_msg['EMAIL_TO_NAME'] ='';
					$html_msg['EMAIL_TO_ADDRESS'] ='';
					$html_msg['EMAIL_SUBJECT'] ='';
					$html_msg['EMAIL_FROM_NAME'] ='';
					$html_msg['EMAIL_FROM_ADDRESS'] ='';
					$html_msg['EMAIL_CUSTOMERS_NAME']    = $check_status->fields['customers_name'];
					$html_msg['EMAIL_TEXT_ORDER_NUMBER'] = MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id;
					$html_msg['EMAIL_TEXT_DATE_ORDERED'] = MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($check_status->fields['date_purchased']);
					$html_msg['EMAIL_TEXT_STATUS_COMMENTS'] = nl2br($notify_comments);
					$html_msg['EMAIL_TEXT_STATUS_UPDATED'] = str_replace('\n','', MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_STATUS_UPDATED);
					$html_msg['EMAIL_TEXT_STATUS_LABEL'] = str_replace('\n','', sprintf(MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_STATUS_LABEL, $orders_status_name ));
					$html_msg['EMAIL_TEXT_NEW_STATUS'] = $orders_status_name;
					$html_msg['EMAIL_TEXT_STATUS_PLEASE_REPLY'] = str_replace('\n','', MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_STATUS_PLEASE_REPLY);

					zen_mail($check_status->fields['customers_name'], $check_status->fields['customers_email_address'], MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_SUBJECT . EMAIL_ORDER_NUMBER_SUBJECT . $orders_id, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status');
					$customer_notified = '1';

					if ((MODULE_PAYMENT_PLATNOSCIPL_ORDER_NOTIFICATION=='Tak' or SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_STATUS == '1') and SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO != '') {
						zen_mail('', SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO, SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_SUBJECT . ' ' . MODULE_PAYMENT_PLATNOSCIPL_EMAIL_TEXT_SUBJECT . EMAIL_ORDER_NUMBER_SUBJECT . $orders_id, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status_extra');
					}
				}

				$db->Execute("update " . TABLE_ORDERS . " set orders_status = '" . $order_status_id . "', last_modified = now() where orders_id = '" . (int)$orders_id . "'");
	
				$sql_data_array = array(
										'orders_id' => $orders_id,
										'orders_status_id' => $order_status_id,
										'date_added' => 'now()',
										'customer_notified' => $customer_notified,
										'comments' => $comment_status
									);
				zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

			}

			die ("OK");
		}
		else {
			platnoscipl_debug_email('platnoscipl_handler:ERROR:: Nie znaleziono zamówienia.'."\n\nParts : ".print_r($parts,true)."\n\nResponse".print_r($platnosci_response,true));
		}
	}
	else {
		platnoscipl_debug_email('platnoscipl_handler:ERROR:: Niezpoznany status transakcji : '.$result['code']."\n\nResult : ".print_r($result,true)."\n\nResponse".print_r($platnosci_response,true));
	}
}
else {
	platnoscipl_debug_email('platnoscipl_handler:ERROR:: Nieprawidłowe dane w odpowiedzi na callback.'."\n\nParts".print_r($parts,true)."\n\nResponse".print_r($platnosci_response,true));
}
  
die ("ERROR");
