<?php

/**
 * class d3_payment_heidelpay
 */
class d3_payment_heidelpay extends d3_payment_heidelpay_parent
{

    /**
     * Bool-Wert fuer das Handling von vorhandenen Kreditkarten-Kunden-Registrierungsdaten in Schritt3
     *
     * @var bool
     */
    protected $sHeidelpayFieldsForPayment;

    protected $_sCheckedProductId;

    public $sHPOpenFormTplName = "heidelpay_payment_inc_openform.tpl";

    public $sHPOxidOpenFormTplName = "heidelpay_oxidpayment_inc_openform.tpl";

    public $sHPCCFormTplName = "payment_heidelpaycreditcard.tpl";

    public $sHPDebitCardFormTplName = "payment_heidelpaydebitcard.tpl";

    public $sHPDebitNoteFormTplName = "payment_heidelpaydebitnote.tpl";

    public $sHPSofortFormTplName = "payment_heidelpaysofort.tpl";

    public $sHPGiroPayFormTplName = "payment_heidelpaygiropay.tpl";

    public $sHPiDealFormTplName = "payment_heidelpayideal.tpl";

    public $sHPEpsFormTplName = "payment_heidelpayeps.tpl";

    public $sHPBillSafeFormTplName = "payment_heidelpaybillsafe.tpl";

    public $sHPPaypalFormTplName = "payment_heidelpaypaypal.tpl";

//    public $sHPPostfinanceFormTplName = "payment_heidelpaypostfinance.tpl";

    public $sHPPrzelewy24FormTplName = "payment_heidelpayprzelewy24.tpl";

    #### mobile-theme
    public $sHPOpenFormTplNameMobile = "heidelpay_payment_inc_openform_mobile.tpl";

    public $sHPOxidOpenFormTplNameMobile = "heidelpay_oxidpayment_inc_openform_mobile.tpl";

    public $sHPCCFormTplNameMobile = "payment_heidelpaycreditcard_mobile.tpl";

    public $sHPDebitCardFormTplNameMobile = "payment_heidelpaydebitcard_mobile.tpl";

    public $sHPDebitNoteFormTplNameMobile = "payment_heidelpaydebitnote_mobile.tpl";

    public $sHPSofortFormTplNameMobile = "payment_heidelpaysofort_mobile.tpl";

    public $sHPGiroPayFormTplNameMobile = "payment_heidelpaygiropay_mobile.tpl";

    public $sHPiDealFormTplNameMobile = "payment_heidelpayideal_mobile.tpl";

    public $sHPEpsFormTplNameMobile = "payment_heidelpayeps_mobile.tpl";

    public $sHPBillSafeFormTplNameMobile = "payment_heidelpaybillsafe_mobile.tpl";

    public $sHPPaypalFormTplNameMobile = "payment_heidelpaypaypal_mobile.tpl";

//    public $sHPPostfinanceFormTplNameMobile = "payment_heidelpaypostfinance_mobile.tpl";

    public $sHPPrzelewy24FormTplNameMobile = "payment_heidelpayprzelewy24_mobile.tpl";

    /**
     * Initiate and register module classes
     * intitiate reference number
     * reset payment success
     *
     * @return void
     */
    public function init()
    {
        parent::init();

        if (false == d3_cfg_mod::get('d3heidelpay')->isActive()) {
            d3_cfg_mod::get('d3heidelpay')->d3getLog()->Log(
                d3log::INFO,
                __CLASS__,
                __FUNCTION__,
                __LINE__,
                'module is inactive',
                'module is inactive'
            );

            return;
        }

        $settings = oxNew('d3_d3heidelpay_models_settings_heidelpay', d3_cfg_mod::get('d3heidelpay'));
        oxRegistry::set('d3_d3heidelpay_models_settings_heidelpay', $settings);

        /** @var d3_d3heidelpay_models_factory $oFactory */
        $oFactory         = oxNew('d3_d3heidelpay_models_factory', d3_cfg_mod::get('d3heidelpay'));
        $sReferenceNumber = $oFactory->getReferenceNumber();
        if (empty($sReferenceNumber)) {
            $oFactory->initReferenceNumber();
        }

        $oHeidelpayViewConfig = oxNew(
            'd3_d3heidelpay_models_viewconfig',
            d3_cfg_mod::get('d3heidelpay'),
            oxRegistry::get('oxRegistry'),
            $oFactory
        );
        $this->addTplParam('oHeidelpayViewConfig', $oHeidelpayViewConfig);

        $oFactory->resetPaymentSuccess();
    }

