<?php

namespace YSquare\GiftCert\Controller;


use OxidEsales\Eshop\Application\Controller\BasketController;
use OxidEsales\Eshop\Core\Registry;

class PaymentController extends PaymentController_parent
{

    public function render(){

        $viewConfig = $this->getViewConfig();

        if(!$viewConfig->isGiftcertBusinessCleanBasket()) {
            Registry::getUtilsView()->addErrorToDisplay("YS_GIFTCERT_BUSINESS_NOT_UNIQUE_BASKET_ERROR", false, false, null, 'basket');
            Registry::getUtils()->redirect(Registry::getConfig()->getShopHomeUrl() . 'cl=basket', false, 302);
        }

        return parent::render();
    }

    /* View functions */

    /**
     * @return mixed
     */
    public function getAllSets()
    {
        $allSets = parent::getAllSets();

        $config = Registry::getConfig();
        $allowedOnline = $config->getConfigParam('aYsGiftcertAllowedShippingtypesOnline') ?? [];
        $allowedOffline = $config->getConfigParam('aYsGiftcertAllowedShippingtypesOffline') ?? [];
        $allowedBusiness = $config->getConfigParam('aYsGiftcertAllowedShippingtypesBusiness') ?? [];

        // check if offline article is in Basket
        $hasOffline = false;
        $hasOnline = false;
        $hasBusiness = false;
        $oBasket = Registry::getSession()->getBasket();
        $articles = $oBasket->getBasketArticles();
        foreach ($articles as $article) {
            if ($article->isGiftCertArticle() && $article->isOfflineGiftCert()) {
                $hasOffline = true;
                break;
            }
        }
        // check if business
        foreach ($articles as $article) {
            if ($article->isGiftCertArticle() && $article->isBusinessGiftCert()) {
                $hasBusiness = true;
                break;
            }
        }

        // check if non business online article is in Basket
        foreach ($articles as $article) {
            if ($article->isGiftCertArticle() && !$article->isOfflineGiftCert() && !$article->isBusinessGiftCert()) {
                $hasOnline = true;
                break;
            }
        }

        // merge to lowest consent
        $allowedSets = [];
        if($hasOnline && $hasOffline && $hasBusiness){
            $allowedSets = array_intersect($allowedOnline, $allowedOffline, $allowedBusiness);
        } elseif ($hasOnline && $hasOffline) {
            $allowedSets = array_intersect($allowedOnline, $allowedOffline);
        } elseif ($hasOnline && $hasBusiness) {
            $allowedSets = array_intersect($allowedOnline, $allowedBusiness);
        } elseif ($hasBusiness && $hasOffline) {
            $allowedSets = array_intersect($allowedBusiness, $allowedOffline);
        } elseif ($hasOnline) {
            $allowedSets = $allowedOnline;
        } elseif ($hasOffline) {
            $allowedSets = $allowedOffline;
        } elseif ($hasBusiness) {
            $allowedSets = $allowedBusiness;
        }

        if(
            $hasOnline && is_array($allowedOnline) && count($allowedOnline) > 0 ||
            $hasOffline && is_array($allowedOffline) && count($allowedOffline) > 0 ||
            $hasBusiness && is_array($allowedBusiness) && count($allowedBusiness) > 0)
        {
            foreach ($allSets as $sKey => $oDelivery) {
                if (!$allowedSets || !in_array($sKey, $allowedSets)) {
                    unset($allSets[$sKey]);
                }
            }
        }

        return $allSets;
    }

    /**
     * Check if pool money should be used
     *
     * @return bool
     */
    public function UseGiftcertPoolMoney()
    {
        $session = \OxidEsales\Eshop\Core\Registry::getSession();
        $usePoolMoney = $session->getVariable('ys_giftcert_use_pool_money');

        if ($usePoolMoney == 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Calculate the part that the pool can handle
     *
     * @return mixed
     */
    public function getPoolRedeemFraction()
    {
        $oBasket = Registry::getSession()->getBasket();
        $oUser = $this->getUser();

        $basketvalue = $oBasket->getGiftcertIntermediateTotal(); // Payment and delivery costs not included: If needed use getBruttoSum()
        $poolBalance = $oUser->getYSGiftcertPoolAmount();

        if ($basketvalue->getPrice() < $poolBalance->getPrice()) {
            return $basketvalue;
        } else {
            return $poolBalance;
        }
    }

    /**
     * Set the pool as active as the user chooses it actively
     */
    public function setPayByPoolMoney()
    {
        $usePoolMoney = \OxidEsales\Eshop\Core\Registry::getRequest()->getRequestEscapedParameter('ys_giftcert_use_pool_money');
        if ($usePoolMoney != 1) {
            $usePoolMoney = 0;
        }
        $session = \OxidEsales\Eshop\Core\Registry::getSession();
        $session->setVariable('ys_giftcert_use_pool_money', $usePoolMoney);
        $session->getBasket()->calculateBasket(true);
    }


    /**
     * Make it possible to redeem codes also on the payment page
     */
    /**
     * Assigns voucher or giftcert to current basket
     */
    public function addVoucher()
    {
        $oBasket = $this->getSession()->getBasket();

        //oxid voucher code input
        $vouchercode = $this->getConfig()->getRequestParameter('voucherNr');
        if(empty($vouchercode)){
            //check special input field too
            $vouchercode = $this->getConfig()->getRequestParameter('giftcardNr');
        }
        $prefix = $this->getConfig()->getConfigParam('aYsGiftcertPrefix')."-";

        $isOldGiftcertCode = $this->_checkOldGiftCert($vouchercode);

        // Check if the code is a gift certificate and add that to the basket or fall back to default otherwise
        if($isOldGiftcertCode || substr($vouchercode, 0, strlen($prefix)) === $prefix) {
            $oBasket->addGiftcert($vouchercode);
        } else {
            Registry::get(BasketController::class)->addVoucher();
//            parent::addVoucher();
        }
    }

    /** LEGACY: ONLY FOR SHOPS THAT USED GIFTCARD IN VOUCHER CONTEXT BEFORE */
    protected function _checkOldGiftCert($sGiftcertNr) {

        $sViewName = "ysgiftcert";
        $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
        $sQ = "select {$sViewName}.* from {$sViewName} where 
                    {$sViewName}.ysgiftcertnr = " . $oDb->quote($sGiftcertNr) . " and {$sViewName}.ysrestdiscount > 0";
        if($oDb->getOne($sQ)) {return true;}
        return false;
    }
}