<?php

use Query\Operator;

require_once 'languageCheck.php';

$main_class = 'languageCheckAdmin';

class languageCheckAdmin extends LanguageCheck
{
    use DatabaseCommunication;

    protected $template = 'window/languageCheckAdmin.tpl';

    public function get_vars()
    {
        $data = Frame::get_vars();
        $results = [];
        $language = $this->getActualLanguage();
        $selection = $this->getActualSelection();
        $file = $this->selectType($selection);
        if ($selection === self::FORMAT_PO) {
            $data['po_file'] = $file['po_file'];
            $po_sql = $this->getFrontendTranslations($selection, $language);
            foreach ($file['merged_lang'] as $translation) {
                $status = 'OK';
                $podstatus = '';
                if ($translation['original'] == '') {
                    $status = 'ERROR';
                } else {
                    $engine_translation = $file['engine_lang'][$translation['original']]['translation'] ?? '';
                    $shop_translation = $file['shop_lang'][$translation['original']]['translation'] ?? '';
                    if ($translation['translation'] == $translation['original']) {
                        $status = 'WARNING';
                    }
                    if ($translation['translation'] == '') {
                        if (empty($engine_translation)) {
                            $status = 'ERROR';
                        } else {
                            $translation['translation'] = $engine_translation;
                        }
                    }
                    if (!empty($shop_translation)) {
                        $podstatus = 'SHOP';
                    }
                }

                $plural = $translation['plural'];
                $plurals = [];
                foreach ($translation['pluralTranslations'] as $id => $pluralTranslation) {
                    $plurals[$id] = [
                        'original' => $plural,
                        'translation' => $pluralTranslation,
                        'sql' => $po_sql[$plural.'_plural'.$id] ?? null,
                    ];
                }

                $results[$translation['original']] = [
                    'original' => $translation['original'],
                    'translation' => $translation['translation'],
                    'sql' => $po_sql[$translation['original']] ?? null,
                    'plural' => $plural,
                    'pluralTranslations' => $plurals,
                    'references' => $translation['references'],
                    'status' => $status,
                    'podstatus' => $podstatus,
                ];
            }
        } else {
            // PHP

            $mergedMain = $file['main_lang']['merged'];
            $mergedForeign = $file['foreign_lang']['merged'];
            $mergedForeignShop = $file['foreign_lang']['shop'];

            $this->recursiveTranslationsFetch($mergedMain, $mergedForeign, $mergedForeignShop, $results);

            $diff = array_diff_key($file['foreign_lang']['merged'], $file['main_lang']['merged']);
            if (!empty($diff)) {
                // v cizim jazyce jsou sekce prekladu navic
                $results += $this->mainLangSectionNotFound('{NENALEZENO}', $diff);
            }
        }

        uksort($results, 'strcasecmp');
        foreach ($results as &$rs) {
            uksort($rs, 'strcasecmp');
        }
        $data['results'] = $results;

        return $data;
    }

    protected function recursiveTranslationsFetch($translationsMain, $translationsForeign, $translationsForeignShop, &$results, $path = [])
    {
        foreach ($translationsMain as $section => $value) {
            $currentPath = $path;
            $currentPath[] = $section;

            $foreignTranslation = $this->findPathInArray($currentPath, $translationsForeign);

            if (!$foreignTranslation) {
                $pathString = implode('/', $currentPath);
                if (is_array($value)) {
                    $results += $this->sectionNotFound($pathString, $value);
                } else {
                    $results += $this->translationNotFound($pathString, $value);
                }
            } else {
                if (is_array($value)) {
                    $this->recursiveTranslationsFetch($value, $translationsForeign, $translationsForeignShop, $results, $currentPath);
                } else {
                    $status = '';
                    $podstatus = '';
                    if ($value != $foreignTranslation) {
                        if ($value == '' || $foreignTranslation == '') {
                            $status = 'ERROR';
                        } else {
                            $status = 'OK';
                        }
                    } else {
                        $status = 'WARNING';
                    }

                    if ($this->findPathInArray($currentPath, $translationsForeignShop)) {
                        $podstatus = 'SHOP';
                    }
                    $pathString = implode('/', $currentPath);
                    $sql = $this->translationFrontendExists($pathString, $this->getActualLanguage(), 'PHP');
                    $results[$pathString] = [
                        'cesta' => $pathString,
                        'original' => $value,
                        'translation' => $foreignTranslation,
                        'status' => $status,
                        'podstatus' => $podstatus,
                        'sql' => $sql,
                    ];
                }
            }
        }
    }