    //<editor-fold desc="TODO:3 ways with existing paymentdata possible. see /tests/acceptance/selenium/dudeWantToPay.graphml">
    /**
     * Returns true if user has stored payment data
     *
     * @param $sPaymentId
     *
     * @return bool
     */
    public function hasUserHPStoreData($sPaymentId)
    {
        if (false == d3_cfg_mod::get('d3heidelpay')->isActive()) {
            d3_cfg_mod::get('d3heidelpay')->d3getLog()->Log(
                d3log::INFO,
                __CLASS__,
                __FUNCTION__,
                __LINE__,
                'module is inactive',
                'module is inactive'
            );

            return '';
        }

        // keine Anzeige gespeicherter Registrierungsdaten erlauben?
        if (false == d3_cfg_mod::get('d3heidelpay')->getValue('d3heidelpay_blShowStoredHPData')) {
            return '';
        }

        if ($this->sHeidelpayFieldsForPayment == $sPaymentId) {
            return '';
        }

        return (bool)$this->getUserHPStoreID($sPaymentId);
    }

    /**
     * Returns user stored payment data
     *
     * @param $sPaymentId
     *
     * @return bool|object
     */
    public function getUserHPStoreData($sPaymentId)
    {
        if (false == d3_cfg_mod::get('d3heidelpay')->isActive()) {
            return '';
        }

        $oxId = $this->getUserHPStoreID($sPaymentId);
        if (false == $oxId) {
            return '';
        }

        /** @var oxbase $oUsrStoreData */
        $oUsrStoreData = oxNew('oxbase');
        $oUsrStoreData->init('d3hpuid');
        $oUsrStoreData->load($oxId);

        $oUsrStoreData->aDynValue = unserialize($oUsrStoreData->d3hpuid__oxpaymentdata->rawValue);

        return $oUsrStoreData;
    }

    /**
     * Loads user stored data and fill session dynvalue with it
     *
     * @return mixed
     */
    public function getHPWrappedPayment()
    {
        if (false == d3_cfg_mod::get('d3heidelpay')->isActive()) {
            return '';
        }

        $sPaymentId = $this->getConfig()->getRequestParameter("paymentid");

        $blUseHPStore = $this->getConfig()->getRequestParameter("usehpstore");

        if (false == $blUseHPStore || false == $this->hasUserHPStoreData($sPaymentId)) {
            //Setze Flag, um bn BS3 die normalen KK-Eingabefelder zu zeigen
            $this->sHeidelpayFieldsForPayment = $sPaymentId;

            return '';
        }

        $oUsrStoreData = $this->getUserHPStoreData($sPaymentId);

        // setze manuell die UniqueId der gespeicherten Kundenregistierung
        $oUsrStoreData->aDynValue['oxuid'] = $oUsrStoreData->getFieldData('oxuid');

        $this->getSession()->setVariable("dynvalue", $oUsrStoreData->aDynValue);

        return $this->validatePayment();
    }

    //</editor-fold>

    /**
     * Returns current selected payment id/number
     *
     * @return int
     */
    public function getD3CheckedPaymentCount()
    {
        $count = 0;
        if (d3_cfg_mod::get('d3heidelpay')->isActive()) {

            foreach ($this->getPaymentList() as $sPaymentID => $object) {
                if ($sPaymentID == $this->getCheckedPaymentId()) {
                    return $count;
                }
                $count++;
            }
        }

        return $count;
    }

    /**
     * Injects the Trusted Shops Excellence protection into the current session
     *
     * @return bool true if TSprotection is set, false if it was removed
     */
    public function setTsProtection()
    {
        $oBasket = $this->getSession()->getBasket();
        if (oxRegistry::getConfig()->getRequestParameter('bltsprotection')) {
            $sTsProductId = oxRegistry::getConfig()->getRequestParameter('stsprotection');
            $oBasket->setTsProductId($sTsProductId);
            oxRegistry::getSession()->setVariable('stsprotection', $sTsProductId);

            return true;
        }
        oxRegistry::getSession()->deleteVariable('stsprotection');
        $oBasket->setTsProductId(null);

        return false;
    }

    /**
     * Injects the Trusted Shops Excellence protection into the POST superglobal
     *
     * @return mixed
     */
    public function validatePayment()
    {
        $oBasket = $this->getSession()->getBasket();
        if ($oBasket->getTsProductId()) {
            $_POST['bltsprotection'] = true;
            $_POST['stsprotection']  = $oBasket->getTsProductId();
        }

        return parent::validatePayment();
    }

