<?php

namespace YSquare\GiftCert\Controller;

class BasketController extends BasketController_parent {

    /**
     * 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 {
            parent::addVoucher();
        }
    }

    public function removeGiftcert() {
        $oBasket = $this->getSession()->getBasket();
        $oBasket->removeGiftcert(\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('voucherId'));
    }

    /** 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;
    }

}