<?php

use KupShop\I18nBundle\Util\TranslationUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

#[AllowDynamicProperties]
class Frame extends Base
{
    protected $ID;
    protected $errors = [];
    protected $htmlErrors = [];

    public function get_vars()
    {
        $vars = parent::get_vars();

        $ErrStr = getVal('ErrStr');
        if (!empty($ErrStr)) {
            $this->errors[] = $ErrStr;
        }

        $vars['ErrStr'] = join(',', $this->getErrors());

        if ($vars['ErrStr'] && $vars['ErrStr'] != translate('saved', 'status')) {
            header('admin-error: '.urlencode(mb_strcut($vars['ErrStr'], 0, 1024)));
        }

        if (!empty($this->getHTMLErrors())) {
            $error = '';
            foreach ($this->getHTMLErrors() as $HTMLError) {
                $error .= '<p>'.$HTMLError.'</p>';
            }
            header('admin-html-error: '.urlencode(mb_strcut($error, 0, 1024)));
        }

        $OkStr = getVal('OkStr');
        if (!empty($OkStr)) {
            $vars['OkStr'] = $OkStr;
        }

        if (!empty($this->getHTMLErrors())) {
            $vars['htmlErrors'] = $this->getHTMLErrors();
        }

        $header = getVal('header', $vars, []);

        $header['date'] = date('Ymd');

        if (getVal('hdrType') != null) {
            $header['hdrType'] = getVal('hdrType');
        }

        $header['refresh'] = getVal('refresh');

        $vars['header'] = $header;

        return $vars;
    }

    public function tryRights($acn = '')
    {
        // Musim mit budto prava na pozadovanou akci, nebo READ prava
        if (!UserRights::hasRights($this->getRightsType(), $acn) && !UserRights::hasRights($this->getRightsType(), 'READ')) {
            throw new AccessDeniedException('');
        }
    }

    protected function getRightsType()
    {
        $type = getVal('s');
        if (!$type || $type == 'list.php') {
            $type = getVal('type');

            if (!$type) {
                $type = lcfirst($this->getClassName());
            }
        } else {
            $type = substr($type, 0, -4);
        }

        return $type;
    }

    protected function getAction()
    {
        if (empty($this->action)) {
            $acn = getVal('acn');
            if (empty($acn)) {
                $acn = 'add';
            }
            $this->action = $acn;
        }

        return $this->action;
    }

    protected function getID()
    {
        if (empty($this->ID)) {
            $ID = getVal('ID');
            /*if(empty($ID))
             logError(__FILE__, __LINE__, "Empty ID");*/
            $this->setID($ID);
        }

        return $this->ID;
    }

    public function setID($id)
    {
        $this->ID = $id;
    }

    public function getName()
    {
        return substr(getVal('s'), 0, -4);
    }

    public function returnError($ErrStr, $parentRefresh = '', $ID = null)
    {
        if (empty($ID)) {
            $ID = $this->getID();
        }
        if ($parentRefresh) {
            if ($refresh = getVal('refresh')) {
                $parentRefresh = "&refresh={$refresh}";
            } else {
                $parentRefresh = '&refresh=parent';
            }
        }
        if (getVal('autoclose')) {
            $parentRefresh .= '&refresh=close';
        }
        $type = getVal('type');
        if ($type) {
            $parentRefresh .= '&type='.$type;
        }
        redirect("launch.php?s={$this->getName()}.php&acn=edit{$parentRefresh}&flap=".getVal('flap')."&ID={$ID}&ErrStr=".urlencode($ErrStr));
    }

    public function addError($ErrStr = null)
    {
        $this->errors[] = $ErrStr;
    }

    public function addHTMLError($error)
    {
        $this->htmlErrors[] = $error;
    }

    public function getHTMLErrors()
    {
        return array_unique($this->htmlErrors);
    }

    public function getErrors()
    {
        return array_unique($this->errors);
    }

    public function returnOK($ErrStr = null, $parentRefresh = false, $params = [])
    {
        if (empty($ErrStr)) {
            $this->returnError($GLOBALS['txt_str']['status']['saved'], true);
        }

        if ($parentRefresh) {
            $params['refresh'] = 'parent';
        }

        if (getVal('type')) {
            $params['type'] = getVal('type');
        }

        if (getVal('flap')) {
            $params['flap'] = getVal('flap');
        }

        $params['OkStr'] = $ErrStr;

        if (empty($params['acn'])) {
            $params['acn'] = 'edit';
        }

        return $this->redirect($params);
    }

    public function redirect($params = [])
    {
        $params = array_merge($_GET, $params);

        return redirect('launch.php?'.http_build_query($params));
    }

    public function unserializeCustomData(&$data)
    {
        if (!isset($data['data'])) {
            $data['data'] = [];

            return;
        }

        if (is_string($data['data'])) {
            $data['data'] = json_decode($data['data'], true);
        }

        if (!is_array($data['data']) && !is_object($data['data'])) {
            $data['data'] = [];
        }
    }

    public function serializeCustomData(&$data)
    {
        if (empty($data['data'])) {
            $data['data'] = null;
        } else {
            $data['data'] = json_encode($data['data']);
        }
    }

    protected function isDuplicate()
    {
        return getVal('Duplicate');
    }

    protected function getTranslationUtil(): ?TranslationUtil
    {
        if (!findModule(\Modules::TRANSLATIONS)) {
            return null;
        }
        static $translationUtil;

        if (!$translationUtil) {
            $translationUtil = ServiceContainer::getService(TranslationUtil::class);
        }

        return $translationUtil;
    }
}