    /**
     * Returns id of user stored payment data
     *
     * @param $sPaymentId
     *
     * @return string
     */
    public function getUserHPStoreID($sPaymentId)
    {
        if (false == ($sUserID = $this->getSession()->getVariable("usr"))) {
            return '';
        }

        return oxDb::getDb()->GetOne(
            "SELECT `oxid` FROM `d3hpuid` WHERE `oxuserid` = '$sUserID' AND `oxpaymentid` = '$sPaymentId'"
        );
    }

    /**
     * Returns dyn values for paymenttype DirectDebit
     *
     * @return array
     */
    public function D3getDynValueHeidelpay()
    {
        $aDynValue = parent::getDynValue();

        // Ticket #0002089
        // Bei maskierter Kontonummer werden keine Kontodaten bei Bestandskunden übergeben
        if (isset($aDynValue['lsktonr']) &&
            substr_count($aDynValue['lsktonr'], "*")) {
            unset($aDynValue);
        }

        if (isset($aDynValue['lsblz']) &&
            d3_cfg_mod::get('d3heidelpay')->getValue('d3heidelpay_blSepaMode') &&
            preg_match('/^[0-9]*$/', $aDynValue['lsblz'])) {

            // Wenn das Feld lsblz nur aus Zahlen besteht, handelt es sich um eine BLZ
            // Mit aktivem SEPA-Modus duefen dann keine Altdaten ans Template uebergeben werden
            return null;
        }

        return $aDynValue;
    }

    /**
     * @return string
     */
    public function getD3ValidatePaymentError()
    {
        /** @var d3utils $oD3Utils */
        $oD3Utils = oxNew('d3utils');
        if ($oD3Utils->hasParentClassMethod($this, __FUNCTION__, __CLASS__)) {
            return parent::getD3ValidatePaymentError();
        }

        return "";
    }

    /**
     * @param oxPayment $oPayment
     * @param string    $sTemplate
     *
     * @return string
     */
    public function d3GetOpenFormTemplateName(oxPayment $oPayment, $sTemplate = 'azure')
    {
        $sTheme = '';
        if ($sTemplate != 'azure') {
            $sTheme = ucfirst($sTemplate);
        }

        /** @var d3_d3heidelpay_models_viewconfig $oHeidelpayViewConfig */
        $oHeidelpayViewConfig = oxNew(
            'd3_d3heidelpay_models_viewconfig',
            d3_cfg_mod::get('d3heidelpay'),
            oxRegistry::get('oxRegistry'),
            oxNew('d3_d3heidelpay_models_factory', d3_cfg_mod::get('d3heidelpay'))
        );
        $oHeidelPaySettings = $oHeidelpayViewConfig->getSettings();
        /** @var d3utils $oD3Utils */
        $oD3Utils = oxNew('d3utils');
        if ($oHeidelPaySettings->isAssignedToHeidelPayment($oPayment)) {
            return $this->{'sHPOpenFormTplName'.$sTheme};
        } elseif ($oD3Utils->hasParentClassMethod($this, __FUNCTION__, __CLASS__)) {
            return parent::d3GetOpenFormTemplateName($oPayment,$sTemplate);
        } else {
            return $this->{'sHPOpenFormTplName'.$sTheme};
        }
    }

