<?php

namespace KupShop\I18nBundle\Admin;

use KupShop\AdminBundle\Util\ActivityLog;
use KupShop\I18nBundle\Translations\SettingsTranslation;
use KupShop\I18nBundle\Util\TranslationLocator;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class languagesSettings extends \Window
{
    private $settingsTranslations;

    private TranslationLocator $translationLocator;

    public function __construct()
    {
        $this->settingsTranslations = ServiceContainer::getService(SettingsTranslation::class);
        $this->translationLocator = ServiceContainer::getService(TranslationLocator::class);
    }

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

        $acn = $this->getAction();
        $this->settingsTranslations->setLanguageId($this->getID());

        $pageVars = [
            'acn' => $acn,
            'data' => $this->settingsTranslations->get(true),
        ];

        $pageVars['data']['id'] = $this->getID();

        $vars['type'] = $this->getType();
        $vars['body'] = $pageVars;
        $vars['body']['language'] = $this->getLanguageName();

        $vars['body']['configurableTranslations'] = [];
        // Konfigurovatelne preklady - moznost u nich zaskrtnout, ze se maji skryvat neprelozene objekty
        foreach ($this->translationLocator->getTranslations() as $class) {
            try {
                $translation = $this->translationLocator->getTranslation($class);
            } catch (\Throwable $e) {
                continue;
            }

            if ($translation->supportsHideNotTranslated) {
                $vars['body']['configurableTranslations'][$translation->getTableName()] = $pageVars['data']['hide_not_translated_objects'][$translation->getTableName()] ?? 'N';
            }
        }

        return $vars;
    }

    public function fetchObject($table, $ID)
    {
        return null;
    }

    public function getObject()
    {
        return null;
    }

    public function handle()
    {
        $this->checkTranslatable();

        $language = $this->getID();
        $data = $this->getData();
        $submit = getVal('Submit');
        if (!empty($data) && !empty($submit)) {
            $settings = \Settings::createFromDB($language, true);

            array_walk_recursive($data, function (&$value) {
                $value = trim($value);
            });

            $activityLog = ServiceContainer::getService(ActivityLog::class);
            $activityLog->addDifferencialActivityLog(ActivityLog::SEVERITY_NOTICE,
                ActivityLog::TYPE_CHANGE,
                "Upraveno nastavení pro jazykovou mutaci: {$language}.",
                (array) $settings,
                $data);
        }

        parent::handle();
    }

    public function handleUpdate()
    {
        $data = $this->getData();
        $empty = getVal('empty', null, []);

        // recursively remove nested empty elements
        $arrayFilterRecursive = function (&$array, bool $nested = false, $empty = []) use (&$arrayFilterRecursive) {
            foreach ($array as $key => $item) {
                if (!is_array($item)) {
                    $array[$key] = (array_key_exists($key, $empty) ? null : trim($array[$key]));
                }

                is_array($item) && $array[$key] = $arrayFilterRecursive($item, true, $empty[$key] ?? []);
                if ($nested && ($array[$key] === '' || $array[$key] === [])) {
                    unset($array[$key]);
                }
            }

            return $array;
        };
        $arrayFilterRecursive($data, false, $empty);

        $result = $this->settingsTranslations->setLanguageId($this->getID())->save($data);

        $this->handleTabs(true);

        return $result;
    }

    public function getLanguageName()
    {
        $language = $this->selectSQL('languages', ['id' => $this->getID()])->fetch();

        return $language['name'];
    }

    public function checkTranslatable()
    {
        $languageContext = ServiceContainer::getService(LanguageContext::class);
        $check = $this->selectSQL('languages', ['id' => $this->getID()])->fetch();
        if (!$check || ($check['id'] == $languageContext->getDefaultId())) {
            throw new \Exception('This language is not translatable');
        }

        return true;
    }

    public function hasRights($name = null)
    {
        switch ($name) {
            case \Window::RIGHT_DELETE:
            case \Window::RIGHT_DUPLICATE:
                return false;
            default:
                return parent::hasRights($name);
        }
    }
}

return languagesSettings::class;
