<?php

namespace YSquare\GiftCert\Controller\Admin;

use OxidEsales\Eshop\Core\Field;
use OxidEsales\Eshop\Core\Registry;
use YSquare\GiftCert\Model\GiftCert;

class GiftCertLogAjax extends \OxidEsales\Eshop\Application\Controller\Admin\AdminController
{

    protected $_iVoucherLength = "8";
    protected $_sVoucherChars = "0123456789abcdefghijklmnopqrstuvwxyz";

    public function changeFilter()
    {
        $request = Registry::getRequest();
        $session = Registry::getSession();
        if ($session->hasVariable("ysGiftcertAdminFilters")) {
            $filters = $session->getVariable("ysGiftcertAdminFilters");
        } else {
            // Default
            $filters = ["onlyWithValue" => false];
        }

        if ($request->getRequestEscapedParameter("onlyWithValue")) {
            $filters["onlyWithValue"] = true;
        } else {
            $filters["onlyWithValue"] = false;
        }

        if ($request->getRequestEscapedParameter("filterByCode")) {
            $filters["filterByCode"] = $request->getRequestEscapedParameter("filterByCode");
        }
        $results["debug"] = $request->getRequestEscapedParameter("resetFilterByCode");
        if ($request->getRequestEscapedParameter("resetFilterByCode") == 1) {
            $filters["filterByCode"] = "";
        }
        $session->setVariable("ysGiftcertAdminFilters", $filters);

        $results["status"] = "200";
        $results["filters"] = $filters;
        $this->renderJson($results);
        die();
    }

    /**
     *
     */
    public function redeemGiftcert()
    {
        $oRequest = Registry::getRequest();
        $oConfig = Registry::getConfig();
        $lang = Registry::getLang();


        // Load GET data
        $voucherNr = $oRequest->getRequestEscapedParameter('voucherNr');
        $voucherValue = $oRequest->getRequestEscapedParameter('voucherValue');
        $voucherRedeemFull = $oRequest->getRequestEscapedParameter('fullredeem');

        $voucherValue = floatval(str_replace(',', '.', str_replace('.', '', $voucherValue)));

        // Load voucher
        $voucher = oxNew(GiftCert::class);
        try {
            $voucher->getGiftcertByNr($voucherNr);
        } catch (\OxidEsales\Eshop\Core\Exception\VoucherException $oEx) {
            $results['status'] = "501";
            $results["message"] = $lang->translateString("YS_GIFTCERT_ERROR_CERT_NOT_AVAILABLE");
            $this->renderJson($results);
            die();
        }

        // Redeem voucher
        if (boolval($voucherRedeemFull) || !$oConfig->getConfigParam('blYsGiftcertRedeemPartly')) {
            $redeemValue = $voucher->ysgiftcert__ysrestdiscount->value;
        } else {
            $redeemValue = $voucherValue;
        }

        $voucher->markAsUsed("-", "-", $redeemValue);

        $results["value"] = $redeemValue;
        $results["redeemfull"] = $voucherRedeemFull;
        $results["PartlySetting"] = $oConfig->getConfigParam('blYsGiftcertRedeemPartly');

        $results["status"] = "200";
        $results["message"] = $lang->translateString("YS_REDEEM_GIFTCERT_MODAL_SUCCESS");

        $this->renderJson($results);
        die();
    }

    /**
     *
     */
    function addGiftcert()
    {
        $oRequest = Registry::getRequest();
        $lang = Registry::getLang();
        $oSession = Registry::getSession();

        // Load GET data
        $voucherValue = $oRequest->getRequestEscapedParameter('voucherValue');
        $voucherDate = $oRequest->getRequestEscapedParameter('voucherDate');
        $voucherQuantity = $oRequest->getRequestEscapedParameter('voucherQuantity');
        if (!$voucherQuantity) {
            $voucherQuantity = 1;
        }
        $voucherDate = date('Y-m-d H:i:s', strtotime($voucherDate));

        $code = "";
        $codes = [];
        for ($i = 0; $i < $voucherQuantity; $i++) {
            $data = $this->_createGiftcert($voucherValue, $voucherDate) . " ";
            $code .= $data;
            $codes[] = $data;
        }

        $results["status"] = "200";
        $results["generatedCode"] = $code;
        if ($voucherQuantity > 1) {
            $results["message"] = $lang->translateString("YS_ADD_GIFTCERTS_MODAL_SUCCESS") . $code;
        } else {
            $results["message"] = $lang->translateString("YS_ADD_GIFTCERT_MODAL_SUCCESS") . $code;
        }
        $oSession->setVariable("generatedCode", $codes);

        $this->renderJson($results);
        die();
    }

    /**
     * @param $dPrice
     * @param $date
     * @return string
     */
    protected function _createGiftcert($dPrice, $date)
    {
        $sCode = $this->_generateVoucherCode();
        $oGiftcert = oxNew(\YSquare\GiftCert\Model\GiftCert::class);
        $oGiftcert->ysgiftcert__ysgiftcertnr = new Field($sCode);
        $oGiftcert->ysgiftcert__ysinitialdiscount = new Field($dPrice);
        $oGiftcert->ysgiftcert__ysrestdiscount = new Field($dPrice);
        $oGiftcert->ysgiftcert__ysdatepurchased = new Field($date);
        $oGiftcert->save();
        return $sCode;
    }

    /**
     * @return string
     */
    protected function _generateVoucherCode()
    {
        $string = '';
        for ($p = 0; $p < $this->_iVoucherLength; $p++) {
            $string .= $this->_sVoucherChars[mt_rand(0, strlen($this->_sVoucherChars) - 1)];
        }

        $prefix = Registry::getConfig()->getConfigParam('aYsGiftcertPrefix');
        $string = $prefix . "-" . $string;

        return $string;
    }

    public function deleteGiftcert()
    {
        $oRequest = Registry::getRequest();
        $oConfig = Registry::getConfig();
        $lang = Registry::getLang();


        // Load GET data
        $voucherNr = $oRequest->getRequestEscapedParameter('voucherNr');

        // Load voucher
        $voucher = oxNew(GiftCert::class);
        try {
            $voucher->getGiftcertByNr($voucherNr);
        } catch (\OxidEsales\Eshop\Core\Exception\VoucherException $oEx) {
            $results['status'] = "501";
            $results["message"] = $lang->translateString("YS_DELETE_GIFTCERT_MODAL_ERROR_NOT_LOADED");
            $this->renderJson($results);
            die();
        }

        $results["status"] = "200";

        // Delete voucher
        if ($voucher->delete()) {
            $results["message"] = $lang->translateString("YS_DELETE_GIFTCERT_MODAL_SUCCESS");
        } else {
            $results["message"] = $lang->translateString("YS_DELETE_GIFTCERT_MODAL_ERROR");
        }

        $this->renderJson($results);
        die();
    }

    function renderJson($value)
    {

        ini_set('display_errors', 0);
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-type: text/json");

        echo json_encode($value);
    }

}