<?php

    namespace App\System\Plugin;
    use App\System\Basic\beRouter;
use App\System\Model\ProductAddonGroupModel;
use App\System\Model\ProductAddonModulesModel;
use App\System\Model\ProductAddonsModel;
use App\System\Model\ProductAddonTranslationsModel;
use App\System\Model\ServerModel;
use App\System\Model\SettingGroupsModel;
    use App\System\Model\SettingModel;
use App\System\Vendor\beModule;
use App\System\Vendor\bePlugin;
use App\System\Vendor\beSms;

    class hetznercloud_helper {
        public function plugin_info(){
            return [
                "name" => "Hetzner Cloud Eklentisi",
                "description" => "Hetzner Cloud 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" => "my_routes_insert"
            ];
        }
        public function plugin_settings(){
            return ["status" => true,"url" => beGetRoute("hetznercloud.dashboard")];
        }
        public function plugin_install(){
            $sgid = bePlugin::beCreateSettingGroup("hetznercloud","Hetzner Cloud","Hetzner Cloud modülü için gerekli ayarları yükler");
            bePlugin::beCreateSetting($sgid,"hetznercloud_auto_price","Otomatik Fiyatlandırma","Hetzner Cloud ürünleri için fiyatlandırmanın otomatik olup olmamasını seçiniz","select\n0=Kapalı\n1=Açık","1");
            bePlugin::beCreateSetting($sgid,"hetznercloud_profit_rate","Kar Oranı","Ürün sistemi üzerinde otomatik moddayken fiyatların üstüne koyulacak kazanç oranı","int","30");
            return ["status" => true];
        }
        public function plugin_remove(){
            $sgid = SettingGroupsModel::beSelect("sgid")->beWhere("sgcode","hetznercloud")->beGet()["sgid"];
            SettingGroupsModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            SettingModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            return ["status" => true,"message" => "Başarılı bir şekilde eklenti silindi!"];
        }
        public function my_routes_insert(){
            beRouter::bePrefix("/hetznercloud","hetznercloud.")->beGroup(function(){
                beRouter::beRoute("/","hetznercloud_helper@dashboard")->beName("dashboard")->beSpecial()->beMiddleWare(["Auth","Admin" => ["permission" => "admin_plugin_edit"]]);
                beRouter::beRoute("/add-addon","hetznercloud_helper@addon_add_post","post")->beName("addon.add.post")->beSpecial()->beMiddleWare(["Auth","Admin" => ["permission" => "admin_plugin_edit"]]);
            });
        }
        public function dashboard(){
            $settinggroup = SettingGroupsModel::beSelect("sgid")->beWhere("sgcode","hetznercloud")->beGet();
            return beGetView("plugins.hetznercloud.dashboard",["settingsurl" => beGetRoute("admin.settings.settinggroup.show",["sgid" => $settinggroup["sgid"]])]);
        }
        public function addon_add_post(){
            $productaddongroup = ProductAddonGroupModel::beSelect("pagid")->beWhere("pagname","Hetzner Cloud")->beGet();
            if(!$productaddongroup){
                $productaddongroup = [];
                $productaddongroup["pagid"] = ProductAddonGroupModel::beInsert([
                    "pagname" => "Hetzner Cloud",
                    "pagdateline" => BE_TIME
                ]);
            }
            $addontype = $_POST["addontype"];
            switch($addontype){
                case "image" :
                    $productaddontranslation = ProductAddonTranslationsModel::beSelect("patid")->beWhere("pacode","hetznercloud_image")->beGet();
                    if($productaddontranslation){
                        return beAjaxError(["message" => "Modül için imaj görüntüleri eklentisi zaten oluşturulmuş. Lütfen ürün eklentileri kısmını kontorl ediniz!"]);
                    }
                    $paid = ProductAddonsModel::beInsert([
                        "pagid" => $productaddongroup["pagid"],
                        "padateline" => BE_TIME
                    ]);
                    $patid = ProductAddonTranslationsModel::beInsert([
                        "lid" => 1,
                        "paid" => $paid,
                        "paname" => "İşletim Sistemi(CPX)",
                        "pacode" => "hetznercloud_image",
                        "patype" => "select",
                        "paoptions" => '{"1":{"oname":"Ubuntu 20","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"2":{"oname":"Ubuntu 22","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"3":{"oname":"Ubuntu 24","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"4":{"oname":"Centos 9","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"5":{"oname":"Debian 11","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"6":{"oname":"Debian 12","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"7":{"oname":"Fedora 40","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"8":{"oname":"Fedora 41","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"9":{"oname":"Rocky 8","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"10":{"oname":"Rocky 9","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"11":{"oname":"Alma 8","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"12":{"oname":"Alma 9","operiodtime":1,"operiod":"none","oprice":"0","ocid":1},"13":{"oname":"openSuse 15","operiodtime":1,"operiod":"none","oprice":"0","ocid":1}}',
                        "pastatus" => "1",
                        "paposition" => 0,
                        "pacompulsory" => "1",
                        "paovveridecurrency" => "0",
                        "pamatchperiod" => "0"
                    ]);
                    $images = ["ubuntu-20.04","ubuntu-22.04","ubuntu-24.04","centos-stream-9","debian-11","debian-12","fedora-40","fedora-41","rocky-8","rocky-9","alma-8","alma-9","opensuse-15"];
                    foreach($images as $key => $image){
                        ProductAddonModulesModel::beInsert([
                            "paid" => $paid,
                            "patid" => $patid,
                            "pamodule" => "hetznercloud",
                            "pamodulekey" => $key+1,
                            "pavalue" => $image,
                            "padateline" => BE_TIME
                        ]);
                    }
                    return beAjaxSuccess(["message" => "Başarılı bir şekilde imaj görüntüleri için eklenti eklendi!"]);
                    break;
                case "location" :
                    $server = ServerModel::beGetServer("hetznercloud");
                    if(!$server){
                        return ["status" => false,"message" => "Hetzner Cloud eklentileri için Hetzner Cloud modülünün sunucu bilgileri girilmemiş."];
                    }
                    $settings = SettingModel::beGetSettings("hetznercloud_auto_price,hetznercloud_profit_rate");
                    beModule::beLoadModule("product.hetznercloud");
                    $module = beModule::beGetModule("hetznercloud");
                    $response = $module->beSendApiRequest([
                        "apiurl" => $server["surl"],
                        "method" => "servertypes",
                        "data" => [
                            "login_token" => $server["stoken"]
                        ]
                    ]);
                    if(!$response["status"]){
                        return ["status" => false,"message" => $response["message"]];
                    }
                    $servertypes = $response["servertype"];
                    $response = $module->beSendApiRequest([
                        "apiurl" => $server["surl"],
                        "method" => "datacenters",
                        "data" => [
                            "login_token" => $server["stoken"]
                        ]
                    ]);
                    if(!$response["status"]){
                        return ["status" => false,"message" => $response["message"]];
                    }
                    $datacenters = $response["datacenters"];
                    foreach($servertypes as $skey => $servertype){
                        $productaddontranslation = ProductAddonTranslationsModel::beSelect("patid")->beWhere("pacode","hetznercloud_{$servertype['name']}")->beGet();
                        if($productaddontranslation){
                           continue;
                        }
                        $paid = ProductAddonsModel::beInsert([
                            "pagid" => $productaddongroup["pagid"],
                            "padateline" => BE_TIME
                        ]);
                        $options = [];
                        $counter = 1;
                        $modulevalue = [];
                        foreach($servertype["prices"] as $pkey => $price){
                            $location = $price["location"];
                            $found = false;
                            $datacenter = [];
                            foreach($datacenters as $dkey => $datacenter){
                                if($datacenter["location"]["name"] != $location){
                                    continue;
                                }
                                $found = true;
                                break;
                            }
                            if(!$found){
                                continue;
                            }
                            $itemprice = round($price["price_monthly"]["net"],4);
                            if($settings["hetznercloud_auto_price"]){
                                $itemprice = round(($itemprice*(100+$settings["hetznercloud_profit_rate"]))/100,4);
                            }
                            $options[$counter] = [
                                "oname" => $datacenter["location"]["city"],
                                "operiodtime" => 1,
                                "operiod" => "month",
                                "oprice" => $itemprice,
                                "ocid" => 3
                            ];
                            $modulevalue[$counter] = $location;
                            $counter += 1;
                        }
                        $patid = ProductAddonTranslationsModel::beInsert([
                            "lid" => 1,
                            "paid" => $paid,
                            "paname" => "Lokasyon({$servertype['description']})",
                            "pacode" => "hetznercloud_{$servertype['name']}",
                            "patype" => "select",
                            "paoptions" => json_encode($options,JSON_UNESCAPED_UNICODE),
                            "pastatus" => "1",
                            "paposition" => 0,
                            "pacompulsory" => "1",
                            "paovveridecurrency" => "1",
                            "pamatchperiod" => "1"
                        ]);
                        foreach($modulevalue as $mkey => $value){
                            ProductAddonModulesModel::beInsert([
                                "paid" => $paid,
                                "patid" => $patid,
                                "pamodule" => "hetznercloud",
                                "pamodulekey" => "datacenter",
                                "pakey" => $mkey,
                                "pavalue" => $value,
                                "padateline" => BE_TIME
                            ]);
                        }
                    }
                    return beAjaxSuccess(["message" => "Başarılı bir şekilde lokasyon verileri için eklenti eklendi!"]);
                    break;
            }
        }
    }
?>