    protected function handleSend()
    {
        $data_array = getVal('translation');
        $save_array = [];

        $idLanguage = $this->getActualLanguage();
        $type = strtoupper($this->getActualSelection());

        foreach ($data_array as $original => $data) {
            $exists = $this->translationFrontendExists($original, $idLanguage);
            $checkbox = (int) ($data['checkbox'] ?? 0);

            if (
                (!$exists && (!empty($data['translation']) || $checkbox))
                || ($exists && $checkbox)
            ) {
                $this->translationsInsertOnDuplicateUpdate($idLanguage, $type, $original, $data['translation']);

                if (!empty($data['plural'])) {
                    $this->savePlurals($data);
                }
                $save = $data['save'] ?? '0';
                if ($save === '1') {
                    $save_array[] = $data;
                }
            } else {
                $this->deleteSQL('translations_frontend', ['id_language' => $idLanguage, 'type' => $type, 'original' => $original]);
                if (!empty($data['plural'])) {
                    $qb = sqlQueryBuilder()->delete('translations_frontend')
                        ->where(Operator::equals(['id_language' => $idLanguage, 'type' => $type]))
                        ->andWhere(Operator::like(['original' => $data['plural'].'_plural%']));
                    $qb->execute();
                }
            }
        }

        $this->saveToFile($save_array);

        $this->returnOK('Překlady byly úspěšně odeslány.');
    }

    private function saveToFile($data)
    {
        if (empty($data)) {
            return;
        }

        $engine_translations = null;
        $language = $this->getActualLanguage();
        $file = $this->getActualPOFile($this->pathFinder->shopPath('lang/'), $language);
        if (!$file) {
            $file = $this->getActualPOFile($this->pathFinder->enginePath('web/lang/'), $language);
            $engine_translations = \Gettext\Translations::fromPoFile($file);
        }
        if ($file) {
            /** @var \Gettext\Translations $shop_translations */
            $shop_translations = \Gettext\Translations::fromPoFile($file);
            foreach ($data as $new_translation) {
                $plurals = $new_translation['plurals'] ?? null;
                /** @var \Gettext\Translation $translation */
                $translation = $shop_translations->find(null, $new_translation['original']);
                if ($translation) {
                    $translation->setTranslation($new_translation['translation']);
                    if ($translation->getPlural() && $plurals) {
                        $plurals_translations = $translation->getPluralTranslations();
                        $plurals_translations = array_replace($plurals_translations, $plurals);
                        $translation->setPluralTranslations($plurals_translations);
                    }
                } else {
                    if (!$engine_translations) {
                        $engine_file = $this->getActualPOFile($this->pathFinder->enginePath('web/lang/'), $language);
                        $engine_translations = \Gettext\Translations::fromPoFile($engine_file);
                    }
                    $translation = $engine_translations->find(null, $new_translation['original']);
                    if ($translation) {
                        $new = $translation->getClone();
                        $new->setTranslation($new_translation['translation']);
                        if ($new->getPlural() && $plurals) {
                            $plurals_translations = $new->getPluralTranslations();
                            $plurals_translations = array_replace($plurals_translations, $plurals);
                            $new->setPluralTranslations($plurals_translations);
                        }
                        $shop_translations->append($new);
                    }
                }
            }
            Gettext\Generators\Po::toFile($shop_translations, $file);
        }
    }
}
