<?php
error_reporting(E_ERROR | E_PARSE);
if (!class_exists('POfile')) require_once("common_cadline_libraries/POfile.php");
if (!class_exists('Database')) require_once("common_cadline_libraries/crm_database.class.php");

$dir    = $_SERVER['DOCUMENT_ROOT'] . '/public/pofiles';
$files  = array_diff(scandir($dir), array('.', '..'));

if (count($files) >= 10)
    $time = '-5 minutes';
else
    $time = '-1 days';

foreach ($files as $file) {
    if (filemtime($dir . '/' . $file) <= strtotime($time)) {
        if (file_exists($dir . '/' . $file))
            unlink($dir . '/' . $file);
    }
}

$locale = array();
$guid   = isset($_GET['packageID']) ? $_GET['packageID'] : time();
$lang   = isset($_GET['lang']) ? strtolower($_GET['lang']) : 'eng';
$seID   = isset($_GET['se']) ? $_GET['se'] : 0;
$region = isset($_GET['region']) ? strtoupper($_GET['region']) : 'INT';
$types  = array(
    'resource'              => '1, 2, 3, 4',
    'Translat'              => '10',
    'Translat_Int'          => '9',
    'Translat_Coll'         => '11',
    'Translat_Mat'          => '12',
    'Translat_Set'          => '13',
    'Translat_Tooltip'      => '14',
    'TranslateEnergetics'   => '15',
    'TranslatePG'           => '16'
);

$tables = array(
    'eng'   => 'resourcemanager.text_table_ref',
    'hun'   => 'resourcemanager.text_table_hun',
    'ita'   => 'resourcemanager.text_table_ita',
    'de-de' => 'resourcemanager.text_table_ger',
    'pol'   => 'resourcemanager.text_table_pol',
    'kor'   => 'resourcemanager.text_table_kor',
    'esp'   => 'resourcemanager.text_table_esp',
    'gre'   => 'resourcemanager.text_table_gre',
    'cz'    => 'resourcemanager.text_table_cz',
    'cr'    => 'resourcemanager.text_table_cr',
    'chn'   => 'resourcemanager.text_table_chn',
    'nor'   => 'resourcemanager.text_table_nor',
    'fr'    => 'resourcemanager.text_table_fr',
    'pt-pt' => 'resourcemanager.text_table_pt',
    'us'    => 'resourcemanager.text_table_ref',
    'aus'   => 'resourcemanager.text_table_ref',
    'pt-br' => 'resourcemanager.text_table_pt',
    'de-at' => 'resourcemanager.text_table_ger',
    'zh-cn' => 'resourcemanager.text_table_zh_cn', // Chinese (simplified)
    'bg'    => 'resourcemanager.text_table_bg'
);

$zip    = new ZipArchive();
$name   = '/' . $guid . '.zip';
$path   = $dir . $name;

if ($zip->open($path, ZipArchive::CREATE) !== TRUE)
    exit("cannot open <$path>\n");

$year           = '';
$progVersion    = '';
$yearID         = '';

if (isset($_GET['ver'])) {
    if ($_GET['ver'] >= '2024') {
        $query = 'SELECT year FROM cl_hlusers.p_versions p
            WHERE p.year = ?';
    } else {
        $query = 'SELECT year FROM cl_hlusers.p_versions p
            WHERE p.verPassword8and9 = ?';
    }

    Database::getInstance()->query($query, array('i', $_GET['ver']));
    $version = Database::getInstance()->fetchNext();

    $year = $version['year'];

    $query = 'SELECT id FROM resourcemanager.year y WHERE y.name = ' . $year;
    Database::getInstance()->query($query, array('i', $year));
    $year = Database::getInstance()->fetchNext();

    $yearID = $year['id'];

    $yearName = $version['year'];
} else {
    $query = 'SELECT id FROM resourcemanager.year ORDER BY id DESC';
    Database::getInstance()->query($query);
    $year = Database::getInstance()->fetchNext();

    $yearID = $year['id'];
    $yearName = $year['name'];
}

$query = 'SELECT ref.text AS langText, ref.text AS refText, ref.key AS refKey
            FROM resourcemanager.text_table_ref ref
            WHERE ref.type_id = 17 AND ref.key LIKE ?;';
Database::getInstance()->query($query, array('s', '%_' . $region));
$checkRegion = Database::getInstance()->fetchAssoc();

