<?php

$lang=(isset($_GET['lang']) && gettype ($_GET['lang']) == "string") ? $_GET['lang']:"";
$langs = getlng();
if(!$lang) {
    $langcode = (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
    $langcode = (!empty($langcode)) ? explode(",", $langcode) : $langcode;
    $lngs = Array();
    if(is_array($langcode)) {
        foreach ($langcode as $lng) {
            $lng = (!empty($lng)) ? explode(";", $lng) : $lng;
            $lng = (!empty($lng[0])) ? explode("-", $lng['0']) : $lng;
            $lng = (!empty($lng[0])) ? $lng['0'] : $lng;
            if(!in_array(strtolower($lng), $lngs)) $lngs[]=strtolower($lng);
        }
    } else {
        if(!empty($langcode)) {
            $lng=$langcode;
            $lng = (!empty($lng)) ? explode(";", $lng) : $lng;
            $lng = (!empty($lng[0])) ? explode("-", $lng['0']) : $lng;
            $lng = (!empty($lng[0])) ? $lng['0'] : $lng;
            if(!in_array(strtolower($lng), $lngs)) $lngs[]=strtolower($lng);
        }
    }
    if(!empty($lngs)) {
        if ($langs !== false) {
            for ($i=0; $i<count($lngs) && !$lang; $i++) {
                $lng = $lngs[$i];
                foreach($langs as $name=>$value) {
                    if($name==strtolower($lng)) {
                        $lang=$name;
                        break;
                    }
                }
            }
        }

    }
    if(!$lang) {
        $lang="en";
    }
    unset($langcode);
}

if (isset($_GET['debug'])) {
    $timing[]=Array("Lang_init",microtime(true));
}
include "db.php";
if($db_link) {
    mysqli_select_db($db_link,$db) or die("Database Error");
    $table="lang";
    $query="desc $table";
    $result=mysqli_query($db_link,$query);
    if(!$result) {
        echo "Creating lang table... ";
        $query="create table $table (id int not null auto_increment primary key, lang varchar(32) default '', name varchar(32) default '', description varchar(128) default '', text text) default charset=utf8mb4 collate=utf8mb4_bin";
        mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        echo "<b>Success</b><br>\n";

    }
    $table="lang_preload";
    $query="desc $table";
    $result=mysqli_query($db_link,$query);
    if(!$result) {
        echo "Creating lang_preload table... ";
        $query="create table $table (id int not null auto_increment primary key, name varchar(32) default '', type varchar(32) default '', target varchar(128) default '') default charset=utf8mb4 collate=utf8mb4_bin";
        mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        echo "<b>Success</b><br>\n";

    }
    $table="locales";
    $query="desc $table";
    $result=mysqli_query($db_link,$query);
    if(!$result) {
        echo "Creating locales table... ";
        $query="create table $table (id int not null auto_increment primary key, lang varchar(32) not null default '', def_title varchar(32) not null default '', loc_title varchar(32) not null default '') default charset=utf8mb4 collate=utf8mb4_bin";
        mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        echo "<b>Success</b><br>\n";
    }
    mysqli_close($db_link);
    if (isset($_GET['debug'])) {
        $timing[]=Array("Lang DBSetup",microtime(true));
    }
} else exit("DB Connection Error");

if (chklng($lang) != $lang) {
    $lang_ok=false;
    $lang="en";
}

else $lang_ok=true;

if (isset($_GET['debug'])) {
    $timing[]=Array("Lang Init_Final",microtime(true));
}
function loadTranslations($lang) {
    global $translations, $translations_indb;
    if (isset($translations[$lang]))
        unset($translations["lang"]);
    $translations[$lang] = Array();
    if (isset($translations_indb[$lang]))
        unset($translations_indb["lang"]);
    $translations_indb[$lang] = Array();
    include "db.php";
    if($db_link) {
        mysqli_select_db($db_link,$db) or die(mysqli_error($db_link));
        mysqli_query($db_link,"set names utf8mb4");
        $table="lang";
        $lang=addslashes($lang);
        $query="select name, text from $table where lang='$lang'";
        $result=mysqli_query($db_link,$query);
        if(mysqli_num_rows($result) > 0){
            while($arr=mysqli_fetch_assoc($result)){
                $translations[$lang][$arr['name']] = $arr['text'];
                $translations_indb[$lang][$arr['name']] = true;
            }
        }
        mysqli_close($db_link);
    }
}

function saveTranslations() {
    global $translations, $translations_modified, $translations_indb;
    if (isset($translations_modified) && is_array($translations_modified)) {
        include "db.php";
        if($db_link) {
            mysqli_select_db($db_link,$db) or die(mysqli_error($db_link));
            mysqli_query($db_link,"set names utf8mb4");
            $table="lang";
            $modified = array_keys($translations_modified);
            foreach($modified as $lang) {
                if (is_array($translations_modified[$lang])) {
                    $keys = array_keys($translations_modified[$lang]);
                    foreach($keys as $name) {
                        $value=mysqli_real_escape_string($db_link,$translations_modified[$lang][$name]);
                        if (isset($translations_indb) && isset($translations_indb[$lang]) && isset($translations_indb[$lang][$name])) {
                            $indb=$translations_indb[$lang][$name];
                        } else
                            $indb = false;
                        if($indb) {
                            if (!isset($query_update))
                                $query_update = "update $table set text = (case \n";
                            $query_update.="\twhen name='$name' then '$value'\n";
                            if (isset($query_update_where))
                                $query_update_where .= ", ";
                            else
                                $query_update_where = "where name in (";
                                $query_update_where .= "'$name'";
                        } else {
                            if (!isset($query_insert))
                                $query_insert = "insert into $table (name, text, lang) values\n\t";
                            else
                                $query_insert .= ",\n\t";
                            $query_insert.="('$name','$value','$lang')";
                            //$query="insert into $table (name, text, lang) values ('$name','$value','$lang')";
                            //mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                        }
                    }
                    if (!empty($query_update)) {
                        $query_update.="\tend)\n$query_update_where) and lang='$lang'\n";
                        $ret = mysqli_query($db_link,$query_update) or die(mysqli_error($db_link));
                    }
                    if (!empty($query_insert)) {
                        $ret = mysqli_query($db_link,$query_insert) or die(mysqli_error($db_link));
                    }
                }
            }
            mysqli_close($db_link);
        }
    }
}

loadTranslations($lang);
if ($lang != "en")
    loadTranslations("en");

if (isset($_GET['debug'])) {
    $timing[]=Array("Lang LoadTranslations",microtime(true));
}

function getstr($field, $lang="en", $default="") {
    global $translations, $prefix;
    if (array_key_exists($lang,$translations) && array_key_exists($field,$translations[$lang]) ) {
        $msg = $translations[$lang][$field];
    } elseif (array_key_exists("en",$translations) && array_key_exists($field,$translations["en"])) {
        $msg = preloadstr($field, $lang);
        if ($msg === false) {
            $msg = $translations["en"][$field];
            setstr ($field, $msg, $lang);
        }
    } else {
        $msg = preloadstr($field, "en");
        if ($msg === false) {
            $msg = $default?$default:$field;
            setstr($field, $msg, $lang);
        }
    }
    return $msg;
}

function preloadstr($field, $lang="en") {
    global $translations, $translations_indb, $prefix, $module, $action;
    if(!isset($translations_indb[$lang][$field])) {
        $preload_ok = false;
        include "db.php";
        if ($db_link) {
            mysqli_select_db($db_link,$db) or die(mysqli_error($db_link));
            mysqli_query($db_link,"set names utf8mb4");
            $table="lang";
            $table2 = "lang_preload";
            $query="select name, text from $table where name='".mysqli_real_escape_string($db_link,$field)."' and lang='".mysqli_real_escape_string($db_link,$lang)."'";
            $result=mysqli_query($db_link,$query);
            if(mysqli_num_rows($result) > 0){
                if($arr=mysqli_fetch_assoc($result)){
                    $translations[$lang][$field] = $arr['text'];
                    $translations_indb[$lang][$field] = true;
                    $preload_ok=true;
                    if (!empty($module) && !empty($action)) {
                        switch($action) {
                            case "logout":
                            case "delmodule":
                            case "editmodule":
                                $type = "action";
                                $target=$action;
                            break;
                            default:
                                $type = "module_action";
                                $target=$module."_".$action;
                            break;
                        }
                    } elseif (!empty($module)) {
                        $type = "module";
                        $target=$module;
                    } elseif (!empty($action)) {
                        $type = "action";
                        $target=$action;
                    } else {
                        $type = "default";
                        $target = "";
                    }
                    $query = "insert into $table2 (name,type,target) values ('".mysqli_real_escape_string($db_link,$field)."','".mysqli_real_escape_string($db_link,$type)."','".mysqli_real_escape_string($db_link,$target)."')";
                    mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                }
            }
            mysqli_close($db_link);
        }
        if(!$preload_ok) return false;
        else
            return $translations[$lang][$field];
    } else
        return $translations[$lang][$field];
}

function setstr($field, $value, $lang="en") {
    global $translations,$translations_modified,$translations_indb;
    if (!is_array($translations))
        $translations = Array();
    if (!isset($translations[$lang]) || !is_array($translations[$lang]))
        $translations[$lang] = Array();
    if (!isset($translations[$lang][$field]) || $translations[$lang][$field] != $value) {
    if (!is_array($translations_modified))
        $translations_modified = Array();
        if (!isset($translations_modified[$lang]) || !is_array($translations_modified[$lang]))
            $translations_modified[$lang] = Array();
        $translations_modified[$lang][$field] = $value;
        $translations[$lang][$field] = $value;
        if(!isset($translations_indb[$lang][$field]))
            $translations_indb[$lang][$field] = false;
    }
}

function delstr($field, $lang="en") {
    $table="lang";
    $lang=addslashes($lang);
    include "db.php";
    if($db_link){
        mysqli_select_db($db_link,$db) or die(mysqli_error($db_link));
        mysqli_query($db_link,"set names utf8mb4");
        $query="delete from $table where name='$field' and lang='$lang'";
        $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        mysqli_close($db_link);
    }
}

function delstr2($id) {
    $table="lang";
    include "db.php";
    if($db_link){
        mysqli_select_db($db_link,$db) or die(mysqli_error($db_link));
        mysqli_query($db_link,"set names utf8mb4");
        $query="delete from $table where id=$id";
        $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        mysqli_close($db_link);
    }
}

function setlng($lang, $title, $locale=""){
    $table="locales";
    $lang=addslashes($lang);
    include "db.php";
    if($db_link){
        mysqli_select_db($db_link,$db) or die(mysqli_error($db_link));
        mysqli_query($db_link,"set names utf8mb4");
        $query="select * from $table where lang='$lang'";
        $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        $count=mysqli_num_rows($result);
        if($count > 0) {
            $query="update $table set def_title='$title' where lang='$lang'";
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
            $query="update $table set loc_title='$locale' where lang='$lang'";
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
            //update
        } else {
            $query="insert into $table (lang, def_title, loc_title) values ('$lang','$title','$locale')";
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
            //insert
        }
        $query="delete from $table where lang=''";
        mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        $query="delete from $table where def_title=''";
        mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        mysqli_close($db_link);
    }
}
function getlng(){
    include "db.php";
    if($db_link){
        mysqli_select_db($db_link,$db);
        mysqli_query($db_link,"set names utf8mb4");
        $table="locales";
        $query = "select * from $table";
        $result=mysqli_query($db_link,$query);
        if($result) {
            $count=mysqli_num_fields($result);
            if($count > 0){
                while($arr=mysqli_fetch_assoc($result)){
                    $tmp[$arr['lang']]=Array($arr['def_title'],$arr['loc_title']);
                }
            }
        }
        mysqli_close($db_link);
    }
    if(isset($tmp)) return $tmp;
    else return false;
}
function lister(){
    global $lang;
    include "db.php";
    if($db_link) {
        mysqli_select_db($db_link,$db);
        $table="lang";
        $tmp=Array();
        $names=Array();
        $query="select * from $table where lang='".mysqli_real_escape_string($db_link,$lang)."'";
        $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        if($result) {
            $count=mysqli_num_rows($result);
            if($count > 0){
                while($arr=mysqli_fetch_assoc($result)){
                    $tmp[]=Array($arr['name'],$arr['id'],$arr['lang']);
                    $names[]=$arr['name'];
                }

            }
        }
        $query="select * from $table where lang!='".mysqli_real_escape_string($db_link,$lang)."'";
        $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        if($result) {
            $count=mysqli_num_rows($result);
            if($count > 0){
                while($arr=mysqli_fetch_assoc($result)){
                    if(!in_array($arr['name'],$names)) {
                        $tmp[]=Array($arr['name'],$arr['id'],$arr['lang']);
                        $names[]=$arr['name'];
                    }

                }

            }
        }
        if(isset($tmp)) sort($tmp);


        mysqli_close($db_link);
    }
    if(isset($tmp)) return $tmp;
    else return false;
}

function chklng($lang){
    include "db.php";
    if($db_link){
        mysqli_select_db($db_link,$db);
        $table="locales";
        $query="desc $table";
        $query="select * from $table where lang='".addslashes($lang)."'";
        $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        $count=mysqli_num_rows($result);
        if($count == 0){
            $lang="en";
        }
        mysqli_close($db_link);
    }
    return $lang;
}

?>