<?php

namespace App\System\Module;

use App\System\Basic\beRouter;
use App\System\Controller\NavController;
use App\System\Model\CurrencyModel;
use App\System\Model\InvoiceItemModel;
use App\System\Model\InvoiceModel;
use App\System\Model\ModuleLogModel;
use App\System\Model\ProductModel;
use App\System\Model\UserProductExtensionsModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\Basic\beCookie;
use App\System\Vendor\beLanguage;

class diyovm {
    public $options = [
        "isneedserver" => true
    ];
    public $pages = [
        "/" => [
            "showmenu" => true,
            "name" => "Ana Sayfa",
            "icon" => "<i class=\"ri-home-line\"></i>"
        ],
        "sifre-yonetimi" => [
            "showmenu" => true,
            "name" => "Şifre Yönetimi",
            "icon" => "<i class=\"ri-git-repository-private-line\"></i>",
            "function" => "diyovm_clientarea_password"
        ],
        "ip-adresleri" => [
            "showmenu" => true,
            "name" => "IPv4 Adresleri",
            "icon" => "<i class=\"ri-earth-line\"></i>",
            "function" => "diyovm_clientarea_ipaddress"
        ],
        "rdns" => [
            "showmenu" => true,
            "name" => "rDNS İşlemleri",
            "icon" => "<i class=\"ri-ai-generate\"></i>",
            "altmenu" => [
                "rdns-kaydi-olustur" => [
                    "showmenu" => true,
                    "name" => "rDNS Kaydı Oluştur",
                    "icon" => "<i class=\"ri-map-pin-add-line\"></i>",
                    "function" => "diyovm_clientarea_rdns_create"
                ],
                "rdns-kayitlari" => [
                    "showmenu" => true,
                    "name" => "rDNS Kayitlari",
                    "icon" => "<i class=\"ri-link-m\"></i>",
                    "function" => "diyovm_clientarea_rdns_list"
                ],
                "rdns-kaydi-duzenle" => [
                    "showmenu" => false,
                    "name" => "rDNS Kaydi Düzenle",
                    "function" => "diyovm_clientarea_rdns_edit"
                ],
            ]
        ],
        "yedek-yonetimi" => [
            "showmenu" => true,
            "name" => "Yedek Yönetimi",
            "icon" => "<i class=\"ri-arrow-go-back-line\"></i>",
            "function" => "diyovm_clientarea_snapshot"
        ],
        "kayitlar" => [
            "showmenu" => true,
            "name" => "Kayıtlar",
            "icon" => "<i class=\"ri-git-repository-line\"></i>",
            "function" => "diyovm_clientarea_logs"
        ],
        "format" => [
            "showmenu" => true,
            "name" => "Format / Yeniden Kurulum",
            "icon" => "<i class=\"ri-format-clear\"></i>",
            "function" => "diyovm_clientarea_format"
        ],
        "console" => [
            "showmenu" => true,
            "name" => "Konsol",
            "icon" => "<i class=\"ri-terminal-box-line\"></i>",
            "function" => "diyovm_clientarea_console"
        ],
        "arttir" => [
            "showmenu" => true,
            "name" => "Yükseltim İşlemleri",
            "icon" => "<i class=\"ri-ai-generate\"></i>",
            "altmenu" => [
                "yukseltim" => [
                    "showmenu" => true,
                    "name" => "Hizmetimi Yükselt",
                    "icon" => "<i class=\"ri-upload-cloud-2-fill\"></i>",
                    "function" => "diyovm_clientarea_upgrade"
                ],
                "cpu-arttir" => [
                    "showmenu" => true,
                    "name" => "CPU Yükselt",
                    "icon" => "<i class=\"ri-ai-generate\"></i>",
                    "function" => "diyovm_clientarea_extra_cpu"
                ],
                "ram-arttir" => [
                    "showmenu" => true,
                    "name" => "RAM Yükselt",
                    "icon" => "<i class=\"ri-ai-generate\"></i>",
                    "function" => "diyovm_clientarea_extra_ram"
                ],
                "disk-arttir" => [
                    "showmenu" => true,
                    "name" => "DISK Yükselt",
                    "icon" => "<i class=\"ri-ai-generate\"></i>",
                    "function" => "diyovm_clientarea_extra_disk"
                ],
                "ip-arttir" => [
                    "showmenu" => true,
                    "name" => "IP Ekle",
                    "icon" => "<i class=\"ri-ai-generate\"></i>",
                    "function" => "diyovm_clientarea_extra_ip"
                ]
            ]
        ],
    ];
    public function diyovm_permissions($data = []){
        return [
            [
                "ugpname" => "Sipariş Üzerinde Hesap Bilgilerini Görüntüleme",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_show_info",
            ],
            [
                "ugpname" => "Sipariş Üzerinde İstatistik Bilgilerini Görüntüleyebilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_show_info_stats",
            ],
            [
                "ugpname" => "Sipariş Üzerinde Sunucuyu Başlatabilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_process_start",
            ],
            [
                "ugpname" => "Sipariş Üzerinde Sunucuyu Durdurabilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_process_stop",
            ],
            [
                "ugpname" => "Sipariş Üzerinde Sunucuyu Yeniden Başlatabilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_process_restart",
            ],
            [
                "ugpname" => "Sipariş Üzerinde Sunucu Konsoluna Erişebilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_console",
            ],
            [
                "ugpname" => "Sipariş Üzerinde Sunucuyu Güncelleyebilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_update",
            ],
            [
                "ugpname" => "Sipariş Üzerinde Sunucunun IP Adreslerini Güncelleyebilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_change_ip",
            ],
            [
                "ugpname" => "Sipariş Üzerinde Sunucuya Format Atabilir",
                "ugptype" => "bool",
                "ugpcode" => "diyovm_format",
            ]
        ];
    }
    public function diyovm_info(){
        return [
            "name" => "DiyoVM",
            "description" => "DiyoVM ile gerekli bağlantıyı kurup otomasyon sağlar",
            "version" => "1.0",
            "vercode" => 10,
            "type" => "server",
            "author" => "ITenGriTR"
        ];
    }
    public function diyovm_connection_test($params = []){
        $response = $this->beSendApiRequest([
            "apiurl" => $params["surl"],
            "method" => "checkuser",
            "data" => [
                "email" => $params["susername"],
                "password" => $params["spassword"],
                "hash" => $params["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return ["status" => false,"message" => $response["message"]];
        }
        return ["status" => true];
    }
    public function diyovm_order_config(){
        return [
            "status" => [
                "name" => "Sunucu Durumu",
                "description" => "Sunucunun durumunu belirler",
                "type" => "select",
                "status" => 1,
                "default" => 1,
                "values" => [
                    -1 => "Silindi",
                    1 => "Kuruluyor",
                    2 => "Kuruldu"
                ]
            ],
            "vm_id" => [
                "name" => "VM ID",
                "description" => "Kullanıcının yöneteceği sunucunun panel üzerindeki değerini giriniz(Sunucu Yönetimi)",
                "type" => "integer",
                "default" => ""
            ]
        ];
    }
    public function diyovm_product_config($params = []){
        global $be;
        $defcurrencie = $be->settings["system_currency"];
        $currencie = CurrencyModel::beGetCurrencies("cid,cname",$defcurrencie);
        return [
            "clusterid" => [
                "name" => "Cluster Değeri",
                "description" => "Clusterin değerini belirleyiniz(Cluster Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "hostid" => [
                "name" => "Host Değeri",
                "description" => "Hostun değerini belirleyiniz(Host Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "datastoreid" => [
                "name" => "Disk Değeri",
                "description" => "Diskin değerini belirleyiniz(Disk Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "poolid" => [
                "name" => "Havuz Değeri",
                "description" => "Havuzun değerini belirleyiniz(Havuz Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "planid" => [
                "name" => "Plan Paketi",
                "description" => "Farklı bir planın değerini giriniz(Plan Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "ipplanid" => [
                "name" => "IP Plan Paketi",
                "description" => "Farklı bir ip plan paketinin değerini giriniz(IP Plan Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "ipcount" => [
                "name" => "IP Adresi Adeti",
                "description" => "Verilecek ip adresi adetini giriniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "cpucore" => [
                "name" => "İşlemci Sayısı(Çekirdek)",
                "description" => "Verilecek çekirdek sayısını belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0,
                    "max" => 99
                ]
            ],
            "cpulimitmhz" => [
                "name" => "İşlemci Hızı",
                "description" => "Verilecek işlemci hızını(MHZ) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0,
                    "max" => 99
                ]
            ],
            "ramgb" => [
                "name" => "Ram GB",
                "description" => "Verilecek ram miktarını(GB) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "diskgb" => [
                "name" => "Disk GB",
                "description" => "Verilecek disk miktarını(GB) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "bandwith" => [
                "name" => "Bant Genişliği GB",
                "description" => "Verilecek bant genişliği miktarını(GB) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "osid" => [
                "name" => "İşletim Sistemi",
                "description" => "İşletim sisteminin değerini giriniz(Şablon Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "snapshot" => [
                "name" => "Yedek Hakkı",
                "description" => "Verilecek yedek hakkını(Adet) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "formatcount" => [
                "name" => "Format Hakkı",
                "description" => "Verilecek format hakkını(Adet) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "cpuprice" => [
                "name" => "CPU(CORE) Fiyatı({$currencie['cname']} - AYLIK)",
                "description" => "Sunucu içerisinden ekstra olarak işlemci çekirdeği alındığında uygulanacak fiyat.",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "ramprice" => [
                "name" => "RAM(GB) Fiyatı({$currencie['cname']} - AYLIK)",
                "description" => "Sunucu içerisinden ekstra olarak RAM(GB) alındığında uygulanacak fiyat.",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "diskprice" => [
                "name" => "DISK(GB) Fiyatı({$currencie['cname']} - AYLIK)",
                "description" => "Sunucu içerisinden ekstra olarak DISK(GB) alındığında uygulanacak fiyat.",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "ipprice" => [
                "name" => "IP(ADET) Fiyatı({$currencie['cname']} - AYLIK)",
                "description" => "Sunucu içerisinden ekstra olarak IP(ADET) alındığında uygulanacak fiyat.",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-3" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ]    
        ];
    }
    public function diyovm_addon_config($params = []){
        return [        
            "clusterid" => [
                "name" => "Cluster Değeri",
                "description" => "Clusterin değerini belirleyiniz(Cluster Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "hostid" => [
                "name" => "Host Değeri",
                "description" => "Hostun değerini belirleyiniz(Host Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "datastoreid" => [
                "name" => "Disk Değeri",
                "description" => "Diskin değerini belirleyiniz(Disk Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "planid" => [
                "name" => "Plan Paketi",
                "description" => "Farklı bir planın değerini giriniz(Plan Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "poolid" => [
                "name" => "Havuz Değeri",
                "description" => "Havuzun değerini belirleyiniz(Havuz Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "ipplanid" => [
                "name" => "IP Plan Paketi",
                "description" => "Farklı bir ip plan paketinin değerini giriniz(IP Plan Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-4" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "osid" => [
                "name" => "İşletim Sistemi",
                "description" => "İşletim sisteminin değerini giriniz(Şablon Yönetimi ID)",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "ipcount" => [
                "name" => "IP Adresi Adeti",
                "description" => "Extra olarak verilecek ip adresi adetini giriniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "cpucore" => [
                "name" => "İşlemci Sayısı(Çekirdek)",
                "description" => "Extra olarak verilecek çekirdek sayısını belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0,
                    "max" => 99
                ]
            ],
            "cpulimitmhz" => [
                "name" => "İşlemci Hızı",
                "description" => "Extra olarak verilecek işlemci hızını(MHZ) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0,
                ]
            ],
            "ramgb" => [
                "name" => "Ram GB",
                "description" => "Extra olarak verilecek ram miktarını(GB) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "diskgb" => [
                "name" => "Disk GB",
                "description" => "Extra olarak verilecek disk miktarını(GB) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "bandwith" => [
                "name" => "Bant Genişliği GB",
                "description" => "Extra olarak verilecek bant genişliği miktarını(GB) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "snapshot" => [
                "name" => "Yedek Hakkı",
                "description" => "Extra olarak verilecek yedek hakkını(Adet) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ],
            "formatcount" => [
                "name" => "Format Hakkı",
                "description" => "Extra olarak verilecek format hakkını(Adet) olarak belirleyiniz",
                "type" => "integer",
                "default" => "",
                "form-view" => [
                    "class" => "col-6" 
                ],
                "requirements" => [
                    "min" => 0
                ]
            ]
        ];
    }
    public function diyovm_content_up($params = []){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "templatelist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return "Erişim Hatası: DiyoVM modülüne erişilemedi!<br>".$response["message"];
        }
        $statuslist = [
            -1 => [
                0 => "Askıda",
                1 => "text-warning"
            ],
            1 => [
                0 => "Aktif",
                1 => "text-success"
            ]
        ];
        $vm = $response["server"];
        $vm["sdata"] = json_decode($vm["sdata"],true);
        $templatelist = $response["templatelist"] ?? [];
        foreach($templatelist as $key => $template){
            if($vm["sdata"]["template"] == $template["tid"]){
                $vm["sdata"]["templatename"] = $template["tname"];
            }
        }
        return beGetView("modules.diyovm.contentup",["userproduct" => $userproduct,"server" => $params["server"],"vm" => $vm,"statuslist" => $statuslist]);
    }
    public function diyovm_content_down($params = []){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        if($updata["status"] != 2){
            return "";
        }
        return beGetView("modules.diyovm.contentdown",["userproduct" => $userproduct,"updata" => $updata]);
    }
    public function diyovm_create($params = []){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $system_vals = [
            "clusterid" => [
                "name" => "clusterId",
                "type" => "set"
            ],
            "hostid" => [
                "name" => "hostId",
                "type" => "set"
            ],
            "datastoreid" => [
                "name" => "datastoreId",
                "type" => "set"
            ],
            "planid" => [
                "name" => "planId",
                "type" => "set"
            ],
            "poolid" => [
                "name" => "poolId",
                "type" => "set"
            ],
            "ipplanid" => [
                "name" => "ipPlanId",
                "type" => "set"
            ],
            "ipcount" => [
                "name" => "ipCount",
                "type" => "option"
            ],
            "osid" => [
                "name" => "osId",
                "type" => "set"
            ],
            "cpucore" => [
                "name" => "cpuCore",
                "type" => "option"
            ],
            "cpulimitmhz" => [
                "name" => "cpuLimitMhz",
                "type" => "option"
            ],
            "ramgb" => [
                "name" => "ramGB",
                "type" => "option"
            ],
            "diskgb" => [
                "name" => "diskGB",
                "type" => "option"
            ],
            "bandwith" => [
                "name" => "bandwithGB",
                "type" => "option"
            ],
            "snapshot" => [
                "name" => "snapShotCount",
                "type" => "option"
            ]
        ];
        $server_data = [];
        $formatcount = 0;
        foreach($params["productmodules"] as $key => $value){
            $server_data[$system_vals[$key]["name"]] = $value;
            if($key == "formatcount"){
                $formatcount = $value;
            }
        }
        foreach($params["addonmodules"] as $key => $value){
            if(!$value[0]){
                continue;
            }
            if($system_vals[$key]["type"] == "set"){
                $server_data[$system_vals[$key]["name"]] = $value[0];
            }
            else{
                $server_data[$system_vals[$key]["name"]."Extra"] = $value[0];
            }
            if($key == "formatcount"){
                $formatcount += $value[0];
            }
        }
        $user = Auth::beGetUser($userproduct["uid"],"email");
        $basic_vals["userMail"] = $user["email"];
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "createvm",
            "data" => array_merge([
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ],$server_data)
        ]);
        if(!$response["status"]){
            ModuleLogModel::beCreateModuleLog($userproduct["upid"],"diyovm","Kurulum Hatası",$response["message"],[
                "data" => $server_data,
                "response" => $response
            ]);
            return ["status" => false,"message" => "Sunucu oluşturulurken bir şeyler ters gitti!"];
        }
        $updatedata = [];
        $updatedata["uptag"] = $response["iplist"][0];
        $firstip = $response["iplist"][0];
        $updata = [
            "firstip" => $firstip,
            "assigned_ips" => $response["iplist"],
            "username" => $response["username"],
            "password" => beEncryptData($response["password"]),
            "vm_id" => $response["sid"],
            "taskid" => $response["tid"],
            "status" => 1,
            "formatcount" => $formatcount,
            "formatcountnow" => 0
        ];
        $activisioninfo = "Sunucu IP: {$firstip}<br>";
        $activisioninfo .= "Kullanıcı Adı: {$updata['username']}<br>";
        $activisioninfo .= "Şifre: {$response['password']}<br>";
        $updatedata["updata"] = json_encode($updata,JSON_UNESCAPED_UNICODE);
        UserProductModel::beUpdate($updatedata)->beWhere("upid",$userproduct["upid"])->beExecute();
        return [
            "status" => true,
            "message" => "Ürün yönetim paneline yönlendiliriliyorsunuz",
            "url" => beGetRoute("client.userproduct.userproduct.show",["upid" => $userproduct["upid"]]),
            "activisioninfo" => $activisioninfo
        ];
    }
    public function diyovm_manage($params = []){
        $userproduct = $params["userproduct"];
        beCookie::beCreateCookie("be_upid",$userproduct["upid"],true,true);
        return ["status" => true,"message" => "Ürün yönetim paneline yönlendiliriliyorsunuz","url" => beGetRoute("client.userproduct.userproduct.show",["upid" => $userproduct["upid"]])];
    }
    public function diyovm_suspend($params = []){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "suspendvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "action" => "suspend",
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return ["status" => false,"message" => $response["message"]];
        }
        $updata["status"] = 1;
        UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
        return ["status" => true,"message" => "Başarılı bir şekilde sipariş modül üzerinde askıya alındı!"];
    }
    public function diyovm_unsuspend($params = []){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "suspendvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "action" => "unsuspend",
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return ["status" => false,"message" => $response["message"]];
        }
        $updata["status"] = 1;
        UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
        return ["status" => true,"message" => "Başarılı bir şekilde sipariş modül üzerinde askıya alındı!"];
    }
    public function diyovm_terminate($params = []){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "deletevm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return ["status" => false,"message" => $response["message"]];
        }
        $updata["status"] = 1;
        UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
        return ["status" => true,"message" => "Başarılı bir şekilde sipariş modül üzerinde silindi!"];
    }
    public function diyovm_upgrade($params = []){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "updatevm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "planId" => (int)$params["newproductmodules"]["planid"],
                "oldPlanId" => (int)$params["productmodules"]["planid"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            ModuleLogModel::beCreateModuleLog($userproduct["upid"],"diyovm","Yükseltim Hatası",$response["message"],[
                "data" => [
                    "vm_id" => $updata["vm_id"],
                    "planId" => (int)$params["newproductmodules"]["planid"],
                    "oldPlanId" => (int)$params["productmodules"]["planid"]
                ],
                "response" => $response
            ]);
            return ["status" => false,"message" => "Yükseltim işleminde bir sorun oluştu!"];
        }
        return ["status" => true,"message" => "Başarılı bir şekilde yükseltim işlemi tamamlandı!"];
    }
    public function diyovm_special_invoice($params){
        $productmodules = $params["productmodules"];
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $item = $params["item"];
        $type = $item["iidata"]["type"];
        $itemprice = $item["iidata"]["itemprice"];
        $alltimeprice = $item["iidata"]["alltimeprice"];
        if(!in_array($type,["cpu","ram","disk","ip"])){
            return ["status" => false,"message" => "Belirtilen özel fatura DIYOVM modülü tarafından tanınmadı!"];
        }
        $upeid = UserProductExtensionsModel::beInsert([
            "upid" => $userproduct["upid"],
            "cid" => $userproduct["cid"],
            "upename" => $item["iiname"],
            "upeunitcount" => $item["iiunitcount"],
            "upeunitprice" => $alltimeprice,
            "upeunittype" => "quantity",
            "uperate" => $item["iitaxrate"],
            "upetype" => "period",
            "upestatus" => "1",
            "upedata" => json_encode([
                "module" => "diyovm",
                "type" => $type,
                "count" => $item["iiunitcount"]
            ],JSON_UNESCAPED_UNICODE)
        ]);
        switch($type){
            case "cpu" :
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "updatevm",
                    "data" => [
                        "vm_id" => $updata["vm_id"],
                        "updatetype" => "upgrade",
                        "cpuCore" => $item["iiunitcount"],
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                if(!$response["status"]){
                    ModuleLogModel::beCreateModuleLog($userproduct["upid"],"diyovm","Özel Yükseltim Hatası",$response["message"],[
                        "data" => [
                            "vm_id" => $updata["vm_id"],
                            "type" => $type,
                        ],
                        "response" => $response
                    ]);
                    return ["status" => false,"message" => "Özel yükseltim işleminde bir sorun oluştu!"];
                }
                break;
            case "ram" :
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "updatevm",
                    "data" => [
                        "vm_id" => $updata["vm_id"],
                        "updatetype" => "upgrade",
                        "ramGB" => $item["iiunitcount"],
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                if(!$response["status"]){
                    ModuleLogModel::beCreateModuleLog($userproduct["upid"],"diyovm","Özel Yükseltim Hatası",$response["message"],[
                        "data" => [
                            "vm_id" => $updata["vm_id"],
                            "type" => $type,
                        ],
                        "response" => $response
                    ]);
                    return ["status" => false,"message" => "Özel yükseltim işleminde bir sorun oluştu!"];
                }
                break;
            case "disk" :
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "updatevm",
                    "data" => [
                        "vm_id" => $updata["vm_id"],
                        "updatetype" => "upgrade",
                        "diskGB" => $item["iiunitcount"],
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                if(!$response["status"]){
                    ModuleLogModel::beCreateModuleLog($userproduct["upid"],"diyovm","Özel Yükseltim Hatası",$response["message"],[
                        "data" => [
                            "vm_id" => $updata["vm_id"],
                            "type" => $type,
                        ],
                        "response" => $response
                    ]);
                    return ["status" => false,"message" => "Özel yükseltim işleminde bir sorun oluştu!"];
                }
                break;
            case "ip" :
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "getvm",
                    "data" => [
                        "vm_id" => $updata["vm_id"],
                        "iplist" => true,
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                $vm = $response["server"];
                $iids = [];
                foreach($response["iplist"] as $ipaddress){
                    $iid = (int)$ipaddress["iid"];
                    $iids["ip_".$iid] = $iid;
                }
                $ipplanid = $productmodules["ipplanid"];
                $iplist = [];
                if($ipplanid){
                    $response = $this->beSendApiRequest([
                        "apiurl" => $params["server"]["surl"],
                        "method" => "getipaddresses",
                        "data" => [
                            "igid" => $ipplanid,
                            "istatus" => "1",
                            "email" => $params["server"]["susername"],
                            "password" => $params["server"]["spassword"],
                            "hash" => $params["server"]["stoken"]
                        ]
                    ]);
                    $iplist = $response["ipaddresses"];
                    $ipcount = count($iplist);
                    if($ipcount < $item["iiunitcount"]){
                        return ["status" => false,"message" => "Özel yükseltim işleminde belirtilen adette stok bulunamadı!"];
                    }
                }
                else{
                    $response = $this->beSendApiRequest([
                        "apiurl" => $params["server"]["surl"],
                        "method" => "getipaddresses",
                        "data" => [
                            "hid" => $vm["hid"],
                            "istatus" => "1",
                            "email" => $params["server"]["susername"],
                            "password" => $params["server"]["spassword"],
                            "hash" => $params["server"]["stoken"]
                        ]
                    ]);
                    $iplist = $response["ipaddresses"];
                    $ipcount = count($iplist);
                    if($ipcount < $item["iiunitcount"]){
                        return ["status" => false,"message" => "Özel yükseltim işleminde belirtilen adette stok bulunamadı!"];
                    }
                }
                $ipaddresses = [];
                $ipcounter = 0;
                foreach($iplist as $ipaddress){
                    $iid = (int)$ipaddress["iid"];
                    $iids["ip_".$iid] = $iid;
                    $ipaddresses[] = $ipaddress["iaddress"];
                    $ipcounter += 1;
                    if($ipcounter == $item["iiunitcount"]){
                        break;
                    }
                }
                $extensionname = $item["iiname"]."(".implode(",",$ipaddresses).")";
                UserProductExtensionsModel::beUpdate(["upename" => $extensionname])->beWhere("upeid",$upeid)->beExecute();
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "networkchangevm",
                    "data" => array_merge([
                        "vm_id" => $updata["vm_id"],
                        "onserver" => false,
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ],$iids)
                ]);
                break;
        }
        return ["status" => true,"message" => "Özel yükseltim işlemi başarılı bir şekilde tamamlandı!"];
    }
    public function diyovm_clientarea($params = []){
        /*return [
            "status" => true,
            "title" => "Sunucuyu Yönetimi",
            "content" => "Şuan otomasyon sistemimizde bakım yapılmaktadır, 1 saat içerisinde panel aktif olacaktır."
        ];*/
        $userproduct = $params["userproduct"];
        $productmodules = $params["productmodules"];
        $updata = json_decode($userproduct["updata"],true);
        $url = $params["url"];
        $page = $params["page"];
        beLanguage::beReadLang("diyovm");
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        $vm = $response["server"];
        $vm["sdata"] = json_decode($vm["sdata"],true);
        if($vm["sdata"]["formatting"] != 0){
            $updata["status"] = 1;
            $updata["taskid"] = $vm["sdata"]["formatting"];
            UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
            $content = beGetView("modules.diyovm.formatsteps",[
                "userproduct" => $userproduct
            ]);
            return [
                "status" => true,
                "title" => "Devam Eden İşlem",
                "content" => $content    
            ];
        }
        else{
            if($updata["status"] != 2){
                $updata["status"] = 2;
                UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
            }
        }
        $pages = $this->pages;
        if(!$productmodules["cpuprice"]){
            unset($pages["arttir"]["altmenu"]["cpu-arttir"]);
        }
        if(!$productmodules["ramprice"]){
            unset($pages["arttir"]["altmenu"]["ram-arttir"]);
        }
        if(!$productmodules["diskprice"]){
            unset($pages["arttir"]["altmenu"]["disk-arttir"]);
        }
        if($page){
            $pageinfo = $pages[$page];
            if($pageinfo){
                $params["title"] = $pageinfo["name"];
                NavController::beAddBreadcumb($pageinfo["name"]);
                $function = $pageinfo["function"];
                $content = $this->$function($params);
            }
            else{
                $found = false;
                foreach($pages as $key => $value){
                    if($value["altmenu"]){
                        foreach($value["altmenu"] as $altkey => $altvalue){
                            if($page == $altkey){
                                $found = true;
                                break 2;
                            }
                        }
                    }
                }
                if($found){
                    $pageinfo = $altvalue;
                    $params["title"] = $pageinfo["name"];
                    NavController::beAddBreadcumb($pageinfo["name"]);
                    $function = $pageinfo["function"];
                    $content = $this->$function($params);
                }
                else{
                    $content = "Bu sayfa bulunamadı!";
                }
            }
        }
        else{
            $invoice = null;
            $invoiceitem = InvoiceItemModel::beSelect("iid")->beWhere("iiobjectid",$userproduct["upid"])->beWhere("iiobject","ExtendOrder")->beOrder("iiid","DESC")->beLimit(1)->beGet();
            if($invoiceitem){
                $invoice = InvoiceModel::beSelect("iid,cid,iname,iprice")->beWhere("iid",$invoiceitem["iid"])->beWhere("istatus","0")->beGet();
            }
            $response = $this->beSendApiRequest([
                "apiurl" => $params["server"]["surl"],
                "method" => "getvm",
                "data" => [
                    "vm_id" => $updata["vm_id"],
                    "iplist" => true,
                    "snapshotlist" => true,
                    "templatelist" => true,
                    "logs" => true,
                    "rdnslist" => true,
                    "stats" => false,
                    "email" => $params["server"]["susername"],
                    "password" => $params["server"]["spassword"],
                    "hash" => $params["server"]["stoken"]
                ]
            ]);
            if(!$response["status"]){
                beError("Bir Sorun Oluştu",$response["message"]);
            }
            $vm = $response["server"];
            $vm["sdata"] = json_decode($vm["sdata"],true);
            $iplist = $response["iplist"];
            $snapshotlist = $response["snapshotlist"] ?? [];
            $templatelist = $response["templatelist"] ?? [];
            $logs = $response["logs"] ?? [];
            $rdnslist = $response["rdnslist"] ?? [];
            $rdnsiplist = [];
            foreach($rdnslist as $rdns){
                $rdnsiplist[$rdns["iid"]] = 1;
            }
            foreach($templatelist as $key => $template){
                if($vm["sdata"]["template"] == $template["tid"]){
                    $vm["sdata"]["templatename"] = $template["tname"];
                }
            }
            $upoptions = json_decode($userproduct["upoptions"],true);
            $currencie = CurrencyModel::beGetCurrencies("cicon",$userproduct["cid"]);
            $orderinfo = [
                "product" => $userproduct["pname"],
                "billingprice" => $upoptions["period"]["price"],
                "billingcycle" => ProductModel::beGetPeriods()[$upoptions["period"]["period"]],
                "regdate" => date("d.m.Y",$userproduct["upstime"]),
                "nextduedate" => date("d.m.Y",$userproduct["upntime"]),
                "amount" => $userproduct["upprice"],
                "currencie" => $currencie
            ];
            if(!$vm["sdata"]["stats"]["uptime"]){
                $vm["sdata"]["stats"]["uptime"] = 0;
            }
            if(!$vm["slastcheck"]){
                $vm["slastcheck"] = 0;
            }
            $formatcount = $updata["formatcount"];
            $formatcountnow = $updata["formatcountnow"];
            if(!$vm["sdata"]["config"]["password"] || $vm["sdata"]["config"]["password"] == "-"){
                $vm["sdata"]["config"]["password"] = beDecryptData($updata["password"]);
            }
            $vminfo = [
                "power" => $vm["sdata"]["stats"]["power_status"],
                "uptime" => round($vm["sdata"]["stats"]["uptime"]/60),
                "lastcheck" => round((time()-$vm["slastcheck"])/60),
                "templatename" => $vm["sdata"]["templatename"],
                "ipaddres" => $vm["sip"],
                "username" => $vm["sdata"]["config"]["username"],
                "password" => $vm["sdata"]["config"]["password"],
                "format" => [
                    "formatcountnow" => $formatcountnow,
                    "formatcount" => $formatcount
                ]
            ];
            $usageinfo = [
                "cpu_usage" => $vm["sdata"]["stats"]["cpu_mhz"],
                "cpu_max" => round($vm["sdata"]["settings"]["core"]*$vm["sdata"]["stats"]["cpu_hz"]*1000),
                "cpu_percent" => $vm["sdata"]["stats"]["cpu_percent"],
                "cpu_type" => "MHZ",
                "ram_usage" => $vm["sdata"]["stats"]["ram_mb"],
                "ram_max" => $vm["sdata"]["settings"]["ram"],
                "ram_percent" => $vm["sdata"]["stats"]["ram_percent"],
                "ram_type" => "MB",
                "disk_usage" => $vm["sdata"]["stats"]["disk_gb"],
                "disk_max" => $vm["sdata"]["settings"]["disk"],
                "disk_percent" => $vm["sdata"]["stats"]["disk_percent"],
                "network_usage" => $vm["sdata"]["stats"]["network"],
                "network_type" => "KB/sn"
            ];
            if($usageinfo["ram_usage"] > 1024){
                $usageinfo["ram_usage"] /= 1024;
                $usageinfo["ram_usage"] = round($usageinfo["ram_usage"],2);
                $usageinfo["ram_type"] = "GB";
            }
            if($usageinfo["cpu_usage"] > 1024){
                $usageinfo["cpu_usage"] /= 1000;
                $usageinfo["cpu_usage"] = round($usageinfo["cpu_usage"],2);
                $usageinfo["cpu_type"] = "GHZ";
            }
            if($usageinfo["cpu_percent"] > 60){
                $usageinfo["cpu_percent_color"] = "#f1416c";
            }
            else if($usageinfo["cpu_percent"] > 30){
                $usageinfo["cpu_percent_color"] = "#ffc700";
            }
            else{
                $usageinfo["cpu_percent_color"] = "#009ef7";
            }
            if($usageinfo["ram_percent"] > 60){
                $usageinfo["ram_percent_color"] = "#f1416c";
            }
            else if($usageinfo["ram_percent"] > 30){
                $usageinfo["ram_percent_color"] = "#ffc700";
            }
            else{
                $usageinfo["ram_percent_color"] = "#009ef7";
            }
            if($usageinfo["disk_percent"] > 60){
                $usageinfo["disc_percent_color"] = "#f1416c";
            }
            else if($usageinfo["disk_percent"] > 30){
                $usageinfo["disc_percent_color"] = "#ffc700";
            }
            else{
                $usageinfo["disc_percent_color"] = "#009ef7";
            }
            if($usageinfo["network_usage"] > 128){
                $usageinfo["network_usage"] = round($usageinfo["network_usage"]/128);
                $usageinfo["network_type"] = "MB/sn";
            }
            $passwordlogs = false;
            if($logs){
                foreach($logs as $log){
                    if($log["ltype"] == 13){
                        $passwordlogs = true;
                        break;
                    }
                }
            }
            $content = beGetView("modules.diyovm.show",[
                "url" => $url,
                "pages" => $pages,
                "userproduct" => $userproduct,
                "orderinfo" => $orderinfo,
                "invoice" => $invoice,
                "vminfo" => $vminfo,
                "usageinfo" => $usageinfo,
                "iplist" => $iplist,
                "snapshotlist" => $snapshotlist,
                "templatelist" => $templatelist,
                "logs" => $logs,
                "passwordlogs" => $passwordlogs,
                "rdnslist" => $rdnslist,
                "rdnsiplist" => $rdnsiplist
            ]);
        }
        $altmenu = [];
        if($updata["status"] == 2){
            $menuitems = [];
            foreach($pages as $pageurl => $data){
                if(!$data["showmenu"]){
                    continue;
                }
                if($data["altmenu"]){
                    foreach($data["altmenu"] as $key => $value){
                        $texturl = "";
                        if($key == "/"){
                            $texturl = $url;
                        }
                        else{
                            $texturl = $url."/".$key;
                        }
                        $data["altmenu"][$key]["url"] = $texturl;
                    }
                }
                $texturl = "";
                if($pageurl == "/"){
                    $texturl = $url;
                }
                else{
                    $texturl = $url."/".$pageurl;
                }
                $menuitems[] = [
                    "name" => $data["name"],
                    "icon" => $data["icon"],
                    "altmenu" => $data["altmenu"],
                    "url" => $texturl
                ];
            }
            $altmenu[] = [
                "name" => "Sunucu Yönetimi",
                "menuitems" => $menuitems
            ];
            if(isset($vminfo) && $vminfo["power"] == 1){
                $altmenu[] = [
                    "name" => "Sunucu İşlemleri",
                    "menuitems" => [
                        [
                            "name" => beGetLang("manage_stop"),
                            "icon" => "<i class=\"ri-stop-circle-line\"></i>",
                            "url" => "#",
                            "class" => "beCallRequestx",
                            "extra" => "data-method=\"power_action\" data-data=\"process=stop\""
                        ],
                        [
                            "name" => beGetLang("manage_restart"),
                            "icon" => "<i class=\"ri-restart-line\"></i>",
                            "url" => "#",
                            "class" => "beCallRequestx",
                            "extra" => "data-method=\"power_action\" data-data=\"process=restart\""
                        ],
                    ]
                ];
            }
            else{
                $altmenu[] = [
                    "name" => "Sunucu İşlemleri",
                    "menuitems" => [
                        [
                            "name" => beGetLang("manage_start"),
                            "icon" => "<i class=\"ri-play-line\"></i>",
                            "url" => "#",
                            "class" => "beCallRequestx",
                            "extra" => "data-method=\"power_action\" data-data=\"process=start\""
                        ]
                    ]
                ];
            }
        }
        return [
            "status" => true,
            "title" => "Sunucuyu Yönetimi",
            "content" => $content,
            "menus" => $altmenu
        ];
    }
    public function diyovm_clientarea_upgrade($params){
        $userproduct = $params["userproduct"];
        beRouter::beRedirect(beGetRoute("client.userproduct.userproduct.upgrade",["upid" => $userproduct["upid"]]));
    }
    public function diyovm_clientarea_password($params){
        $userproduct = $params["userproduct"];
        return beGetView("modules.diyovm.password",["userproduct" => $userproduct]); 
    }
    public function diyovm_clientarea_ipaddress($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "iplist" => true,
                "rdnslist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        $iplist = $response["iplist"];
        $rdnslist = $response["rdnslist"];
        return beGetView("modules.diyovm.iplist",["iplist" => $iplist,"rdnslist" => $rdnslist,"url" => $params["url"]]);
    }
    public function diyovm_clientarea_rdns_create($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "iplist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        $iplist = $response["iplist"];
        return beGetView("modules.diyovm.rdns-create",["iplist" => $iplist,"url" => $params["url"],"userproduct" => $userproduct]);
    }
    public function diyovm_clientarea_rdns_list($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "iplist" => true,
                "rdnslist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        $iplist = $response["iplist"];
        $rdnslist = $response["rdnslist"];
        $rdnsstatuslist = [
            -1 => [
                "name" => "Reddedildi",
                "color" => "up-btn-danger"
            ],
            1 => [
                "name" => "İşlemde",
                "color" => "up-btn-primary"
            ],
            2 => [
                "name" => "Aktif",
                "color" => "up-btn-success"
            ]
        ];
        return beGetView("modules.diyovm.rdnslist",["iplist" => $iplist,"rdnslist" => $rdnslist,"rdnsstatuslist" => $rdnsstatuslist,"url" => $params["url"],"userproduct" => $userproduct]);
    }
    public function diyovm_clientarea_rdns_edit($params){
        $rid = (int)$_GET["rid"];
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "iplist" => true,
                "rdnslist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        $rdns = [];
        foreach($response["rdnslist"] as $rdnslist){
            if($rdnslist["rid"] == $rid){
                $rdns = $rdnslist;
                break;
            }
        }
        if(!$rdns){
            beError("Bulunamadı","Belirtilen rDNS kaydı sistem üzerinde bulunamadı!");
        }
        $iplist = $response["iplist"];
        return beGetView("modules.diyovm.rdns-edit",["iplist" => $iplist,"rdns" => $rdns,"url" => $params["url"],"userproduct" => $userproduct]);
    }
    public function diyovm_clientarea_logs($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "logs" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        $logs = $response["logs"];
        return beGetView("modules.diyovm.logs",["logs" => $logs]);
    }
    public function diyovm_clientarea_format($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "templatelist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        $vm = $response["server"];
        $vm["sdata"] = json_decode($vm["sdata"],true);
        $templatelist = $response["templatelist"];
        $planid = (int)$params["productmodules"]["planid"];
        if($planid){
            $response = $this->beSendApiRequest([
                "apiurl" => $params["server"]["surl"],
                "method" => "getplans",
                "data" => [
                    "pid" => $planid,
                    "email" => $params["server"]["susername"],
                    "password" => $params["server"]["spassword"],
                    "hash" => $params["server"]["stoken"]
                ]
            ]);
            if(!$response["status"]){
                beError("Bir Sorun Oluştu",$response["message"]);
            }
            $plan = $response["plans"][0];
            if($plan["ptemplates"] != "-1"){
                $ptemplates = explode(",",$plan["ptemplates"]);
                foreach($templatelist as $key => $template){
                    if(!in_array($template["tid"],$ptemplates)){
                        unset($templatelist[$key]);
                    }
                }
            }
        }
        return beGetView("modules.diyovm.format",["templatelist" => $templatelist,"vmtemplateid" => $vm["sdata"]["template"],"userproduct" => $userproduct]); 
    }
    public function diyovm_clientarea_console($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getconsole",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "templatelist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        return beGetView("modules.diyovm.console",["console_url" => $response["url"]]); 
    }
public function diyovm_extra($params){
        beLanguage::beReadLang("diyovm");
        beLanguage::beReadLang("form");
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("order");
        $type = $_POST["type"];
        $count = (int)$_POST["count"];
        if($count < 1 || !in_array($type,["cpu","ram","disk","ip"])){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        global $be;
        $defcurrencie = $be->settings["system_currency"];
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $productmodules = $params["productmodules"];
        $itemprice = $productmodules[$type."price"];
        if(!$itemprice){
            return beAjaxError(["message" => beGetLang("extra_price_not_found")]);
        }
        if($defcurrencie != $userproduct["cid"]){
            $itemprice = beConvertCurrencie($itemprice,$defcurrencie,$userproduct["cid"]);
        }
        $upoptions = json_decode($userproduct["upoptions"],true);
        if(!in_array($upoptions["period"]["period"],["month","year"])){
            return beAjaxError(["message" => beGetLang("order_upgrade_disabled")]);
        }
        $remainingtime = ($userproduct["upetime"]-BE_TIME)/ProductModel::beGetPeriodsTimes()["day"];
        $newitemprice = round($itemprice*$remainingtime/30,2);
        $alltimeprice = round($itemprice*$upoptions["period"]["periodcounter"]*ProductModel::beGetPeriodsTimes()[$upoptions["period"]["period"]]/ProductModel::beGetPeriodsTimes()["month"],2);
        if($type == "ip"){
            $ipplanid = $productmodules["ipplanid"];
            if($ipplanid){
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "getipaddresses",
                    "data" => [
                        "igid" => $ipplanid,
                        "istatus" => "1",
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                $ipcount = count($response["ipaddresses"]);
                if($ipcount < $count){
                    return beAjaxError(["message" => beGetLang("extra_count_to_much",["count" => $count,"maximum" => $ipcount])]);
                }
            }
            else{
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "getvm",
                    "data" => [
                        "vm_id" => $updata["vm_id"],
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                $vm = $response["server"];
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "getipaddresses",
                    "data" => [
                        "hid" => $vm["hid"],
                        "istatus" => "1",
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                $ipcount = count($response["ipaddresses"]);
                if($ipcount < $count){
                    return beAjaxError(["message" => beGetLang("extra_count_to_much",["count" => $count,"maximum" => $ipcount])]);
                }
            }
        }
        $iid = InvoiceModel::beCreateModuleInvoice([
            "cid" => $userproduct["cid"],
            "uid" => $userproduct["uid"],
            "iname" => beGetLang("invoice_order_upgrade_name"),
            "idescription" => beGetLang("invoice_order_upgrade_name"),
            "iexpiredate" => BE_TIME+86400*3,
            "itaxrate" => $userproduct["uptaxrate"],
            "items" => [
                [
                    "upid" => $userproduct["upid"],
                    "name" => beGetLang("extra_".$type),
                    "price" => $newitemprice,
                    "count" => $count,
                    "data" => [
                        "alltimeprice" => $alltimeprice*$count,
                        "newitemprice" => $newitemprice,
                        "itemprice" => $itemprice,
                        "type" => $type,
                    ]
                ]
            ]
        ]);
        return beAjaxSuccess(["message" => beGetLang("invoice_created"),"url" => beGetRoute("client.invoice.invoice",["iid" => $iid])]);
    }
    public function diyovm_clientarea_extra_cpu($params){
        return $this->diyovm_clientarea_extra_show($params,"cpu");
    }
    public function diyovm_clientarea_extra_ram($params){
        return $this->diyovm_clientarea_extra_show($params,"ram");
    }
    public function diyovm_clientarea_extra_disk($params){
        return $this->diyovm_clientarea_extra_show($params,"disk");
    }
    public function diyovm_clientarea_extra_ip($params){
        return $this->diyovm_clientarea_extra_show($params,"ip");
    }
    public function diyovm_clientarea_extra_show($params,$type){
        global $be;
        $defcurrencie = $be->settings["system_currency"];
        $userproduct = $params["userproduct"];
        $productmodules = $params["productmodules"];
        $price = $productmodules[$type."price"];
        if(!$price){
            beError("DIYOVM",beGetLang("extra_price_not_found"));
        }
        if($defcurrencie != $userproduct["cid"]){
            $price = beConvertCurrencie($price,$defcurrencie,$userproduct["cid"]);
        }
        $currencie = CurrencyModel::beGetCurrencies("cid,cicon",$userproduct["cid"]);
        return beGetView("modules.diyovm.extra",["type" => $type,"price" => $price,"currencie" => $currencie,"userproduct" => $userproduct]); 
    }
    public function diyovm_clientarea_snapshot($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "snapshotlist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            beError("Bir Sorun Oluştu",$response["message"]);
        }
        $vm = $response["server"];
        $vm["sdata"] = json_decode($vm["sdata"],true);
        $snapshotlist = $response["snapshotlist"] ?? [];
        return beGetView("modules.diyovm.snapshot",["snapshotlist" => $snapshotlist,"userproduct" => $userproduct]); 
    }
    public function diyovm_power_action($params){
        $user = Auth::beGetUser();
        beLanguage::beReadLang("usergroup");
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $process = $_POST["process"];
        if(!in_array($process,["stop","start","restart"])){
            return beAjaxSuccess(["message" => "Belirtilen işlem izinli işlemler arasında bulunmuyor!"]);
        }
        if($userproduct["uid"] != $user["uid"] && !beCheckPermission("diyovm_process_".$process,0)){
            return beAjaxSuccess(["message" => beGetLang("usergroup_permission_denied",["permission" => "diyovm_process_".$process])]);
        }
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "statusaction",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "action" => $process,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => $response["message"]]);
    }
    public function diyovm_password_change($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $password = $_POST["password"];
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "passwordvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "onserver" => true,
                "password_vm" => $password,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        $updata["password"] = beEncryptData($password);
        UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
        return beAjaxSuccess(["message" => $response["message"]]);
    }
    public function diyovm_rnds_create($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "createrdnsrecord",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "iid" => (int)$_POST["iid"],
                "type" => $_POST["type"],
                "dns" => $_POST["dns"],
                "priority" => (int)$_POST["priority"],
                "ttl" => (int)$_POST["ttl"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        return json_encode($response,JSON_UNESCAPED_UNICODE);
    }
    public function diyovm_rnds_edit($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "editrdnsrecord",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "rid" => (int)$_POST["rid"],
                "iid" => (int)$_POST["iid"],
                "type" => $_POST["type"],
                "dns" => $_POST["dns"],
                "priority" => (int)$_POST["priority"],
                "ttl" => (int)$_POST["ttl"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        return json_encode($response,JSON_UNESCAPED_UNICODE);
    }
    public function diyovm_rnds_delete($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "deleterdnsrecord",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "rid" => (int)$_POST["rid"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        return json_encode($response,JSON_UNESCAPED_UNICODE);
    }
    public function diyovm_snapshot_create($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "snapshotlist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        $snapshotlist = $response["snapshotlist"] ?? [];
        if(count($snapshotlist) >= $params["productmodules"]["snapshot"]){
            return beAjaxError(["message" => "Maksimum yedek sayısına ulaştınız!"]);
        }
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "createsnapshot",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => $response["message"]]);
    }
    public function diyovm_snapshot_deploy($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $ssid = (int)$_POST["ssid"];
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "deploysnapshot",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "ssid" => $ssid,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => $response["message"]]);
    }
    public function diyovm_snapshot_delete($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $ssid = (int)$_POST["ssid"];
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "deletesnapshot",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "ssid" => $ssid,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => $response["message"]]);
    }
    public function diyovm_entegration($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $type = $_POST["type"];
        switch($type){
            case "network" : 
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "networkvm",
                    "data" => [
                        "vm_id" => $updata["vm_id"],
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                break;
            case "disk" :
                $response = $this->beSendApiRequest([
                    "apiurl" => $params["server"]["surl"],
                    "method" => "diskvm",
                    "data" => [
                        "vm_id" => $updata["vm_id"],
                        "email" => $params["server"]["susername"],
                        "password" => $params["server"]["spassword"],
                        "hash" => $params["server"]["stoken"]
                    ]
                ]);
                break;
            default:
                return beAjaxError(["message" => "Belirtilen işlem bulunamadı!"]);
        }
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => $response["message"]]);
    }
    public function diyovm_format($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        if($updata["status"] != 2){
            return beAjaxError(["message" => "Sunucunuzuz bu işlem için kurulu olması gerek!"]);
        }
        if(!$_POST["approval"]){
            return beAjaxError(["message" => "Lütfen tüm bilgilerinizin siliniceğini onaylayın!"]);
        }
        $formatcountnow = $updata["formatcountnow"] ?? 0;
        $formattimefirst = $updata["firsttime"] ?? 0;
        $defaultformat = $updata["formatcount"] ?? 3;
        $timenow = time();
        if($defaultformat > 0){
            if($formatcountnow >= $defaultformat){
                if($timenow-$formattimefirst < 2592000){
                    return beAjaxError(["message" => "Bir ay içerisinde tüm format haklarınızı kullandınız tekrardan dolmasına: ".(round(($timenow-$formattimefirst+2592000)/86400))." gün kaldı!"]);
                }
                else{
                    $updata["formatcount"] = 0;
                    $updata = $timenow;
                    UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
                }
            }
            else{
                if(!$formattimefirst){
                    $updata["formatcount"] = $timenow;
                }
                $updata["formatcountnow"]  += 1;
                UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
            }
        }
        $tid = (int)$_POST["tid"];
        $password = $_POST["password"];
        $planid = (int)$params["productmodules"]["planid"];
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "templatelist" => true,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        $vm = $response["server"];
        $vm["sdata"] = json_decode($vm["sdata"],true);
        $templatelist = $response["templatelist"];
        if($planid){
            $response = $this->beSendApiRequest([
                "apiurl" => $params["server"]["surl"],
                "method" => "getplans",
                "data" => [
                    "pid" => $planid,
                    "email" => $params["server"]["susername"],
                    "password" => $params["server"]["spassword"],
                    "hash" => $params["server"]["stoken"]
                ]
            ]);
            if(!$response["status"]){
                return beAjaxError(["message" => $response["message"]]);
            }
            $plan = $response["plans"][0];
            if($plan["ptemplates"] != "-1"){
                $ptemplates = explode(",",$plan["ptemplates"]);
                foreach($templatelist as $key => $template){
                    if(!in_array($template["tid"],$ptemplates)){
                        unset($templatelist[$key]);
                    }
                }
            }
        }

        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "formatvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "template" => $tid,
                "password_vm" => $password,
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        $updata["status"] = 1;
        $updata["password"] = beEncryptData($password);
        $updata["taskid"] = $response["taskid"];
        UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
        return beAjaxSuccess(["message" => $response["message"],"refresh" => 1]);
    }
    public function diyovm_format_trigger($params){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://{$params["server"]["surl"]}/app/tasks/createserver.php");
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_exec($ch);
        curl_close($ch);
        return beAjaxSuccess(["message" => "İşlem tetiklendi!"]);
    }
    public function diyovm_format_step($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "gettask",
            "data" => [
                "taskid" => $updata["taskid"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        $task = $response["task"];
        $laststep = (int)$_POST["laststep"];
        $steps = [
            0 => "Siliniyor!",
            1 => "Kurulum için hazırlanıyor!",
            2 => "Kurulum yapılıyor",
            3 => "Disk Ayarlanıyor",
            4 => "Sunucu Başlatılıyor",
            5 => "Ip adresleri tanımlanıyor!"
        ];
        if($task["tstatus"] == 0){
            $updata["status"] = 2;
            UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
            return beAjaxSuccess(["refresh" => 1]);
        }
        $tdata = json_decode($task["tdata"],true);
        $stepnow = $tdata["status"]["step"];
        if($laststep == $stepnow){
            if($stepnow == 2){
                return beAjaxSuccess(["percent" => $tdata["vars"]["percent"]]);
            }
            return beAjaxSuccess(["stepnow" => $stepnow]);
        }
        $start = 1;
        if($stepnow == 14){
            $start = 0;
            $stepnow = 0;
        }
        $stepscontent = "";
        for($i = $start; $i < 6; $i++){
            if($stepnow > $i){
                $stepscontent .= "<li class=\"maked\"><span>{$steps[$i]}</span><i class=\"ri-check-double-line\"></i></li>";
            }
            else if($stepnow == $i){
                $activestep = $steps[$i];
                if($i == 2){
                    $extradata = " <span class=\"percentServer\">%".$tdata["vars"]["percent"]."</span>";
                }
                $stepscontent .= "<li class=\"active\"><span>{$activestep}{$extradata}</span><i class=\"ri-edit-circle-line\"></i></li>";
            }
            else{
                $stepscontent .= "<li class=\"waiting\"><span>{$steps[$i]}</span><i class=\"ri-git-pull-request-fill\"></i></li>";
            }
        }
        return beAjaxSuccess(["steps" => $stepscontent,"steptext" => $activestep,"stepnow" => $stepnow,"data" => $tdata]);
    }
    public function diyovm_check_stat($params){
        $userproduct = $params["userproduct"];
        $updata = json_decode($userproduct["updata"],true);
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://{$params["server"]["surl"]}/app/tasks/statserver.php?vmlist={$updata['vm_id']}");
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_exec($ch);
        curl_close($ch);
        $response = $this->beSendApiRequest([
            "apiurl" => $params["server"]["surl"],
            "method" => "getvm",
            "data" => [
                "vm_id" => $updata["vm_id"],
                "email" => $params["server"]["susername"],
                "password" => $params["server"]["spassword"],
                "hash" => $params["server"]["stoken"]
            ]
        ]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        $vm = $response["server"];
        $vm["sdata"] = json_decode($vm["sdata"],true);
        $usageinfo = [
            "cpu_usage" => $vm["sdata"]["stats"]["cpu_mhz"],
            "cpu_max" => round($vm["sdata"]["settings"]["core"]*$vm["sdata"]["stats"]["cpu_hz"]*1000),
            "cpu_percent" => $vm["sdata"]["stats"]["cpu_percent"],
            "cpu_type" => "MHZ",
            "ram_usage" => $vm["sdata"]["stats"]["ram_mb"],
            "ram_max" => $vm["sdata"]["settings"]["ram"],
            "ram_percent" => $vm["sdata"]["stats"]["ram_percent"],
            "ram_type" => "MB",
            "disk_usage" => $vm["sdata"]["stats"]["disk_gb"],
            "disk_max" => $vm["sdata"]["settings"]["disk"],
            "disk_percent" => $vm["sdata"]["stats"]["disk_percent"],
            "network_usage" => $vm["sdata"]["stats"]["network"],
            "network_type" => "KB/sn"
        ];
        if($usageinfo["ram_usage"] > 1024){
            $usageinfo["ram_usage"] /= 1024;
            $usageinfo["ram_usage"] = round($usageinfo["ram_usage"],2);
            $usageinfo["ram_type"] = "GB";
        }
        if($usageinfo["cpu_usage"] > 1024){
            $usageinfo["cpu_usage"] /= 1000;
            $usageinfo["cpu_usage"] = round($usageinfo["cpu_usage"],2);
            $usageinfo["cpu_type"] = "GHZ";
        }
        if($usageinfo["cpu_percent"] > 60){
            $usageinfo["cpu_percent_color"] = "#f1416c";
        }
        else if($usageinfo["cpu_percent"] > 30){
            $usageinfo["cpu_percent_color"] = "#ffc700";
        }
        else{
            $usageinfo["cpu_percent_color"] = "#009ef7";
        }
        if($usageinfo["ram_percent"] > 60){
            $usageinfo["ram_percent_color"] = "#f1416c";
        }
        else if($usageinfo["ram_percent"] > 30){
            $usageinfo["ram_percent_color"] = "#ffc700";
        }
        else{
            $usageinfo["ram_percent_color"] = "#009ef7";
        }
        if($usageinfo["disk_percent"] > 60){
            $usageinfo["disc_percent_color"] = "#f1416c";
        }
        else if($usageinfo["disk_percent"] > 30){
            $usageinfo["disc_percent_color"] = "#ffc700";
        }
        else{
            $usageinfo["disc_percent_color"] = "#009ef7";
        }
        return beAjaxSuccess($usageinfo);
    }
    public function diyovm_change_status($params = []){
        $userproduct = $params["userproduct"];
        $status = $params["module_vars"]["status"];
        $updata = json_decode($userproduct["updata"],true);
        $response = $this->beSendApiRequest([
            "method" => "getclients",
            "data" => [
                "cids" => $updata["cid"],
                "selectdata" => "cid"
            ]
        ]);
        if(!$response["status"]){
            return ["status" => false,"message" => $response["message"]];
        }
        $response = $this->beSendApiRequest([
            "method" => "setstatusclient",
            "data" => [
                "cid" => $updata["cid"],
                "cstatus" => $status
            ]
        ]);
        if(!$response["status"]){
            return ["status" => false,"message" => $response["message"]];
        }
        $updata["status"] = $status == 1 ? 2:-1;
        UserProductModel::beUpdate(["updata" => json_encode($updata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
        return ["status" => true,"message" => "Başarılı bir şekilde lisansın durumu değiştirildi"];
    }
    public function beSendApiRequest($data = []){
        $data["data"]["ipaddress"] = $_SERVER["SERVER_ADDR"];
        if(!$data["data"]["ipaddress"]){
            $data["data"]["ipaddress"] = "0.0.0.0";
        }
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://{$data['apiurl']}/api/{$data['method']}");
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data["data"]));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response,true);
    }
}
?>