if (empty($checkRegion)) {
    $region = 'INT';
}

$companyName    = '';
$regionResult   = array();
$delimiter = '#';
$startTag = '$(';
$endTag = ')';
$regex = $delimiter . preg_quote($startTag, $delimiter)
    . '(.*?)'
    . preg_quote($endTag, $delimiter)
    . $delimiter
    . 's';

if ($lang != 'all') {
    $table = $tables[$lang];

    if ($lang == 'eng') {
        $query = 'SELECT ref.text AS langText, ref.text AS refText, ref.key AS refKey
            FROM resourcemanager.text_table_ref ref
            WHERE ref.type_id = 17 AND ref.key LIKE ?;';
    } else {
        $query = 'SELECT res.text AS langText, ref.text AS refText, ref.key AS refKey
            FROM resourcemanager.text_table_ref ref
            LEFT JOIN ' . $table . ' res ON res.ref_id = ref.id
            WHERE ref.type_id = 17 AND ref.key LIKE ?;';
    }
    Database::getInstance()->query($query, array('s', '%_' . $region));
    $regionResult = Database::getInstance()->fetchAssoc();
}

foreach ($types as $type_key => $type_value) {
    foreach ($tables as $table_key => $table_value) {
        if ($lang != 'all' && $table_key != $lang)
            continue;

        $poFile = new POfile();

        if ($lang == 'all') {
            if ($table_value == 'resourcemanager.text_table_ref') {
                $query = 'SELECT ref.text AS langText, ref.text AS refText, ref.key AS refKey
                    FROM resourcemanager.text_table_ref ref
                    WHERE ref.type_id = 17 AND ref.key LIKE ?;';
            } else {
                $query = 'SELECT res.text AS langText, ref.text AS refText, ref.key AS refKey
                    FROM resourcemanager.text_table_ref ref
                    LEFT JOIN ' . $table_value . ' res ON res.ref_id = ref.id
                    WHERE ref.type_id = 17 AND ref.key LIKE ?;';
            }
            Database::getInstance()->query($query, array('s', '%_' . $region));
            $regionResult = Database::getInstance()->fetchAssoc();
        }

        if ($table_value == 'resourcemanager.text_table_ref') {
            $query = 'SELECT ref.key AS key_id, ref.type_id AS type_id, ref.text AS lang_text
                FROM resourcemanager.text_table_ref ref
                WHERE ref.type_id IN (' . $type_value . ')';

            $query .= ' AND (ref.from = ' . $yearID . ' OR ((ref.to is null OR ref.to = 0) AND ref.from < ' . $yearID . '))';

            $progName = 'ARCHLine.XP';
        } else {
            $table = $tables[$lang];
            $query = 'SELECT res.text AS langText, ref.text AS refText, ref.key AS refKey
            FROM resourcemanager.text_table_ref ref
            LEFT JOIN ' . $table_value . ' res ON res.ref_id = ref.id
            WHERE ref.type_id = 17 AND ref.key = ? LIMIT 1;';
            Database::getInstance()->query($query, array('s', 'PRODUCT_NAME_' . $region));
            $prgResult = Database::getInstance()->fetchNext();

            $progName = $prgResult['langText'];

            if (strpos($table_key, '-') !== false || $table_key == 'at') {
                $query = 'SELECT * FROM resourcemanager.locale WHERE code = "' . $table_key . '"';
                Database::getInstance()->query($query);
                $locale = Database::getInstance()->fetchNext();
            } else {
                $locale = array();
            }

            if (empty($locale)) {
                $query = 'SELECT ref.key AS key_id, ref.type_id AS type_id, ref.text AS ref_text, res.text AS lang_text, ref.define_txt AS defines
                    FROM resourcemanager.text_table_ref ref
                    LEFT JOIN ' . $table_value . ' res ON ref.id = res.ref_id
                    WHERE ref.type_id IN (' . $type_value . ')';
            } else {
                $query = 'SELECT ref.key AS key_id, ref.type_id AS type_id, ref.text AS ref_text, res.text AS lang_text, ref.define_txt AS defines
                    FROM (
                        SELECT id, ref_id, text, locale, approved, changed, to_translate
                        FROM ' . $table_value . ',
                        (SELECT @row_number := 0) AS row_table
                        ORDER BY locale DESC
                    ) AS res
                    LEFT JOIN resourcemanager.text_table_ref ref ON ref.id = res.ref_id
                    WHERE (res.locale = ' . $locale['id'] . ' OR res.locale is null OR res.locale = 0) AND ref.type_id IN (' . $type_value . ') ';
            }

            $query .= ' AND (ref.from = ' . $yearID . ' OR ((ref.to is null OR ref.to = 0) AND ref.from < ' . $yearID . '))';

            $query .= ' GROUP BY res.ref_id';
        }

        if ($type_key == 'resource')
            $query .= ' ORDER BY ref.type_id ASC, cast(ref.key AS UNSIGNED) ASC';
        else
            $query .= ' ORDER BY ref.type_id ASC, ref.key ASC';

        Database::getInstance()->query($query);
        $resources = Database::getInstance()->fetchAssoc();

        if ($seID == 0) {
            $progVersion = $progName . ' ' . $yearName;
        } else {
            $query = 'SELECT ref.text AS txt 
                FROM resourcemanager.text_table_ref ref
                WHERE ref.type_id = 1 AND ref.key = ?';
            Database::getInstance()->query($query, array('s', $seID));
            $prgName = Database::getInstance()->fetchNext();

            $progVersion = $progName . ' ' . $prgName['txt'] . ' ' . $yearName;
        }

        if (!empty($resources)) {
            foreach ($resources as $res) {
                $alternatives = array();

                if ($res['defines'] != '') {
                    $defines = json_decode($res['defines']);

                    $alternatives = array_filter($defines->defines, function ($define) use ($table_key) {
                        return $define->lang == $table_key;
                    });
                }

                if ($table_value != 'resourcemanager.text_table_ref' && ($res['lang_text'] == '' || $res['lang_text'] == null)) {
                    $res['lang_text'] = $res['ref_text'];
                }

                $preg = preg_match($regex, $res['lang_text'], $matches);
                if (strpos($res['lang_text'], '$(PROGRAM_VERSION)') == false && $preg && !empty($regionResult)) {
                    $found = false;

                    foreach ($regionResult as $result) {
                        if ($found) {
                            continue;
                        }

                        if ($result['refKey'] == $matches[1] . '_' . $region) {
                            $found = true;
                            $companyName = $result['langText'] != '' ? $result['langText'] : $result['refText'];
                            $res['lang_text'] = str_replace($matches[0], $companyName, $res['lang_text']);
                        }
                    }

                    // TODO: Regex, amely nezi, hogy $() kozott van-e nagybetus es alahuzas string. pl.: $(COMPANY_NAME)
                    // Ha nem talal valtozot a stringhez, akkor !VARIABLE NOT FOUND: $(COMPANY_NAME_INT)!-ra cserelje ki
                }

                if (strpos($res['lang_text'], '$(PROGRAM_VERSION)') !== false) {
                    $res['lang_text'] = str_replace('$(PROGRAM_VERSION)', $progVersion, $res['lang_text']);
                }

                if ($type_value >= 9 || ($type_value < 9 && empty($alternatives))) {
                    $msgID  = $res['key_id'];
                    $msgStr = nl2br($res['lang_text']);

                    $poFile->addComment('Key', $res['type_id'] . ':' . $res['key_id']);
                    $poFile->addMsgctxt($res['type_id'] . ':' . $res['key_id']);
                    $poFile->addMsgID($msgID);
                    $poFile->addMsgSTR($msgStr);
                }

                if (!empty($alternatives)) {
                    foreach ($alternatives as $alternative) {
                        $msgID  = $res['key_id'] . '' . $alternative->ext_key;
                        $msgStr = nl2br($alternative->text);

                        $poFile->addComment('Key', $res['type_id'] . ':' . $res['key_id'] . '' . $alternative->ext_key);
                        $poFile->addMsgctxt($res['type_id'] . ':' . $res['key_id'] . '' . $alternative->ext_key);
                        $poFile->addMsgID($msgID);
                        $poFile->addMsgSTR($msgStr);
                    }
                }
            }

            $file_lang = $table_key;

            $zip->addFromString($type_key . '.' . $file_lang . '.po', $poFile->getStream());
        }
    }
}

$zip->close();

echo 'https://www.archline.hu/public/pofiles/' . $guid . '.zip';
