<?php

/**
 * class d3_oxpaymentgateway_heidelpay
 */
class d3_oxpaymentgateway_heidelpay extends d3_oxpaymentgateway_heidelpay_parent
{

    /**
     * executes heidelpay paymentgateway
     * {@inheritdoc}
     */
    public function executePayment($dAmount, &$oOrder)
    {
        /** @var d3_d3heidelpay_models_factory $oFactory */
        $oFactory = oxNew('d3_d3heidelpay_models_factory', d3_cfg_mod::get('d3heidelpay'));
        /** @var d3_d3heidelpay_controllers_paymentgateway $oGatewayFacade */
        $oGatewayFacade = oxNew(
            'd3_d3heidelpay_controllers_paymentgateway',
            d3_cfg_mod::get('d3heidelpay'),
            oxRegistry::get('oxRegistry'),
            $oOrder,
            $oFactory
        );

        $oTransAction = $oFactory->getLatestTransactionByReference($oFactory->getReferenceNumber());

        if (false == $oTransAction) {
            /** @var d3transactionlog $oTransAction */
            $oTransAction = oxNew(
                'd3transactionlog',
                oxNew('d3_d3heidelpay_models_transactionlog_reader_heidelpay'),
                $oFactory->getReferenceNumber()
            );
            $oTransAction->setTransactiondata('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><response/>');
        }

        /** @var d3_d3heidelpay_models_response_parser $oParser */
        $oParser = oxNew(
            'd3_d3heidelpay_models_response_parser',
            d3_cfg_mod::get('d3heidelpay'),
            oxRegistry::get('oxRegistry'),
            $oTransAction->getTransactiondata()
        );

        $mReturn = $oGatewayFacade->executePayment($dAmount, $this->getPayment(), $oParser);

        d3_cfg_mod::get('d3heidelpay')->d3getLog()->Log(
            d3log::INFO,
            __CLASS__,
            __FUNCTION__,
            __LINE__,
            'd3_d3heidelpay_controllers_paymentgateway return value',
            print_r(var_export($mReturn, true), true)
        );

        if (d3_d3heidelpay_controllers_paymentgateway::CALLPARENT === $mReturn) {
            return parent::ExecutePayment($dAmount, $oOrder);
        }

        //payment successful
        if (true === $mReturn) {
            return $mReturn;
        }

        //wrong result -> got error / message
        $this->_iLastErrorNo = $mReturn;

        return false;
    }

    /**
     * Load and returns oxPayment object.
     *
     * @return oxPayment
     */
    public function getPayment()
    {
        /** @var oxPayment $oPayment */
        $oPayment = oxNew('oxPayment');
        $oPayment->load($this->_oPaymentInfo->oxuserpayments__oxpaymentsid->value);

        return $oPayment;
    }
}
