<?php

namespace App\System\Controller;

use App\System\Basic\beContoller;
use App\System\Model\ServerModel;
use App\System\Model\SettingGroupsModel;
use App\System\Model\SettingModel;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beModule;
use App\System\Vendor\bePlugin;
use App\System\Vendor\beUpload;

class SettingController extends beContoller {
    public function settinggroups(){
        $settinggroups = SettingGroupsModel::beGetAll();
        return beGetView("admin.setting.group.list",["settinggroups" => $settinggroups]);
    }
    public function settinggroup($sgid = 0){
        $settinggroup = SettingGroupsModel::beWhere("sgid",$sgid)->beGet();
        $settings = SettingModel::beSelect("scode,stype,sname,sdescription,svalue")->beWhere("sgid",$settinggroup["sgid"])->beWhere("seditable","1")->beGetAll();
        return beGetView("admin.setting.group.show",["settinggroup" => $settinggroup,"settings" => $settings]);
    }
    public function save_post(){
        beLanguage::beReadLang("setting");
        $sgid = (int)$_POST["sgid"];
        $settings = SettingModel::beSelect("sid,scode,sname,stype")->beWhere("sgid",$sgid)->beWhere("seditable","1")->beGetAll();
        bePlugin::beRunHook("settings_update_pre");
        foreach($settings as $setting){
            $settingdata = bePlugin::beRunHook("setting_update_pre",["setting" => $setting,"code" => $setting["scode"]]);
            if(!isset($_POST[$setting["scode"]]) && !isset($_FILES[$setting["scode"]])){
                continue;
            }
            $types = explode(PHP_EOL,$setting["stype"]);
            $type = trim($types[0]);
            unset($types[0]);
            $updatevalue = null;
            switch($type){
                case "int" :
                case "float" :
                case "str" :
                    $updatevalue = $_POST[$setting["scode"]];
                    break;
                case "select" :
                    $updatevalue = $_POST[$setting["scode"]];
                    break;
                case "multipleselect" :
                    foreach($_POST[$setting["scode"]] as $key){
                        if(strpos($key,",") !== false){
                            return beAjaxError(["message" => "Anahtar içerisinde virgül(,) işareti bulunduğu için bu veri kaydedilemez!"]);
                        }
                    }
                    $updatevalue = implode(",",$_POST[$setting["scode"]]);
                    break;
                case "bool" :
                    if(isset($_POST[$setting["scode"]])){
                        $updatevalue = "1";
                    }
                    else{
                        $updatevalue = "0";
                    }
                case "img" :
                    $file = $_FILES[$setting["scode"]];
                    if($file["name"]){
                        $path = explode("=",$types[1])[1];
                        $upload = beUpload::beUploadFile($file,str_replace(" ","",$file["name"]),BE_ROOT.$path,0,null,false);
                        if(!$upload["status"]){
                            return beAjaxError(["message" => $upload["message"]." yüklenemedi!"]);
                        }
                        $fileurl = $path."/".$upload["filename"];
                        $updatevalue = $fileurl;
                    }
                    break;
            }
            if($updatevalue != null){
                SettingModel::beUpdate(["svalue" => $updatevalue])->beWhere("sid",$setting["sid"])->beExecute();
                $settingdata = bePlugin::beRunHook("setting_update_post",["setting" => $setting,"code" => $setting["scode"],"value" => $updatevalue]);
            }
        }
        return beAjaxSuccess(["message" => beGetLang("settings_updated")]);
    }
    public function server(){
        $servers = ServerModel::beSelect("sid,sname,surl,sstatus,sdateline")->beGetAll();
        return beGetView("admin.setting.server.list",["servers" => $servers]);
    }
    public function server_add(){
        $modules = beModule::beLoadModules("product");
        $modulelist = [];
        foreach($modules as $key => $module){
            $modulelist[$key] = $module["info"]["name"];
        }
        return beGetView("admin.setting.server.add",["modulelist" => $modulelist]);
    }
    public function server_add_post(){
        beLanguage::beReadLang("server");
        if(empty($_POST["name"])){
            return beAjaxError(["message" => beGetLang("server_compulsory_fields")]);
        }
        ServerModel::beInsert([
            "sname" => $_POST["name"],
            "smodule" => $_POST["module"],
            "surl" => $_POST["url"],
            "susername" => $_POST["username"],
            "spassword" => beEncryptData($_POST["password"]),
            "stoken" => $_POST["token"],
            "snameserver1" => $_POST["nameserver1"],
            "snameserver2" => $_POST["nameserver2"],
            "snameserver3" => $_POST["nameserver3"],
            "snameserver4" => $_POST["nameserver4"],
            "sstatus" => $_POST["status"],
            "sdateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("server_updated"),"url" => beGetRoute("admin.settings.server")]);
    }
    public function server_edit($sid){
        beLanguage::beReadLang("server");
        $server = ServerModel::beWhere("sid",$sid)->beGet();
        if(!$server){
            beError(beGetLang("server"),beGetLang("server_not_found"));
        }
        $modules = beModule::beLoadModules("product");
        $modulelist = [];
        foreach($modules as $key => $module){
            $modulelist[$key] = $module["info"]["name"];
        }
        $server["spassword"] = beDecryptData($server["spassword"]);
        return beGetView("admin.setting.server.edit",["server" => $server,"modulelist" => $modulelist]);
    }
    public function server_edit_post(){
        beLanguage::beReadLang("server");
        $sid = (int)$_POST["sid"];
        $server = ServerModel::beSelect("sid")->beWhere("sid",$sid)->beGet();
        if(!$server){
            return beAjaxError(["message" => beGetLang("server_not_found")]);
        }
        ServerModel::beUpdate([
            "sname" => $_POST["name"],
            "smodule" => $_POST["module"],
            "surl" => $_POST["url"],
            "susername" => $_POST["username"],
            "spassword" => beEncryptData($_POST["password"]),
            "stoken" => $_POST["token"],
            "snameserver1" => $_POST["nameserver1"],
            "snameserver2" => $_POST["nameserver2"],
            "snameserver3" => $_POST["nameserver3"],
            "snameserver4" => $_POST["nameserver4"],
            "sstatus" => $_POST["status"],
        ])->beWhere("sid",$server["sid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("server_updated")]);
    }
    public function server_check_post(){
        beLanguage::beReadLang("server");
        beLanguage::beReadLang("module");
        $modulename = $_POST["module"];
        $module = beModule::beLoadModule("product.{$modulename}");
        if(!$module["status"]){
            return beAjaxError(["message" => beGetLang("module_not_found")]);
        }
        if(!beModule::beCheckModuleFunction($modulename,"connection_test")){
            return beAjaxError(["message" => beGetLang("module_connection_test_not_found")]);
        }
        $data = [
            "surl" => $_POST["url"],
            "susername" => $_POST["username"],
            "spassword" => $_POST["password"],
            "stoken" => $_POST["token"],
            "snameserver1" => $_POST["nameserver1"],
            "snameserver2" => $_POST["nameserver2"],
            "snameserver3" => $_POST["nameserver3"],
            "snameserver4" => $_POST["nameserver4"]  
        ];
        $response = beModule::beRunModuleFunction($modulename,"connection_test",$data);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => beGetLang("module_connection_test_successfully")]);
    }
    public function module(){
        $settings = SettingModel::beGetSettings("system_sms_module,system_invoice_module");
        $modules = [];
        $modules["sms"] = beModule::beLoadModules("sms");
        $modules["invoice"] = beModule::beLoadModules("invoice");
        return beGetView("admin.setting.module",["modules" => $modules,"settings" => $settings]);
    }
    public function module_set_post(){
        beLanguage::beReadLang("setting");
        $type = $_POST["type"];
        $module = $_POST["module"];
        if(!in_array($type,["sms","invoice"])){
            return beAjaxError(["message" => beGetLang("setting_module_type_not_found")]);
        }
        if($module){
            $modules = beModule::beLoadModules($type);
            if(!$modules[$module]){
                return beAjaxError(["message" => beGetLang("setting_module_type_not_compatible")]);
            }   
        }
        SettingModel::beUpdate(["svalue" => $module])->beWhere("scode","system_{$type}_module")->beExecute();
        return beAjaxSuccess(["message" => beGetLang("settings_updated")]);
    }
}

?>