<?php

/**
 * Class d3_oxorder_heidelpay
 */
class d3_oxorder_heidelpay extends d3_oxorder_heidelpay_parent
{

    /**
     * {@inheritdoc}
     */
    protected function _setOrderStatus($sStatus)
    {
        if (false == d3_cfg_mod::get('d3heidelpay')->isActive()) {
            return parent::_setOrderStatus($sStatus);
        }

        $oDB = oxDb::getDb();

        $sOldStatus = $oDB->GetOne('select oxtransstatus from oxorder where oxid="' . $this->getId() . '"');
        $sPaid      = $oDB->GetOne('select oxpaid from oxorder where oxid="' . $this->getId() . '"');
        $sPaymentId = $this->getFieldData('oxpaymenttype');

        /** @var d3_d3heidelpay_models_settings_heidelpay $oSettings */
        $oSettings = oxNew('d3_d3heidelpay_models_settings_heidelpay', d3_cfg_mod::get('d3heidelpay'));

        /** @var oxPayment $oPayment */
        $oPayment = oxNew('oxPayment');
        $oPayment->load($sPaymentId);

        if (false == $oSettings->isAssignedToHeidelPayment($oPayment)) {
            return parent::_setOrderStatus($sStatus);
        }

        $blIsPrepayment = $oSettings->getPayment($oPayment) instanceof d3_d3heidelpay_models_payment_prepayment;
        $blIsWaiting    = $sOldStatus == 'WAITING' && $sPaid == '0000-00-00 00:00:00';
        if ($blIsPrepayment && $blIsWaiting) {
            $sStatus = "WAITING";
        }

        return parent::_setOrderStatus($sStatus);
    }

    /**
     * Returns bank transfer data if available
     *
     * @return stdClass|null
     */
    public function getHeidelpayBankTransferData()
    {
        if (false == d3_cfg_mod::get('d3heidelpay')->isActive()) {
            return null;
        }

        /** @var d3hpprepaymentdata $oPrePaymentData */
        $oPrePaymentData = oxNew("d3hpprepaymentdata");

        /** @var d3_d3heidelpay_models_settings_heidelpay $oSettings */
        /** @var oxPayment $oPayment */
        $oSettings = oxNew('d3_d3heidelpay_models_settings_heidelpay', d3_cfg_mod::get('d3heidelpay'));
        $oPayment  = oxNew('oxPayment');
        $oPayment->load($this->getFieldData('oxpaymenttype'));
        if (false == $oSettings->isAssignedToHeidelPayment($oPayment)) {
            return null;
        }

        $oHeidelpayment = $oSettings->getPayment($oPayment);

        if ($oHeidelpayment instanceof d3_d3heidelpay_models_payment_prepayment || $oHeidelpayment instanceof d3_d3heidelpay_models_payment_billsafe) {
            return $oPrePaymentData->getBankTransferData($this);
        }

        return null;
    }


    public function finalizeOrder(oxBasket $oxBasket, $oxUser, $blRecalculatingOrder = false)
    {
        $return = parent::finalizeOrder($oxBasket, $oxUser, $blRecalculatingOrder);

        $registry           = oxRegistry::get('oxRegistry');
        $modulConfiguration = d3_cfg_mod::get('d3heidelpay');

        if (false == $modulConfiguration->isActive() || $registry->getConfig()->isAdmin()) {

            return $return;
        }

        /** @var oxPayment $oPayment */
        $oPayment = oxNew('oxPayment');
        $oPayment->load($oxBasket->getPaymentId());

        try {
            /** @var d3_d3heidelpay_models_payment_abstract $heidelPayment */
            $heidelPayment = $registry->get('d3_d3heidelpay_models_settings_heidelpay')->getPayment($oPayment);
        } catch (d3_d3heidelpay_models_payment_exception_PaymentNotReferencedToHeidelpayException $oEx) {
            return $return;
        }

        if (false == $heidelPayment instanceof d3_d3heidelpay_models_payment_abstract) {
            return $return;
        }

        /** @var d3_d3heidelpay_models_factory $factory */
        $factory     = oxNew('d3_d3heidelpay_models_factory', $modulConfiguration);
        $transaction = $factory->getLatestTransactionByReference($factory->getReferenceNumber());

        if (false == $transaction) {
            return $return;
        }

        /** @var d3_d3heidelpay_models_transactionlog_reader_heidelpay $reader */
        $reader       = $transaction->getTransactiondata();
        $basketAmount = $oxBasket->getPrice()->getBruttoPrice();

        $basketAmount = number_format($basketAmount, '2', '.', '');
        if ($basketAmount !== $reader->getAmount()) {

            $transStatusError = $modulConfiguration->getValue('d3heidelpay_oxtransstatuserror');
            if(empty($transStatusError)) {
                $transStatusError = 'ERROR';
            }
            $aAssignment                  = array();
            $aAssignment['oxtransstatus'] = $transStatusError;
            $aAssignment['oxpaid']        = '0000-00-00 00:00:00';
            $this->assign($aAssignment);
            $this->save();


            $message = $registry->getLang()->translateString('D3HEIDELPAY_DIFFERENCE_IN_ORDER_ERRRORMESSAGE', null, true);
            $message = sprintf($message, $this->getFieldData('oxordernr'), $reader->getUniqueid(), $reader->getAmount(), $basketAmount);

            $subject = $registry->getLang()->translateString('D3HEIDELPAY_DIFFERENCE_IN_ORDER_SUBJECT', null, true);
            $subject .= $this->getFieldData('oxordernr');

            $recipient = $modulConfiguration->getValue('d3heidelpay_oxtransstatuserrormail');
            if (empty($recipient)) {
                $recipient = $this->getConfig()->getActiveShop()->getFieldData('oxowneremail');
            }

            $email = oxNew('oxEMail');
            $email->d3SendDifferenceInOrderMail($subject, $message, $recipient);

            $modulConfiguration->d3getLog()->log(
                d3log::ERROR,
                __CLASS__,
                __FUNCTION__,
                __LINE__,
                $subject,
                $message
            );
        }

        return $return;
    }
}
