<?php

    namespace App\System\Plugin;
    use App\System\Basic\beRouter;
    use App\System\Model\CurrencyModel;
    use App\System\Model\ProductAddonTranslationsModel;
    use App\System\Model\ProductModel;
use App\System\Model\SettingGroupsModel;
use App\System\Model\SettingModel;
use App\System\Vendor\Auth;
    use App\System\Vendor\beLanguage;
    use App\System\Vendor\beModule;
use App\System\Vendor\bePlugin;

    class domain {
        public function plugin_info(){
            return [
                "name" => "Alan Adı Eklentisi",
                "description" => "Alan adı sayfasının ve modüllerinin çalışmasını sağlar",
                "version" => "1.0",
                "vercode" => 1,
                "author" => "ITenGriTR"
            ];
        }
        public function plugin_hooks(){
            return [
                "routes_start" => "my_routes_insert",
                "task_currency_post" => "my_task_currency_post"
            ];
        }
        public function plugin_install(){
            $sgid = bePlugin::beCreateSettingGroup("domain","Alan Adı Eklentisi","Alan adı sistemi için gerekli ayarları yükler");
            bePlugin::beCreateSetting($sgid,"domain_status","Durum","Alan adı sisteminin durumunu belirler","select\n0=Kapalı\n1=Açık","1");
            bePlugin::beCreateSetting($sgid,"domain_auto_price","Otomatik Fiyatlandırma","Alan adı modülünüz destekliyor ise fiyatları otomatik olarak güneller","select\n0=Kapalı\n1=Açık","1");
            bePlugin::beCreateSetting($sgid,"domain_ratio","Kar Oranı","Alan adı sistemi üzerinde otomatik moddayken fiyatların üstüne koyulacak kazanç oranı","int","10");
            return ["status" => true];
        }
        public function plugin_active(){
            $setting = SettingModel::beSelect("sid")->beWhere("scode","domain_status")->beGet();
            if(!$setting){
                $sgid = bePlugin::beCreateSettingGroup("domain","Alan Adı Eklentisi","Alan adı sistemi için gerekli ayarları yükler");
                bePlugin::beCreateSetting($sgid,"domain_status","Durum","Alan adı sisteminin durumunu belirler","select\n0=Kapalı\n1=Açık","1");
                bePlugin::beCreateSetting($sgid,"domain_auto_price","Otomatik Fiyatlandırma","Alan adı modülünüz destekliyor ise fiyatları otomatik olarak güneller","select\n0=Kapalı\n1=Açık","1");
                bePlugin::beCreateSetting($sgid,"domain_ratio","Kar Oranı","Alan adı sistemi üzerinde otomatik moddayken fiyatların üstüne koyulacak kazanç oranı","int","10");
            }
            return ["status" => true];
        }
        public function plugin_remove(){
            $sgid = SettingGroupsModel::beSelect("sgid")->beWhere("sgcode","domain")->beGet()["sgid"];
            SettingGroupsModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            SettingModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            return ["status" => true];
        }
        public function my_routes_insert(){
            beRouter::bePrefix("/doamin","domain.")->beGroup(function(){
                beRouter::beRoute("/check-domain","domain@checkdomain_post","post")->beName("check.domain.post")->beSpecial();
            });
        }
        public function checkdomain_post(){
            beLanguage::beReadLang("module");
            $domain = explode(".",$_POST["domain"])[0];
            $domains = [];
            $user = Auth::beGetUser();
            $addon = ProductAddonTranslationsModel::beSelect("patid,paid,paoptions")->beWhere("lid",$user["lid"])->beWhere("pacode","domain_extension")->beGet();
            $extensions = json_decode($addon["paoptions"],true);
            foreach($extensions as $extension){
                $domains[] = $domain.$extension["oname"];
            }
            $modules = beModule::beLoadModules("product");
            $module = "";
            foreach($modules as $key => $data){
                if($data["info"]["type"] == "domain" && $data["info"]["status"] == 1){
                    $module = $key;
                    break;
                }
            }
            if(!$module){
                return beAjaxError(["message" => beGetLang("module_not_found")]);
            }
            if(!beModule::beCheckModuleFunction($module,"checkdomain")){
                return beAjaxError(["message" => beGetLang("module_not_support")]);
            }
            $response = beModule::beRunModuleFunction($module,"checkdomain",$domains);
            if(!$response["status"]){
                return beAjaxError(["message" => beGetLang("module_function_error")]);
            }
            $product = ProductModel::beTable("be_products as p")->beSelect("p.pid,pt.pslug")->beWhere("p.pmodule",$key)->beWhere("pt.lid",$user["lid"])->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = p.pid")->beGet();
            $domains = $response["domains"];
            $localcurrencies = CurrencyModel::beGetCurrencies("cid,ccode,cname,cicon",0,"ccode");
            $currencies = [];
            foreach($localcurrencies as $currnecy){
                $currencies[$currnecy["cid"]] = $currnecy;
            }
            foreach($domains as $domainkey => $domain){
                $currnecy = $localcurrencies[$domain["currency"]];
                $cid = $currnecy["cid"];
                foreach($extensions as $extensionkey => $extension){
                    if($domain["extension"] != $extension["oname"]){
                        continue;
                    }
                    if($extension["ocid"] != $cid){
                        $extensionprice = CurrencyModel::beConvertCurrencie($domain["price"],$cid,$extension["ocid"]);
                        if($extensionprice > $extension["oprice"]){
                            $extensions[$extensionkey]["oprice"] = $extensionprice;
                            ProductAddonTranslationsModel::beUpdate(["paoptions" => json_encode($extensions,JSON_UNESCAPED_UNICODE)])->beWhere("patid",$addon["patid"])->beExecute();
                        }
                        else{
                            $extensionprice = $extension["oprice"];
                        }
                        $domains[$domainkey]["price"] = $extensionprice;
                        $domains[$domainkey]["currency"] = $currencies[$extension["ocid"]];
                    }
                    else{
                        $domains[$domainkey]["currency"] = $currencies[$extension["ocid"]];
                    }
                    if($domains[$domainkey]["price"] < $extension["oprice"]){
                        $domains[$domainkey]["price"] = $extension["oprice"];
                    }
                    $domains[$domainkey]["price"] = beMoneyFormat($domains[$domainkey]["price"]);
                }
            }
            return beAjaxSuccess(["domains" => $domains,"producturl" => beGetRoute("product.product",["slug" => $product["pslug"]])]);
        }
        public function my_task_currency_post(){
            beLanguage::beReadLang("module");
            $settings = SettingModel::beGetSettings("domain_auto_price,domain_ratio");
            if(!$settings["domain_auto_price"]){
                return;
            }
            $extensionaddons = ProductAddonTranslationsModel::beSelect("patid,paoptions")->beWhere("pacode","domain_extension")->beGetAll();
            $modules = beModule::beLoadModules("product");
            $module = "";
            foreach($modules as $key => $data){
                if($data["info"]["type"] == "domain" && $data["info"]["status"] == 1){
                    $module = $key;
                    break;
                }
            }
            if(!$module){
                return beAjaxError(["message" => beGetLang("module_not_found")]);
            }
            if(!beModule::beCheckModuleFunction($module,"tldlist")){
                return beAjaxError(["message" => beGetLang("module_not_support")]);
            }
            $response = beModule::beRunModuleFunction($module,"tldlist",844);
            if(!$response["status"]){
                return beAjaxError(["message" => beGetLang("module_function_error")]);
            }
            $currencyusd = CurrencyModel::beSelect("cid")->beWhere("ccode","USD")->beGet();
            foreach($extensionaddons as $addon){
                $paoptions = json_decode($addon["paoptions"],true);
                foreach($paoptions as $key => $option){
                    $oname  = substr($option["oname"],1);
                    $mainextension = $response["extensions"][$oname];
                    if(!$mainextension){
                        continue;
                    }
                    $price = floatval($mainextension["prices"]["Registration"]);
                    if($option["ocid"] != 2){
                        $price = beConvertCurrencie($price,$currencyusd["cid"],$option["ocid"]);
                    }
                    $price = round($price*(100+$settings["domain_ratio"])/100,2);
                    $paoptions[$key]["oprice"] = $price;
                }
                ProductAddonTranslationsModel::beUpdate(["paoptions" => json_encode($paoptions,JSON_UNESCAPED_UNICODE)])->beWhere("patid",$addon["patid"])->beExecute();
            }
        }
    }
?>