<?php
/**
 * Lang.php
 * Created by: Owen
 * Created on: 2020/1/10 16:45
 *
 */
defined('IN_WEB') or die('Include Error!');
class Lang{
    public function getClass($lang){
        $tb  = otable::CliLangConfig($lang);
        $sql = "SELECT path,name FROM {$tb} WHERE `value`=''";
        return oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
    }

    public function getDataByClass($lang,$class){
        $tb  = otable::CliLangConfig($lang);
        $sql = "SELECT * FROM {$tb} WHERE path LIKE '{$class}.%'";
        return oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
    }

    public function getLang($param){
        return json_encode([
            'class' => self::getClass($param['lang']),
            'data'  => self::getDataByClass($param['lang'],$param['class'])
        ]);
    }

    public function saveLang($param){
        $data = json_decode($param['data'],true);
        $allPath = array_column(self::getDataByClass($data['lang'],$data['class']),'path');
        $tb = otable::CliLangConfig($data['lang']);
        foreach ($data['data'] as $row){
            if(in_array($row['path'],$allPath)){
                $sql = "UPDATE {$tb} SET value='{$row['value']}' WHERE path='{$row['path']}'";
            }else{
                $sql = "INSERT INTO {$tb} (name,path,value) VALUES ('{$row['name']}','{$row['path']}','{$row['value']}')";
            }
            oo::commonOprDb('config')->query($sql);
        }
        $lang = strtolower($data['lang']);
        $filename = $param['filename'];
        $configTb = otable::LangStaticConfig();
        $sql = "UPDATE {$configTb} SET path='{$filename}' WHERE config='{$lang}'";
        oo::commonOprDb('common')->query($sql);
        oo::commonOprRedis('common')->hSet(okeys::LangStaticConfig(),$lang,$filename);
        $ret = oo::commonOprDb('config')->getAll("SELECT * FROM {$tb} WHERE 1",MYSQLI_ASSOC);
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }
}