<?php

namespace YSquare\GiftCert\Controller\Admin;

use OxidEsales\Eshop\Core\Field;
use OxidEsales\Eshop\Core\Registry;

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

    protected $_sThisTemplate = 'ys_giftcert__admin_user.tpl';

    public function render(){
        $soxId = $this->_aViewData["oxid"] = $this->getEditObjectId();
        if (isset($soxId) && $soxId != "-1") {
            // load object
            $oUser = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
            $oUser->load($soxId);
            $this->_aViewData["edit"] = $oUser;
        }

        return parent::render();
    }



    public function getGiftcertLogList() {
        $aGiftcertLogList = [];
        $sQ = "SELECT log.*, g.ysgiftcertnr as YSGIFTCERTNR from ysgiftcertlog log left join ysgiftcert g on log.ysgiftcertid = g.oxid where ysuserid = ? order by ysdateused desc";
        $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC);

        $rs = $oDb->select($sQ, [$this->getEditObjectId()]);
        if ($rs != false && $rs->count() > 0) {
            while (!$rs->EOF) {
                $aGiftcertLogList[$rs->fields['OXID']] = $rs->fields;
                $rs->fetchRow();
            }
        }

        return $aGiftcertLogList;
    }

    public function changeCreditAmount(){
        $userId = $this->getEditObjectId();
        $oUser = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
        $oUser->load($userId);
        $credit = $oUser->oxuser__ys_giftcert_pool_amount->value;

        $newCredit = Registry::getConfig()->getRequestParameter('creditAmount');

        $diff = $newCredit - $credit;
        $this->addGiftcertLog($diff);

        $oUser->oxuser__ys_giftcert_pool_amount = new Field($newCredit);
        $oUser->save();
    }

    public function addGiftcertLog($value){
        $userId = $this->getEditObjectId();
        // add log entry for purchase
        $giftcertLog = oxNew(\YSquare\GiftCert\Model\GiftCertLog::class);
        $giftcertLog->ysgiftcertlog__ysamountused = new Field($value);
        $giftcertLog->ysgiftcertlog__ysuserid = new Field($userId);
        $giftcertLog->ysgiftcertlog__ysdateused = new Field(date("Y-m-d H:i:s", Registry::getUtilsDate()->getTime()));
        $giftcertLog->save();
    }
}