<?php

namespace idoit\Module\Pro\Model;

use idoit\Model\Dao\Base;
use isys_application;
use isys_component;
use isys_component_dao_result;
use isys_exception_database;
use isys_exception_dao;
use isys_helper_upload;
use isys_module_pro;

/**
 * Class Translation
 *
 * @package   idoit\Module\System\Model
 * @copyright synetics GmbH
 * @license   http://www.i-doit.com/license
 */
class Translation extends isys_component
{
    /**
     * @param string $abbreviation
     *
     * @return array
     */
    public function getCustomTranslations(string $abbreviation): array
    {
        global $g_langcache;

        $customTranslations = [];

        // Backup cached translations.
        $cachedLanguage = $g_langcache;

        $file = BASE_DIR . 'src/lang/' . $abbreviation . '_custom.inc.php';

        if (file_exists($file)) {
            include $file;

            $customTranslations = $g_langcache;
        }

        // Write cached translations back.
        $g_langcache = $cachedLanguage;

        return $customTranslations;
    }

    /**
     * @param string $abbreviation
     * @param array  $translations
     *
     * @return void
     * @throws \Exception
     */
    public function saveCustomTranslations(string $abbreviation, array $translations, bool $merge = true)
    {
        $file = BASE_DIR . 'src/lang/' . $abbreviation . '_custom.inc.php';

        if ($merge) {
            $translations = array_merge($this->getCustomTranslations($abbreviation), $translations);
        }

        $fileContent = isys_application::instance()->container->get('template')
            ->assign('translations', $translations)
            ->assign('date', date('Y.m.d'))
            ->fetch(isys_module_pro::getPath() . 'templates/SettingPage/CustomTranslation/language-template.tpl');

        isys_file_put_contents($file, $fileContent);
    }
}
