<?php

use KupShop\I18nBundle\Util\TranslationLocator;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Compat\SymfonyBridge;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\HttpFoundation\File\UploadedFile;

$main_class = 'ImportTranslations';

class ImportTranslations extends Frame
{
    protected $template = 'window/import_translations.tpl';

    protected $listType;

    /** @var string currently selected source language id */
    protected $sourceLanguage;

    /** @var string currently selected target language id */
    protected $language;

    protected $translation;

    protected $import_results = [];

    public function get_vars()
    {
        $vars = parent::get_vars();
        $vars['ID'] = $this->getID();
        $vars['sourceLanguage'] = getVal('sourceLanguage');
        $vars['language'] = getVal('language');

        $result = sqlQueryBuilder()->select('*')->from('languages')->orderBy('id')->execute()->fetchAll();
        $languageContext = ServiceContainer::getService(LanguageContext::class);
        foreach ($result as $lang) {
            if ($lang['id'] != $languageContext->getDefaultId()) {
                // exclude default language
                if (findRight('TRANSLATE_'.$lang['id'])) {
                    $this->languages[$lang['id']] = mb_strtoupper($lang['id']).' - '.$lang['name'];
                }
            } else {
                $this->sourceLanguages[$lang['id']] = mb_strtoupper($lang['id']).' - '.$lang['name'];
            }
        }
        $vars['sourceLanguages'] = $this->sourceLanguages;
        $vars['languages'] = $this->languages;

        $vars['import_results'] = $this->import_results;

        return $vars;
    }

    protected function validateFigure($value): ?string
    {
        // Platné hodnoty ENUM - kvuli ukladani do db
        $validValues = ['Y', 'N', 'O', null];
        if (in_array($value, $validValues, true)) {
            return $value;
        }

        // Pokud hodnota není platná, vrátím null
        return null;
    }

    public function handle()
    {
        if (getVal('Submit')) {
            $file_path = $this->getFile();
            if (!$file_path) {
                return false;
            }

            $transformation = new AutomaticImportTransform($file_path);
            try {
                $data = $transformation->LoadBinfileAsArray();
            } catch (Error $e) {
                $this->error .= 'Soubor s překlady nelze načíst. Zkontrolujte že je ve formátu XLS či XLSX.';

                $this->returnError($this->error);
            }

            $this->language = getVal('language');
            $this->sourceLanguage = getVal('sourceLanguage');
            $translationLocator = ServiceContainer::getService(TranslationLocator::class);
            $translations = $translationLocator->getTranslations();
            foreach ($data as $listType => $listData) {
                $count = 0;
                $this->import_results[$listType] = ['success' => true, 'message' => 'Import proběhl úspěšně, počet importovaných: '];

                $className = str_replace('translate', '', $listType).'Translation';
                try {
                    $className = $translations[$className];
                    if (!$className) {
                        throw new ServiceNotFoundException('NULL');
                    }
                    $this->translation = ServiceContainer::getService($className);
                } catch (ServiceNotFoundException $notFoundException) {
                    $this->import_results[$listType] = ['success' => false, 'message' => "Nejde importovat list '{$listType}'. Je třeba zachovat názvy listů. "];
                    continue;
                }
                $columns = array_values(array_shift($listData));
                $translation_columns = $this->translation->getColumns();
                foreach ($listData as $item) {
                    $item = array_combine($columns, $item);
                    $id = $item['id'];
                    $send_item = null;
                    if ($id) {
                        foreach ($translation_columns as $key => $column) {
                            if (array_key_exists($this->language.'_'.$key, $item) && !empty($item[$this->language.'_'.$key])) {
                                $send_item[$key] = $item[$this->language.'_'.$key];
                                // check na figure hodnoty kvuli enum hodnotam a naslednemu ukladani do db
                                if ($key === 'figure') {
                                    $send_item[$key] = $this->validateFigure($send_item[$key]);
                                }
                            }
                        }
                    }
                    if ($send_item) {
                        try {
                            if ($this->translation->saveSingleObject($this->language, $id, $send_item, $this->sourceLanguage, false)) {
                                $count++;
                            }
                        } catch (Exception $e) {
                            $message = $e->getMessage();
                            if (strlen($message) > 300) {
                                $message = substr($message, 0, 300).'... ';
                            }
                            $this->import_results[$listType]['items'][] = ['success' => false, 'message' => 'ID: '.$id.', Error! '.$message.'; '];
                        }
                    }
                }

                $this->import_results[$listType]['message'] .= $count;
                writeDownActivity("Import překladů: {$this->language} - {$listType} - ".$this->import_results[$listType]['message']);
                $this->translation->clearCache($this->language);
            }
        }
    }

    public function getFile()
    {
        $request = SymfonyBridge::getCurrentRequest();

        /** @var $file UploadedFile */
        $file = $request->files->get('file');
        if (!$file) {
            return '';
        }

        return $file->getRealPath();
    }
}
