<?php

namespace YSquare\Shipcloud\Application\Controller\Admin;

use Exception;
use OxidEsales\Eshop\Application\Controller\Admin\AdminDetailsController;
use OxidEsales\Eshop\Application\Model\CountryList;
use OxidEsales\Eshop\Core\Registry;

/**
 * Admin article main user manager.
 * Performs collection and updatind (on user submit) main item information.
 * Admin Menu: User Administration -> Users -> Main.
 */
class ShipcloudAddressForm extends AdminDetailsController
{
    private $sSaveError = null;

    public function render()
    {
        parent::render();

        $soxId = $this->_aViewData["oxid"] = $this->getEditObjectId();
        if (isset($soxId) && $soxId != "-1") {
            // load object
            $oShipcloudAddress = oxNew(\YSquare\Shipcloud\Application\Model\ShipcloudAddress::class);
            $oShipcloudAddress->load($soxId);
            $this->_aViewData["edit"] = $oShipcloudAddress;
        }

        // passing country list

        $oLang = Registry::getLang();
        $iTplLang = $oLang->getTplLanguage();
        $oCountryList = oxNew(CountryList::class);
        $oCountryList->loadActiveCountries($oLang->getObjectTplLanguage());

        $this->_aViewData["countrylist"] = $oCountryList;

        if ($this->sSaveError) {
            $this->_aViewData["sSaveError"] = $this->sSaveError;
        }

        return "shipcloud_address_form.tpl";
    }

    /**
     * Saves main user parameters.
     */
    public function save()
    {
        parent::save();

        //allow admin information edit only for MALL admins
        $soxId = $this->getEditObjectId();
        if ($this->_allowAdminEdit($soxId)) {
            $aParams = Registry::getRequest()->getRequestEscapedParameter("editval");

            $oShipcloudAddress = oxNew(\YSquare\Shipcloud\Application\Model\ShipcloudAddress::class);
            if ($soxId != "-1") {
                $oShipcloudAddress->load($soxId);
            } else {
                $aParams['ysshipcloudaddress__oxid'] = null;
            }

            $oShipcloudAddress->assign($aParams);

            try {
                $oShipcloudAddress->save();

                // set oxid if inserted
                $this->setEditObjectId($oShipcloudAddress->getId());
            } catch (Exception $oExcp) {
                $this->sSaveError = $oExcp->getMessage();
            }
        }
    }
}
