<?php

include_once './core/order.class.php';
include_once './core/paypalrefund.class.php';
include_once './core/paypal/nvp.class.php';

class Transaction { 

	private $nvp;
	private $currency;

	function __construct() {
		$this->nvp = new NVP();
		$this->currency = 'EUR';
	}

	public function get_transaction_details ($order_id) {
		$order = new Order(Registry::get('base'));
		$order->set_id($order_id);
		$order_data = $order->get_data();

		$postfields = "TRANSACTIONID=".$order_data->paypal_transaction_id;

		$data = $this->nvp->do_post_action('GetTransactionDetails', $postfields);

		if ($data['ACK'] == 'Success') {
			$return_object = new stdClass();
			$return_object->email = $data['EMAIL'];
			$return_object->payer_status = $data['PAYERSTATUS'];
			$return_object->paypal_fees = $data['FEEAMT'];
			$return_object->payment_status = $data['PAYMENTSTATUS'];
			$return_object->transaction_id = $order_data->paypal_transaction_id;

			return $return_object;
		}

		return false;
	}

	public function refund_transaction ($paypal_refund_id) {
		$paypal_refund = new PaypalRefund(Registry::get('base'));
		$paypal_refund->set_id($paypal_refund_id);
		$paypal_refund_data = $paypal_refund->get_data();

		if ($paypal_refund_data->refund_type == 1) {
			$postfields = "TRANSACTIONID=".$paypal_refund_data->paypal_transaction_id
			."&REFUNDTYPE=Full"
			."&CURRENCYCODE=".$this->currency;
		} else {
			$postfields = "TRANSACTIONID=".$paypal_refund_data->paypal_transaction_id
			."&REFUNDTYPE=Partial"
			."&AMT=".$paypal_refund_data->refund_amount
			."&CURRENCYCODE=".$this->currency;
		}

		$data = $this->nvp->do_post_action('RefundTransaction', $postfields);

		if ($data['ACK'] == 'Success') {
			$return_object = new stdClass();
			$return_object->refund_transaction_id = $data['REFUNDTRANSACTIONID'];
			$return_object->fee_refund_amt = $data['FEEREFUNDAMT'];
			$return_object->gross_refund_amt = $data['GROSSREFUNDAMT'];
			$return_object->net_refund_amt = $data['NETREFUNDAMT'];
			$return_object->refund_time = $data['TIMESTAMP'];

			return $return_object;
		}

		return false;
	}
}