    /**
     * @param oxPayment $oPayment
     * @param string    $sTemplate
     *
     * @return string
     */
    public function d3GetPaymentFormTemplateName(oxPayment $oPayment, $sTemplate = 'azure')
    {
        $sTheme = '';
        if ($sTemplate != 'azure') {
            $sTheme = ucfirst($sTemplate);
        }

        /** @var d3utils $oD3Utils */
        $oD3Utils = oxNew('d3utils');

        /** @var d3_d3heidelpay_models_viewconfig $oHeidelpayViewConfig */
        $oHeidelpayViewConfig = oxNew(
            'd3_d3heidelpay_models_viewconfig',
            d3_cfg_mod::get('d3heidelpay'),
            oxRegistry::get('oxRegistry'),
            oxNew('d3_d3heidelpay_models_factory', d3_cfg_mod::get('d3heidelpay'))
        );
        $oHeidelPaySettings = $oHeidelpayViewConfig->getSettings();
        if ($oHeidelPaySettings->isAssignedToHeidelPayment($oPayment)) {
            $oHeidelPayment = $oHeidelPaySettings->getPayment($oPayment);
            if ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_creditcard) {
                return $this->{'sHPCCFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_directdebit) {
                return $this->{'sHPDebitNoteFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_debitcard) {
                return $this->{'sHPDebitCardFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_sofortueberweisung) {
                return $this->{'sHPSofortFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_giropay) {
                return $this->{'sHPGiroPayFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_ideal) {
                return $this->{'sHPiDealFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_eps) {
                return $this->{'sHPEpsFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_billsafe) {
                return $this->{'sHPBillSafeFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_paypal) {
                return $this->{'sHPPaypalFormTplName'.$sTheme};
//            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_postfinance) {
//                return $this->{'sHPPostfinanceFormTplName'.$sTheme};
            } elseif ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_przelewy24) {
                return $this->{'sHPPrzelewy24FormTplName'.$sTheme};
            } else {
                return $this->d3GetDefaultPaymentFormTemplateName($oPayment);
            }
        } elseif ($oD3Utils->hasParentClassMethod($this, __FUNCTION__, __CLASS__)) {
            return parent::d3GetPaymentFormTemplateName($oPayment,$sTemplate);
        } else {
            return $this->d3GetDefaultPaymentFormTemplateName($oPayment);
        }
    }

    /**
     * @param oxPayment $oPayment
     *
     * @return bool
     * @throws d3_d3heidelpay_models_payment_exception_PaymentNotReferencedToHeidelpayException
     */
    public function d3IsHeidelpayPaymentMethode(oxPayment $oPayment)
    {
        /** @var d3utils $oD3Utils */
        $oD3Utils = oxNew('d3utils');

        /** @var d3_d3heidelpay_models_viewconfig $oHeidelpayViewConfig */
        $oHeidelpayViewConfig = oxNew(
        'd3_d3heidelpay_models_viewconfig',
        d3_cfg_mod::get('d3heidelpay'),
        oxRegistry::get('oxRegistry'),
        oxNew('d3_d3heidelpay_models_factory', d3_cfg_mod::get('d3heidelpay'))
        );
        $oHeidelPaySettings = $oHeidelpayViewConfig->getSettings();
        if ($oHeidelPaySettings->isAssignedToHeidelPayment($oPayment)) {
            $oHeidelPayment = $oHeidelPaySettings->getPayment($oPayment);
            if ($oHeidelPayment instanceof d3_d3heidelpay_models_payment_abstract) {
                return true;
            }

            return false;
        } elseif ($oD3Utils->hasParentClassMethod($this, __FUNCTION__, __CLASS__)) {
            return parent::d3IsHeidelpayPaymentMethode($oPayment);
        }

        return false;
    }


    /**
     * @param oxPayment $oPayment
     *
     * @return string
     */
    public function d3GetDefaultPaymentFormTemplateName(oxPayment $oPayment)
    {
        $sPaymentId = $oPayment->getId();

        if ($sPaymentId == "oxidcashondel") {
            return "page/checkout/inc/payment_oxidcashondel.tpl";
        } elseif ($sPaymentId == "oxidcreditcard") {
            return "page/checkout/inc/payment_oxidcreditcard.tpl";
        } elseif ($sPaymentId == "oxiddebitnote") {
            return "page/checkout/inc/payment_oxiddebitnote.tpl";
        } else {
            return "page/checkout/inc/payment_other.tpl";
        }
    }

    /**
     * @return bool
     */
    public function d3CheckForMobileTheme()
    {
        $blIsMobile = false;
        if ( class_exists('oeThemeSwitcherThemeManager') == true) {
            /** @var oeThemeSwitcherThemeManager $oThemeManager */
            $oThemeManager = new oeThemeSwitcherThemeManager();
            $blIsMobile = $oThemeManager->isMobileThemeRequested();
        }
        return $blIsMobile;
    }

    /**
     * @return string
     */
    public function render()
    {
        $mReturn = parent::render();

        $this->addTplParam('blD3HeidelpayAllowPostFinance', $this->isPaymentAllowed('CH', 'CHF'));
        $this->addTplParam('blD3HeidelpayAllowPrzelewy24', $this->isPaymentAllowed('PL', 'PLN'));

        return $mReturn;
    }

    /**
     * @param $sCountryIsoAlpha2
     * @param $sCurrencyName
     *
     * @return bool
     */
    public function isPaymentAllowed($sCountryIsoAlpha2, $sCurrencyName)
    {
        $sCountryId = $this->getUser()->getFieldData('oxcountryid');
        $blAllowed  = false;

        /** @var $oCountry oxcountry * */
        $oCountry = oxNew('oxcountry');
        if ($oCountry->load($sCountryId) && $oCountry->getFieldData('oxisoalpha2') == $sCountryIsoAlpha2 //
            && $this->getActCurrency()->name == $sCurrencyName
        ) {
            $blAllowed = true;

            return $blAllowed;
        }

        return $blAllowed;
    }
}
