<?php

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

if(MODULE_PAYMENT_DOTPAYPL_DIAG == 'Yes') {
	$message = "---- BOF: HANDLER INFO -----\n";
	$message .= "GET=".print_r($_GET,true)."\n";
	$message .= "POST=".print_r($_POST,true)."\n";
	$message .= "REQUEST=".print_r($_REQUEST,true)."\n";
	$message .= "SERVER=".print_r($_SERVER,true)."\n";
	$message .= "---- EOF: HANDLER INFO -----\n";
	dotpaypl_debug_email($message);
}

if(!$dotpayplFoundSession) {
	die ('ERROR'."\n".'dotpaypl_handler: FATAL ERROR:: bug session.');
}

if (!dotpaypl_validate_URLC_Call()) {
	die ('ERROR'."\n".'dotpaypl_handler: FATAL ERROR:: error URLC.');
}

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

$payment_currency = 'PLN';

$result = dotpaypl_get_status();
$orders_id = dotpaypl_get_orders_id($_POST['control']);
if($orders_id === false) {

	dotpaypl_debug_email('dotpaypl_handler:INFO:: Payment new.');

	require(DIR_WS_CLASSES . 'payment.php');
	$payment_modules = new payment($_SESSION['payment']);
	dotpaypl_debug_email('dotpaypl_handler:INFO:: insert payment_modules.');

	require(DIR_WS_CLASSES . 'shipping.php');
	$shipping_modules = new shipping($_SESSION['shipping']);
	dotpaypl_debug_email('dotpaypl_handler:INFO:: insert shipping_modules.');
	
	require(DIR_WS_CLASSES . 'order.php');
	$order = new order;
	dotpaypl_debug_email('dotpaypl_handler:INFO:: New order.');
	
	require(DIR_WS_CLASSES . 'order_total.php');
	$order_total_modules = new order_total;
	dotpaypl_debug_email('dotpaypl_handler:INFO:: insert order_total_modules.');
	
	$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_BEFORE_ORDER_TOTALS_PROCESS');
	dotpaypl_debug_email('dotpaypl_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');
	dotpaypl_debug_email('dotpaypl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_TOTALS_PROCESS.');
	
	$payment_modules->before_process();
	$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_PAYMENT_MODULES_BEFOREPROCESS');
	dotpaypl_debug_email('dotpaypl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_PAYMENT_MODULES_BEFOREPROCESS.');

	$insert_id = $order->create($order_totals, 2);
	$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_CREATE');
	dotpaypl_debug_email('dotpaypl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_CREATE.');

	$payment_modules->after_order_create($insert_id);
	$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_PAYMENT_MODULES_AFTER_ORDER_CREATE');
	dotpaypl_debug_email('dotpaypl_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');
	dotpaypl_debug_email('dotpaypl_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');
	dotpaypl_debug_email('dotpaypl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_AFTER_SEND_ORDER_EMAIL.');
	
	$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');
	dotpaypl_debug_email('dotpaypl_handler:INFO:: NOTIFY_CHECKOUT_PROCESS_HANDLE_AFFILIATES.');
	 
	dotpaypl_store_URLC_transaction($insert_id, $_POST['osCsid'], $_POST['control'], $_POST);
	dotpaypl_debug_email('dotpaypl_handler:INFO:: transaction write');

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

	  unset($_SESSION['sendto']);
	  unset($_SESSION['billto']);
	  unset($_SESSION['shipping']);
	  unset($_SESSION['payment']);
	  unset($_SESSION['comments']);
	  $order_total_modules->clear_posts();//ICW ADDED FOR CREDIT CLASS SYSTEM

	dotpaypl_debug_email('dotpaypl_handler:INFO:: new payment - action checkout process.');

	$orders_id = $insert_id;
	
}

$const_name = 'MODULE_PAYMENT_DOTPAYPL_STATUS_' . $result['code'];
$order_status_id = defined($const_name)?constant($const_name):DEFAULT_ORDERS_STATUS_ID;

$comment_status = MODULE_PAYMENT_DOTPAYPL_TEXT_130 . $_POST['t_id'];
$comment_status .= "\n" . MODULE_PAYMENT_DOTPAYPL_TEXT_140 . $_POST['t_date'];
$comment_status .= "\n" . MODULE_PAYMENT_DOTPAYPL_TEXT_170 . $_POST['channel'];
$comment_status .= "\n" . MODULE_PAYMENT_DOTPAYPL_TEXT_160 . $currencies->format($_POST['amount'],false,$payment_currency);
$comment_status .= "\n" . MODULE_PAYMENT_DOTPAYPL_TEXT_150 . $currencies->format($_POST['orginal_amount'],false,$payment_currency);

