<?php

include_once './core/registry.class.php';
include_once './core/paypalexpresscheckout.class.php';
include_once './core/orderstatus.class.php';

function pay_order($base_object, $layout_object, $order_id) {
	$order_id = $_GET['order_id'];
	$menu_id = $_GET['menu_id'];
	
	$return_url = 'http://' . $_SERVER['SERVER_NAME'] . '/index.php?menu_id=' . $menu_id;
	$cancel_url = $return_url . '&cancel=true';
	
	$order_id = $_GET['order_id'];
	$order = new Order(Registry::get('base'));
	
	$paypal = new PayPalExpressCheckout($return_url, $cancel_url, $order->get_order_total_by_id($order_id));
	
	// payment_cancelled
	// payment_open
	// payment_confirm
	// payment_confirmed
	// payment_error
	
	if (isset($_GET['confirm'])) {
		$token = $_GET['token'];
		$payer_id = $_GET['PayerId'];

		if ($paypal->do_express_checkout_payment($token, $payer_id)) {
			$order->set_order_status(OrderStatus::open(), $id);
			
			$call = 'payment_confirmed';
		} else {
			$layout_object->assign('message', 'Beim Bezahlabschluss ist ein Fehler aufgetreten. ');
			$call = 'payment_error';
		}
	} elseif (isset($_GET['cancel'])) {
		$call = 'payment_cancelled';	
		$order->set_order_status(OrderStatus::cancel(), $order_id);
		
	} else {
		$token = $_GET['token'];
		$payer_id = $_GET['PayerId'];
			
		if (isset($_GET['token'])) {
			if ($paypal->get_express_checkout_details($token)) {
				
				$confirm_url = 'http://' . $_SERVER['SERVER_NAME'] . '/index.php?menu_id=' . $menu_id . '&step=5&order_id=' . $order_id . '&token=' . $token . '&PayerId=' . $payer_id . '&confirm=' . true;
				$layout_object->assign('confirm_url', $confirm_url);
				
				$call = 'payment_confirm';
			} else {
				$layout_object->assign('message', 'Bei der PayPal rückfrage ist ein Fehler aufgetreten.');
				$call = 'payment_error';
			}
		} else {
			if ($paypal->set_express_checkout()) {
				$layout_object->assign('paypal_link', $paypal->get_link());
				$token = $paypal->get_token();
				$order->set_order_paypal_token($token, $order_id);
				
				$call = 'payment_open';
			} else {
				$layout_object->assign('message', 'Beim Initialisieren von PayPal ist ein Fehler aufgetreten.');
				$call = 'payment_error';
			}
		}
	}
	
	
	$layout_object->assign('call', $call);
	
	return $layout_object->fetch('payment_method_paypal.tpl');
}