<?php

    namespace App\System\Plugin;
    use App\System\Basic\beModel;
    use App\System\Basic\beRouter;
    use App\System\Controller\ConnectionController;
use App\System\Model\ServerModel;
use App\System\Model\SettingGroupsModel;
    use App\System\Model\SettingModel;
    use App\System\Vendor\Auth;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beModule;
    use App\System\Vendor\bePlugin;

    class teamspeak_helper {
        public function plugin_info(){
            return [
                "name" => "TeamSpeak Eklentisi",
                "description" => "TeamSpeak modülününü çalışması için gerekli alt yapıyı sağlar",
                "version" => "1.0",
                "vercode" => 1,
                "author" => "ITenGriTR"
            ];
        }
        public function plugin_hooks(){
            return [
                "routes_start" => "be_routes_insert"
            ];
        }
        public function plugin_settings(){
            return ["status" => true,"url" => beGetRoute("teamspeak.dashboard")];
        }
        public function plugin_install(){
            $sgid = bePlugin::beCreateSettingGroup("teamspeak","TeamSpeak Yöntemi","TeamSpeak ürünü yöntemi için gerekli ayarları yükler");
            bePlugin::beCreateSetting($sgid,"teamspeak_port_start","Port Başlangıç Numarası","TeamSpeak ürününün müşterilere teslim edilirken kurulacağı başlangıç port adresi","int","9000");
            bePlugin::beCreateSetting($sgid,"teamspeak_port_end","Port Bitiş Numarası","TeamSpeak ürününün müşterilere teslim edilirken kurulacağı bitiş port adresi","int","9999");
            bePlugin::beCreateSetting($sgid,"teamspeak_default_snapshot","Temel Yedek","Kurulum sonrası temel olarak yüklenecek olan yedeği seçiniz","select\n0=Yükleme","0");
            beModel::beQuery("CREATE TABLE `be_teamspeak3_snapshot` (`tsid` int(11) NOT NULL,`upid` int(11) NOT NULL,`tsname` varchar(256) NOT NULL,`tsdata` text NOT NULL,`tstype` enum('user','system') NOT NULL,`tsdateline` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `be_teamspeak3_snapshot` ADD PRIMARY KEY (`tsid`);ALTER TABLE `be_teamspeak3_snapshot` MODIFY `tsid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;COMMIT;")->beExecute();
            beModel::beQuery("CREATE TABLE `be_teamspeak3_snapshot_default` (`tsid` int(11) NOT NULL,`tsname` varchar(256) NOT NULL,`tsdata` text NOT NULL,`tsdateline` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;ALTER TABLE `be_teamspeak3_snapshot_default` ADD PRIMARY KEY (`tsid`);ALTER TABLE `be_teamspeak3_snapshot_default` MODIFY `tsid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;COMMIT;")->beExecute();
            return ["status" => true,"message" => "Başarılı bir şekilde eklenti kuruldu!"];
        }
        public function plugin_remove(){
            $sgid = SettingGroupsModel::beSelect("sgid")->beWhere("sgcode","paytr")->beGet()["sgid"];
            SettingGroupsModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            SettingModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            beModel::beQuery("DROP TABLE be_teamspeak3_snapshot,be_teamspeak3_snapshot_default")->beExecute();
            return ["status" => true,"message" => "Başarılı bir şekilde eklenti silindi!"];
        }
        public function be_routes_insert(){
            beRouter::bePrefix("/teamspeak","teamspeak.")->beGroup(function(){
                beRouter::beRoute("/","teamspeak_helper@dashboard")->beName("dashboard")->beSpecial()->beMiddleWare(["Auth","Admin" => ["permission" => "admin_plugin_edit"]]);
                beRouter::beRoute("/yedek-yonetimi","teamspeak_helper@snapshot_list")->beName("snapshot.list")->beSpecial()->beMiddleWare(["Auth","Admin" => ["permission" => "admin_plugin_edit"]]);
                beRouter::beRoute("/yedek-ekle","teamspeak_helper@snapshot_add")->beName("snapshot.add")->beSpecial()->beMiddleWare(["Auth","Admin" => ["permission" => "admin_plugin_edit"]]);
                beRouter::beRoute("/snapshot-add-post","teamspeak_helper@snapshot_add_post","post")->beName("snapshot.add.post")->beSpecial()->beMiddleWare(["Auth","Admin" => ["permission" => "admin_plugin_edit"]]);
                beRouter::beRoute("/snapshot-delete-post","teamspeak_helper@snapshot_delete_post","post")->beName("snapshot.delete.post")->beSpecial()->beMiddleWare(["Auth","Admin" => ["permission" => "admin_plugin_edit"]]);
            });
        }
        public function dashboard(){
            $settinggroup = SettingGroupsModel::beSelect("sgid")->beWhere("sgcode","teamspeak")->beGet();
            return beGetView("plugins.teamspeak.dashboard",["settingsurl" => beGetRoute("admin.settings.settinggroup.show",["sgid" => $settinggroup["sgid"]])]);
        }
        public function snapshot_list(){
            $snapshots = beModel::beTable("be_teamspeak3_snapshot_default")->beSelect("tsid,tsname,tsdateline")->beGetAll();
            return beGetView("plugins.teamspeak.snapshot.list",["snapshots" => $snapshots]);
        }
        public function snapshot_add(){
            $servers = ServerModel::beSelect("sid,sname,surl")->beWhere("smodule","teamspeak")->beGetAll();
            return beGetView("plugins.teamspeak.snapshot.add",["servers" => $servers]);
        }
        public function snapshot_add_post(){
            beLanguage::beReadLang("server");
            beLanguage::beReadLang("form");
            $name = htmlspecialchars($_POST["name"]);
            if(!$name){
                return beAjaxError(["message" => beGetLang("form_not_full")]);
            }
            $sid = (int)$_POST["server"];
            $port = (int)$_POST["port"];
            $server = ServerModel::beGetServer($sid);
            if(!$server){
                return beAjaxError(["message" => beGetLang("server_not_found")]);
            }
            if($server["smodule"] != "teamspeak"){
                return beAjaxError(["message" => beGetLang("server_not_found")]);
            }
            beModule::beLoadModule("product.teamspeak");
            $module = beModule::beGetModule("teamspeak");
            $response = $module->beSendApiRequest([
                "apiurl" => $server["surl"],
                "method" => "snapshotcreate",
                "data" => [
                    "port" => $port,
                    "login_host" => $server["surl"],
                    "login_password" => $server["spassword"],
                    "login_port" => $server["stoken"]
                ]
            ]);
            if(!$response["status"]){
                return beAjaxError(["message" => $response["message"]]);
            }
            $snapshot = $response["snapshot"];
            beModel::beInsert([
                "tsname" => $name,
                "tsdata" => $snapshot,
                "tsdateline" => BE_TIME,
            ],"be_teamspeak3_snapshot_default");
            $this->beUpdateSettings();
            return beAjaxSuccess(["message" => "Başarılı bir şekilde yedek alındı!","url" => beGetRoute("teamspeak.snapshot.list")]);
        }
        public function snapshot_delete_post(){
            $tsid = (int)$_POST["tsid"];
            $snapshot = beModel::beTable("be_teamspeak3_snapshot_default")->beSelect("tsid")->beWhere("tsid",$tsid)->beGet();
            if(!$snapshot){
                return beAjaxError(["message" => "Belirtilen yedek sistem üzerinde bulunmuyor!"]);
            }
            beModel::beDelete("be_teamspeak3_snapshot_default")->beWhere("tsid",$snapshot["tsid"])->beExecute();
            $this->beUpdateSettings();
            return beAjaxSuccess(["message" => "Başarılı bir şekilde temel yedek silindi!"]);
        }
        public function beUpdateSettings(){
            $teamspeak_default_snapshot = SettingModel::beGetSettings("teamspeak_default_snapshot")["teamspeak_default_snapshot"];
            $snapshots = beModel::beTable("be_teamspeak3_snapshot_default")->beSelect("tsid,tsname")->beGetAll();
            $updatedata = [];
            $found = false;
            $options = "select".PHP_EOL;
            $options .= "0=Yükleme".PHP_EOL;
            foreach($snapshots as $snapshot){
                $options .= $snapshot["tsid"]."=".$snapshot["tsname"].PHP_EOL;
                if($teamspeak_default_snapshot == $snapshot["tsid"]){
                    $found = true;
                }
            }
            $options = trim($options);
            if(!$found){
                $updatedata["svalue"] = 0;
            }
            $updatedata["stype"] = $options;
            SettingModel::beUpdate($updatedata)->beWhere("scode","teamspeak_default_snapshot")->beExecute();
        }
    }

?>