$zla_kwota = false;
if ($result['code'] == 2) {
	
	$order_currency = $db->Execute("select currency, currency_value from " . TABLE_ORDERS . " where orders_id = '" . $orders_id . "'");
	dotpaypl_debug_email('dotpaypl_handler:INFO:: insert order_currency: '.print_r($order_currency,true));

	$order_currency = $order_currency->fields;

	dotpaypl_debug_email('dotpaypl_handler:INFO:: controll payment total.');
	$total = $db->Execute("select value from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $orders_id . "' and class = 'ot_total' limit 1");
	$total = $total->fields;
	$order_total = $total['value'];
	$payment_total = round($order_total * $currencies->get_value($payment_currency), 2);

	if($currencies->get_value($payment_currency) != $order_currency['currency']) {
		
		$comment_status .= "\n".MODULE_PAYMENT_DOTPAYPL_TEXT_180.$currencies->format(1).' = '.$currencies->format(1,true,$payment_currency);
	}

	$zla_kwota = ($result['code'] == 2 && ($payment_total != $_POST['amount'])); 
	dotpaypl_debug_email('dotpaypl_handler:INFO:: finnish cotrol payment total.');
}

  dotpaypl_store_orders_status_history($orders_id, $order_status_id, 0, $comment_status);
dotpaypl_debug_email('dotpaypl_handler:INFO:: write status.'.print_r($sql_data_array,true));

if ($zla_kwota) {

	$comment_status = MODULE_PAYMENT_DOTPAYPL_TEXT_160 . $currencies->format($_POST['amount'],false,$payment_currency);
	$comment_status .= "\n".MODULE_PAYMENT_DOTPAYPL_TEXT_190.$currencies->format($order_total);
	$comment_status .= "\n".MODULE_PAYMENT_DOTPAYPL_TEXT_150.$currencies->format($payment_total, false, $payment_currency);
	$order_status_id = MODULE_PAYMENT_DOTPAYPL_ORDER_STATUS_KWOTA;
}

if (MODULE_PAYMENT_DOTPAYPL_ORDER_STATUS_ID > 0 && $result['code'] == 2) {
	
	$order_status_id = MODULE_PAYMENT_DOTPAYPL_ORDER_STATUS_ID;
}

$check_status = $db->Execute("select customers_name, customers_email_address, orders_status,
                              date_purchased from " . TABLE_ORDERS . "
                              where orders_id = '" . (int)$orders_id . "'");

dotpaypl_debug_email('dotpaypl_handler:INFO:: status: '.print_r($check_status->fields,true));

switch ($order_status_id) {
	case MODULE_PAYMENT_DOTPAYPL_ORDER_STATUS_ID :		
			$notify = (MODULE_PAYMENT_DOTPAYPL_MAIL_STATUS_ID == 'Tak');
			$notify_comments = sprintf(MODULE_PAYMENT_DOTPAYPL_COMMENT_STATUS_ID, $orders_id);
			$store_order_status = true;
		break;
	case MODULE_PAYMENT_DOTPAYPL_ORDER_STATUS_KWOTA :
			$notify = (MODULE_PAYMENT_DOTPAYPL_MAIL_STATUS_KWOTA == 'Tak');
			$notify_comments = sprintf(MODULE_PAYMENT_DOTPAYPL_COMMENT_STATUS_KWOTA, $orders_id);
			$store_order_status = true;
		break;
	default :
	$notify = false;
	$notify_comments = '';
	$store_order_status = false;
}

$customer_notified = '0';

if ($notify) {
	dotpaypl_debug_email('dotpaypl_handler:INFO:: submit mail.');
	
	$orders_status_name = dotpaypl_get_orders_status_name($order_status_id);

	$message = STORE_NAME . "\n" . MODULE_PAYMENT_DOTPAYPL_EMAIL_SEPARATOR . "\n" .
	MODULE_PAYMENT_DOTPAYPL_EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id . "\n\n" .
	MODULE_PAYMENT_DOTPAYPL_EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($check_status->fields['date_purchased']) . "\n\n" .
	strip_tags($notify_comments) . "\n\n" .
	MODULE_PAYMENT_DOTPAYPL_EMAIL_TEXT_STATUS_UPDATED . sprintf(MODULE_PAYMENT_DOTPAYPL_EMAIL_TEXT_STATUS_LABEL, $orders_status_name ) .
	MODULE_PAYMENT_DOTPAYPL_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_DOTPAYPL_EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id;
	$html_msg['EMAIL_TEXT_DATE_ORDERED'] = MODULE_PAYMENT_DOTPAYPL_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_DOTPAYPL_EMAIL_TEXT_STATUS_UPDATED);
	$html_msg['EMAIL_TEXT_STATUS_LABEL'] = str_replace('\n','', sprintf(MODULE_PAYMENT_DOTPAYPL_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_DOTPAYPL_EMAIL_TEXT_STATUS_PLEASE_REPLY);

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

	dotpaypl_debug_email('dotpaypl_handler:INFO:: submit email customer.');

	if ((MODULE_PAYMENT_DOTPAYPL_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_DOTPAYPL_EMAIL_TEXT_SUBJECT . EMAIL_ORDER_NUMBER_SUBJECT . $orders_id, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status_extra');
		dotpaypl_debug_email('dotpaypl_handler:INFO:: submit extra email.');
	}
}

if ($store_order_status) {
	dotpaypl_store_orders_status_history($orders_id, $order_status_id, $customer_notified, $notify_comments);
	dotpaypl_debug_email('dotpaypl_handler:INFO:: write status.'.print_r($sql_data_array,true));
}

dotpaypl_debug_email('dotpaypl_handler:INFO:: status finnish OK.');
die ("OK");

