<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Model\CurrencyModel;
use App\System\Model\LanguageModel;
use App\System\Model\ProductAddonGroupModel;
use App\System\Model\ProductAddonsModel;
use App\System\Model\ProductAddonTranslationsModel;
use App\System\Model\ProductCategoriesModel;
use App\System\Model\ProductModel;
use App\System\Model\ProductModulesModel;
use App\System\Model\ProductTranslationsModel;
use App\System\Model\ServerModel;
use App\System\Model\SettingModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beModule;
use App\System\Vendor\beUpload;

class ProductController extends beContoller {
    public function list(){
        beLanguage::beReadLang("product");
        $user = Auth::beGetUser();
        $products = ProductModel::beSelect("be_products.pid,pt.pname,pt.pdescription,pstock,pactive,psold,pmodule,pdateline")->beWhere("pt.lid",$user["lid"])->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGetAll();
        beModule::beLoadModules("product");
        return beGetView("admin.product.list",["products" => $products,"modules" => beModule::$beModules]);
    }
    public function add(){
        beLanguage::beReadLang("product");
        $categories = ProductCategoriesModel::beSelect("pcid,pcname")->beGetAll();
        return beGetView("admin.product.add",["categories" => $categories]);
    }
    public function add_post(){
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("category");
        beLanguage::beReadLang("form");
        global $be;
        $name = $_POST["name"];
        $categories = $_POST["categories"];
        $stock = (int)$_POST["stock"];
        if(empty($name)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $file = $_FILES["image"];
        $fileurl = "";
        if($file["name"]){
            $upload = beUpload::beUploadFile($file,str_replace(" ","",$file["name"]),BE_ROOT."assets/product",0,null,false);
            if(!$upload["status"]){
                return beAjaxError(["message" => $upload["message"]." yüklenemedi!"]);
            }
            $fileurl = "assets/product/".$upload["filename"];
        }
        else{
            $fileurl = "assets/media/icons/emptyproduct.png";
        }
        $pcids = [];
        foreach($categories as $pcid){
            $category = ProductCategoriesModel::beSelect("pcid")->beWhere("pcid",$pcid)->beGet();
            if($category){
                $pcids[] = (int)$category["pcid"];
            }
        }
        $pid = ProductModel::beInsert([
            "pcids" => json_encode($pcids),
            "pperiods" => "{\"1\":{\"1\":{\"operiodtime\":\"1\",\"operiod\":\"month\",\"oprice\":\"0\",\"odiscount\":\"0\",\"ocid\":\"1\"}}}",
            "pimage" => $fileurl,
            "pstock" => $stock,
            "pstocktype" => "unlimited",
            "pterminatetype" => "terminate",
            "pupdatedateline" => BE_TIME,
            "pdateline" => BE_TIME
        ]);
        $systemlid = $be->settings["system_language"];
        ProductTranslationsModel::beInsert([
            "lid" => $systemlid,
            "pid" => $pid,
            "pname" => $name,
            "pslug" => beSelfLink($name)
        ]);
        return beAjaxSuccess(["message" => beGetLang("product_created"),"url" => beGetRoute("admin.product.show",["pid" => $pid])]);
    }
    public function copy($pid){
        beLanguage::beReadLang("product");
        $product = ProductModel::beSelect("be_products.pid,be_products.pcids,be_products.pstock,pt.pname")->beWhere("be_products.pid",$pid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGet();
        if(!$product){
            beError(beGetLang("product"),beGetLang("product_not_found"));
        }
        $product["pcids"] = json_decode($product["pcids"],true);
        $categories = ProductCategoriesModel::beSelect("pcid,pcname")->beGetAll();
        return beGetView("admin.product.copy",["product" => $product,"categories" => $categories]);
    }
    public function copy_post(){
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("category");
        beLanguage::beReadLang("form");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $name = $_POST["name"];
        $categories = $_POST["categories"];
        $stock = (int)$_POST["stock"];
        if(empty($name)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $file = $_FILES["image"];
        if($file["name"]){
            $upload = beUpload::beUploadFile($file,str_replace(" ","",$file["name"]),BE_ROOT."assets/product",0,null,false);
            if(!$upload["status"]){
                return beAjaxError(["message" => $upload["message"]." yüklenemedi!"]);
            }
            $fileurl = "assets/product/".$upload["filename"];
        }
        else{
            $fileurl = $product["pimage"];
        }
        $pcids = [];
        foreach($categories as $pcid){
            $category = ProductCategoriesModel::beSelect("pcid")->beWhere("pcid",$pcid)->beGet();
            if($category){
                $pcids[] = (int)$category["pcid"];
            }
        }
        $pid = ProductModel::beInsert([
            "pcids" => json_encode($pcids),
            "sid" => $product["sid"],
            "pperiods" => $product["pperiods"],
            "pimage" => $fileurl,
            "paddons" => $product["paddons"],
            "pstock" => $stock,
            "pstocktype" => "unlimited",
            "pterminatetype" => "terminate",
            "pextend" => $product["pextend"],
            "pextendauto" => $product["pextendauto"],
            "pextendmanuel" => $product["pextendmanuel"],
            "psecret" => $product["psecret"],
            "poverageinvoice" => $product["poverageinvoice"],
            "pmodule" => $product["pmodule"],
            "pupdatedateline" => BE_TIME,
            "pdateline" => BE_TIME
        ]);
        $languages = LanguageModel::beGetLanguages("lid");
        $categorycontroller = new CategoryController();
        foreach($languages as $language){
            $producttranslation = ProductTranslationsModel::beWhere("pid",$product["pid"])->beWhere("lid",$language["lid"])->beGet();
            if($producttranslation){
                ProductTranslationsModel::beInsert([
                    "lid" => $language["lid"],
                    "pid" => $pid,
                    "pname" => $name,
                    "pdescription" => $producttranslation["pdescription"],
                    "pmetadescription" => $producttranslation["pmetadescription"],
                    "pmetakeywords" => $producttranslation["pmetakeywords"],
                    "pfeatures" => $producttranslation["pfeatures"],
                    "pslug" => beSelfLink($name)
                ]);   
                if($pcids){
                    $languages = LanguageModel::beGetLanguages("lid");
                    $categorycontroller = new CategoryController();
                    foreach($pcids as $pcid){
                        $categorycontroller->beRender($language["lid"],$pcid);
                    }
                }
            } 
        }
        $productmodules = ProductModulesModel::beWhere("pid",$product["pid"])->beGetAll();
        foreach($productmodules as $productmodule){
            ProductModulesModel::beInsert([
                "pid" => $pid,
                "pmmodule" => $productmodule["pmmodule"],
                "pmmodulekey" => $productmodule["pmmodulekey"],
                "pmvalue" => $productmodule["pmvalue"],
                "pmdateline" => $productmodule["pmdateline"]
            ]);
        }
        return beAjaxSuccess(["message" => beGetLang("product_copied"),"url" => beGetRoute("admin.product.show",["pid" => $pid])]);
    }
    public function delete_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        ProductModel::beDelete()->beWhere("pid",$product["pid"])->beExecute();
        ProductTranslationsModel::beDelete()->beWhere("pid",$product["pid"])->beExecute();
        ProductModulesModel::beDelete()->beWhere("pid",$product["pid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("product_deleted")]);
    }
    public function show($pid){
        global $be;
        beLanguage::beReadLang("product");
        $user = Auth::beGetUser();
        $product = ProductModel::beWhere("pid",$pid)->beGet();
        if(!$product){
            beError(beGetLang("product"),beGetLang("product_not_found"));
        }
        $categories = ProductCategoriesModel::beSelect("pcid,pcname")->beGetAll();
        $servers = ServerModel::beSelect("sid,sname")->beGetAll();
        $producttranslations = ProductTranslationsModel::beWhere("pid",$product["pid"])->beGetAll();
        $product["paddons"] = json_decode($product["paddons"],true);
        $product["pperiods"] = json_decode($product["pperiods"],true);
        $product["pcids"] = json_decode($product["pcids"],true);
        $product["pupgradeproducts"] = json_decode($product["pupgradeproducts"],true);
        $productaddongroups = ProductAddonGroupModel::beGetAll();
        $productaddons = ProductAddonTranslationsModel::beSelect("be_product_addon_translations.paid,patid,lid,paname,pa.pagid")->beJoin("INNER JOIN be_product_addons as pa ON pa.paid = be_product_addon_translations.paid")->beGetAll();
        $products = ProductModel::beTable("be_products as p")->beSelect("p.pid,pt.pname")->beWhere("pt.lid",$user["lid"])->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = p.pid")->beGetAll();
        $modules = beModule::beLoadModules("product");
        $languages = LanguageModel::beGetLanguages("lid,lname,lcode");
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $systemlid = $be->settings["system_language"];
        $systemcid = $be->settings["system_currency"];
        return beGetView("admin.product.show",["products" => $products,"product" => $product,"categories" => $categories,"servers" => $servers,"producttranslations" => $producttranslations,"productaddongroups" => $productaddongroups,"productaddons" => $productaddons,"modules" => $modules,"languages" => $languages,"currencies" => $currencies,"systemlid" => $systemlid]);
    }
    public function infosave_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid,pcids")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $product["pcids"] = json_decode($product["pcids"],true);
        $languages = LanguageModel::beGetLanguages("lid");
        $categorycontroller = new CategoryController();
        foreach($languages as $language){
            $pname = $_POST["pname"][(int)$language["lid"]];
            if($pname){
                $producttranslation = ProductTranslationsModel::beSelect("ptid")->beWhere("lid",$language["lid"])->beWhere("pid",$product["pid"])->beGet();
                if($producttranslation){
                    ProductTranslationsModel::beUpdate([
                        "pname" => $pname,
                        "pdescription" => $_POST["pdescription"][(int)$language["lid"]],
                        "pmetadescription" => htmlspecialchars($_POST["pmetadescription"][(int)$language["lid"]]),
                        "pmetakeywords" => htmlspecialchars($_POST["pmetakeywords"][(int)$language["lid"]]),
                        "pfeatures" => $_POST["pfeatures"][(int)$language["lid"]],
                        "pslug" => !$_POST["pslug"][(int)$language["lid"]] ? beSelfLink($pname):$_POST["pslug"][(int)$language["lid"]]
                    ])->beWhere("ptid",$producttranslation["ptid"])->beExecute();
                }
                else{
                    ProductTranslationsModel::beInsert([
                        "lid" => $language["lid"],
                        "pid" => $product["pid"],
                        "pname" => $pname,
                        "pdescription" => $_POST["pdescription"][(int)$language["lid"]],
                        "pmetadescription" => htmlspecialchars($_POST["pmetadescription"][(int)$language["lid"]]),
                        "pmetakeywords" => htmlspecialchars($_POST["pmetakeywords"][(int)$language["lid"]]),
                        "pfeatures" => $_POST["pfeatures"][(int)$language["lid"]],
                        "pslug" => !$_POST["pslug"][(int)$language["lid"]] ? beSelfLink($pname):$_POST["pslug"][(int)$language["lid"]]
                    ]);
                }
                if($product["pcids"]){
                    $categorycontroller = new CategoryController();
                    foreach($product["pcids"] as $pcid){
                        $categorycontroller->beRender($language["lid"],$pcid);
                    }
                }
            }
        }
        return beAjaxSuccess(["message" => beGetLang("product_updated")]);
    }
    public function optionsave_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $pextend = (int)$_POST["pextend"];
        $psecret = (int)$_POST["psecret"];
        $pextendauto = (int)$_POST["pextendauto"];
        $pextendmanuel = (int)$_POST["pextendmanuel"];
        $poverageinvoice = (int)$_POST["poverageinvoice"];
        $pstock = (int)$_POST["pstock"];
        $pstocktype = $_POST["pstocktype"];
        $pterminatetype = $_POST["pterminatetype"];
        $categories = $_POST["categories"];
        $pcids = [];
        foreach($categories as $pcid){
            $category = ProductCategoriesModel::beSelect("pcid")->beWhere("pcid",$pcid)->beGet();
            if($category){
                $pcids[] = (int)$category["pcid"];
            }
        }
        if(!in_array($pextend,[0,1]) || !in_array($psecret,[0,1]) || !in_array($pextendauto,[0,1]) || !in_array($pextendmanuel,[0,1]) || !in_array($poverageinvoice,[0,1]) || !in_array($pstocktype,["unlimited","activeone","onetime"]) || !in_array($pterminatetype,["nevercancel","suspend","terminate"])){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        ProductModel::beUpdate([
            "pcids" => json_encode($pcids),
            "pstock" => $pstock,
            "pstocktype" => $pstocktype,
            "pterminatetype" => $pterminatetype,
            "pextend" => $pextend,
            "psecret" => $psecret,
            "pextendauto" => $pextendauto,
            "pextendmanuel" => $pextendmanuel,
            "poverageinvoice" => $poverageinvoice
        ])->beWhere("pid",$product["pid"])->beExecute();
        if($pcids){
            $languages = LanguageModel::beGetLanguages("lid");
            $categorycontroller = new CategoryController();
            foreach($pcids as $pcid){
                foreach($languages as $language){
                    $categorycontroller->beRender($language["lid"],$pcid);
                }
            }
        }
        return beAjaxSuccess(["message" => beGetLang("product_updated")]);
    }
    public function upgradesave_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $pupgrade = (int)$_POST["pupgrade"];
        $products = $_POST["products"];
        $productlist = [];
        foreach($products as $upgradeproduct){
            $productlist[] = (int)$upgradeproduct;
        }
        $products = ProductModel::beSelect("pid")->beWhere("pid",$productlist,"IN")->beGetAll();
        $productlist = [];
        foreach($products as $upgradeproduct){
            $productlist[] = (int)$upgradeproduct["pid"];
        }
        ProductModel::beUpdate([
            "pupgrade" => $pupgrade,
            "pupgradeproducts" => json_encode($productlist)
        ])->beWhere("pid",$product["pid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("product_updated")]);
    }
    public function automationmodule_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $module = $_POST["module"];
        $product = ProductModel::beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        if($product["pmodule"] && !$module){
            $module = $product["pmodule"];
        }
        beModule::beLoadModule("product.{$module}");
        $configs = beModule::beModuleProductConfig($module);
        $productmoduleslist = ProductModulesModel::beSelect("pmid,pmmodulekey,pmvalue")->beWhere("pid",$product["pid"])->beWhere("pmmodule",$module)->beGetAll();
        $productmodules = [];
        foreach($productmoduleslist as $productmodule){
            $productmodules[$productmodule["pmmodulekey"]] = $productmodule["pmvalue"];
        }
        $automation = beGetView("admin.product.automation",["configs" => $configs,"productmodules" => $productmodules]);
        return beAjaxSuccess(["automation" => $automation]);
    }
    public function automationsave_post(){
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("module");
        $pid = (int)$_POST["pid"];
        $sid = (int)$_POST["server"];
        $module = $_POST["module"];
        $product = ProductModel::beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        if($product["pmodule"] && !$module){
            $module = $product["pmodule"];
        }
        beModule::beLoadModule("product.{$module}");
        $options = beModule::beGetModule($module)->options;
        if(isset($options["isneedserver"]) && $options["isneedserver"] == true && $sid == 0){
            return beAjaxError(["message" => beGetLang("product_need_server")]);
        }
        if($sid){
            ProductModel::beUpdate(["sid" => $sid])->beWhere("pid",$product["pid"])->beExecute();
        }
        $configs = beModule::beModuleProductConfig($module);
        $options = [];
        foreach($configs as $key => $data){
            switch($data["type"]){
                case "select" :
                    $value = $_POST[$key];
                    if(!in_array($value,array_keys($data["values"]))){
                        return beAjaxError(["message" => beGetLang("module_field_select_not_correct",["name" => $data["name"]])]);
                    }
                    $options[$key] = $value;
                    break;
                case "integer" :
                    $value = (int)$_POST[$key];
                    if(isset($data["requirements"]["min"]) && $data["requirements"]["min"] > $value){
                        return beAjaxError(["message" => beGetLang("module_field_min_num",["name" => $data["name"],"value" => $data["requirements"]["min"]])]);
                    }
                    if(isset($data["requirements"]["max"]) && $data["requirements"]["max"] < $value){
                        return beAjaxError(["message" => beGetLang("module_field_max_num",["name" => $data["name"],"value" => $data["requirements"]["max"]])]);
                    }
                    $options[$key] = $value;
                    break;
                case "string" :
                    $value = htmlspecialchars($_POST[$key]);
                    $length = strlen($value);
                    if(isset($data["requirements"]["min"]) && $data["requirements"]["min"] > $length){
                        return beAjaxError(["message" => beGetLang("module_field_min_length",["name" => $data["name"],"value" => $data["requirements"]["min"]])]);
                    }
                    if(isset($data["requirements"]["max"]) && $data["requirements"]["max"] < $length){
                        return beAjaxError(["message" => beGetLang("module_field_max_length",["name" => $data["name"],"value" => $data["requirements"]["max"]])]);
                    }
                    $options[$key] = $value;
                    break;
                case "float" :
                    $value = (float)$_POST[$key];
                    if(isset($data["requirements"]["min"]) && $data["requirements"]["min"] > $value){
                        return beAjaxError(["message" => beGetLang("module_field_min_num",["name" => $data["name"],"value" => $data["requirements"]["min"]])]);
                    }
                    if(isset($data["requirements"]["max"]) && $data["requirements"]["max"] < $value){
                        return beAjaxError(["message" => beGetLang("module_field_max_num",["name" => $data["name"],"value" => $data["requirements"]["max"]])]);
                    }
                    $options[$key] = $value;
                    break;
                case "date" :
                    $value = strtotime($_POST[$key]);
                    $options[$key] = $value;
                    break;
            }
        }
        foreach($options as $key => $value){
            $productmodule = ProductModulesModel::beSelect("pmid")->beWhere("pid",$product["pid"])->beWhere("pmmodule",$module)->beWhere("pmmodulekey",$key)->beGet();
            if($productmodule){
                ProductModulesModel::beUpdate(["pmvalue" => $value,"pmdateline" => BE_TIME])->beWhere("pmid",$productmodule["pmid"])->beExecute();
            }
            else{
                if(empty($value)){
                    continue;
                }
                ProductModulesModel::beInsert([
                    "pid" => $product["pid"],
                    "pmmodule" => $module,
                    "pmmodulekey" => $key,
                    "pmvalue" => $value,
                    "pmdateline" => BE_TIME
                ]);
            }
        }
        ProductModel::beUpdate(["pmodule" => $module])->beWhere("pid",$product["pid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("product_updated")]);
    }
    public function automationdelete_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        ProductModulesModel::beDelete()->beWhere("pid",$product["pid"])->beExecute();
        ProductModel::beUpdate(["pmodule" => ""])->beWhere("pid",$product["pid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("product_updated")]);
    }
    public function periodget_post(){
        beLanguage::beReadLang("product");
        $uid = (int)$_POST["uid"];
        $user = Auth::beGetUser($uid);
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid,pperiods")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $pperiods = json_decode($product["pperiods"],true);
        if(!$pperiods[$user["lid"]]){
            return beAjaxError(["message" => beGetLang("product_periods_not_found")]);
        }
        $pperiods = $pperiods[$user["lid"]];
        $periods = ProductModel::beGetPeriods();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon");
        $periodhtml = beGetView("product.configureperiod-admin",["pperiods" => $pperiods,"periods" => $periods,"currencies" => $currencies]);
        return beAjaxSuccess(["html" => $periodhtml]);
    }
    public function productmoduleautomationget_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid,pmodule")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $module = $product["pmodule"];
        $automation = "";
        if($module){
            beModule::beLoadModule("product.{$module}");
            $configs = beModule::beModuleOrderConfig($module);
            $automation = beGetView("admin.order.automation",["configs" => $configs]);
        }
        return beAjaxSuccess(["automation" => $automation]);
    }
    public function addonget_post(){
        beLanguage::beReadLang("product");
        $uid = (int)$_POST["uid"];
        $cart = new CartController;
        $item = $cart->calculate_basket($_POST,0,0,$uid,0,1,true);
        if(!$item["status"]){
            return beAjaxError(["message" => $item["message"]]);
        }
        $rate = $cart->get_rate($item["productprice"],$item["taxrate"]);
        if(!$rate["status"]){
            return ["status" => false,"message" => $rate["message"]];
        }
        return beAjaxSuccess([
            "periodoptions" => $item["periodoptions"],
            "addonoptions" => $item["addonoptions"],
            "addonoptionshtml" => $item["addonoptionshtml"],
            "productprice" => beMoneyFormat($item["productprice"]),
            "totalrate" => beMoneyFormat($rate["rate"]),
            "totalprice" => beMoneyFormat($item["totalprice"]+$rate["rate"]),
            "icon" => $item["icon"],
            "taxrate" => $item["taxrate"]
        ]);
    }
    public function addonsave_post(){
        beLanguage::beReadLang("product");
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $productaddonslist = $_POST["productaddons"];
        $productaddons = [];
        foreach($productaddonslist as $productaddon){
            if(!$productaddon){
                continue;
            }
            $productaddons[] = (int)$productaddon;
        }
        $productaddonslist = [];
        if($productaddons){
            $productaddons = ProductAddonsModel::beSelect("paid")->beWhere("paid",$productaddons,"IN")->beGetAll();
            foreach($productaddons as $productaddon){
                $productaddonslist[] = (int)$productaddon["paid"];
            }
        }
        ProductModel::beUpdate(["paddons" => json_encode($productaddonslist)])->beWhere("pid",$product["pid"])->beExecute();
        $updateorders = (int)$_POST["updateorders"];
        if($updateorders){
            $userproducts = UserProductModel::beSelect("upid,upoptions")->beWhere("pid",$product["pid"])->beWhere("upid",1)->beGetAll();
            foreach($userproducts as $userproduct){
                $upoptions = json_decode($userproduct["upoptions"],true);
                foreach($upoptions as $key => $data){
                    if(preg_match('/addon(.*)/',$key,$matches)){
                        $paid = (int)$matches[1];
                        $found = false;
                        foreach($productaddonslist as $productaddon){
                            if($paid == $productaddon){
                                $found = true;
                                break;
                            }
                        }
                        if(!$found){
                            unset($upoptions[$key]);
                        }
                    }
                }
                UserProductModel::beUpdate(["upoptions" => json_encode($upoptions,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
            }
        }
        return beAjaxSuccess(["message" => beGetLang("product_updated")]);
    }
    public function pricesave_post(){
        beLanguage::beReadLang("product");
        $productprices = $_POST["productprices"];
        $pid = (int)$_POST["pid"];
        $product = ProductModel::beSelect("pid,pcids")->beWhere("pid",$pid)->beGet();
        if(!$product){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $itemprices = [];
        $languages = LanguageModel::beGetLanguages("lid");
        foreach($languages as $language){
            foreach($productprices[$language["lid"]] as $key => $productprice){
                if(!$productprice["period"]){
                    continue;
                }
                $itemprices[$language["lid"]][$key] = [
                    "operiodtime" => $productprice["time"],
                    "operiod" => $productprice["period"],
                    "oprice" => $productprice["price"],
                    "odiscount" => $productprice["discount"],
                    "ocid" => $productprice["currency"],
                ];
            }
        }
        if(empty($itemprices)){
            return beAjaxError(["message" => beGetLang("product_period_not_found")]);
        }
        ProductModel::beUpdate(["pperiods" => json_encode($itemprices,JSON_UNESCAPED_UNICODE)])->beWhere("pid",$product["pid"])->beExecute();
        if($product["pcids"]){
            $product["pcids"] = json_decode($product["pcids"],true);
            $languages = LanguageModel::beGetLanguages("lid");
            $categorycontroller = new CategoryController();
            foreach($product["pcids"] as $pcid){
                foreach($languages as $language){
                    $categorycontroller->beRender($language["lid"],$pcid);
                }
            }
        }
        return beAjaxSuccess(["message" => beGetLang("product_updated")]);
    }
    public function product($slug){
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("currency");
        $user = Auth::beGetUser();
        $product = ProductModel::beSelect("be_products.pid,be_products.sid,be_products.pperiods,be_products.paddons,be_products.paddons,be_products.pstock,be_products.pstocktype,be_products.pmodule,pt.lid,pt.pname,pt.pdescription,pt.pmetadescription,pt.pmetakeywords,pt.pfeatures")->beWhere("pt.pslug",$slug)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGet();
        if(!$product){
            beError(beGetLang("product"),beGetLang("product_not_found"));
        }
        if($product["lid"] != $user["lid"]){
            $producttranslation = ProductTranslationsModel::beSelect("pname,pdescription,pmetadescription,pmetakeywords,pfeatures")->beWhere("lid",$user["lid"])->beWhere("pid",$product["pid"])->beGet();
            if(!$producttranslation){
                beError(beGetLang("product"),beGetLang("product_periods_not_found"));
            }
            foreach($producttranslation as $key => $value){
                $product[$key] = $value;
            }
        }
        if($product["pstock"] == 0){
            beError(beGetLang("product"),beGetLang("product_not_have_stock"));
        }
        $periods = ProductModel::beGetPeriods();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon");
        $pperiods = json_decode($product["pperiods"],true);
        if(!$pperiods[$user["cid"]]){
            beError(beGetLang("product"),beGetLang("product_period_currency_not_found"));
        }
        $pperiods = $pperiods[$user["cid"]];
        $paddons = json_decode($product["paddons"],true);
        if($paddons){
            $productaddons = ProductAddonTranslationsModel::beWhere("lid",$user["lid"])->beWhere("paid",$paddons,"IN")->beWhere("pastatus",1)->beGetAll();
            if(!$productaddons){
                beError(beGetLang("product"),beGetLang("product_addons_not_found"));
            }
        }
        if($product["pmodule"]){
            $data = ["product" => $product,"pperiods" => $pperiods,"productaddons" => $productaddons,"periods" => $periods,"currencies" => $currencies];
            if($product["sid"]){
                $server = ServerModel::beWhere("sid",$product["sid"])->beGet();
                $server["spassword"] = beDecryptData($server["spassword"]);
                $data["server"] = $server;
            }
            beModule::beLoadModule("product.{$product['pmodule']}");
            if(beModule::beCheckModuleFunction($product["pmodule"],"preconfiguration")){
                $response = beModule::beRunModuleFunction($product["pmodule"],"preconfiguration",$data);
            }
        }
        NavController::beAddBreadcumb($product["pname"]);
        beSetHeaderContent();
        $periodextend = SettingModel::beGetSettings("cart_periodextend")["cart_periodextend"];
        return beGetView("product.configure",["product" => $product,"pperiods" => $pperiods,"productaddons" => $productaddons,"periods" => $periods,"currencies" => $currencies,"periodextend" => $periodextend]);
    }
    public function price_post(){
        $cart = new CartController;
        $basket = $cart->calculate_basket($_POST,0,0,0,0,1);
        if(!$basket["status"]){
            return beAjaxError(["message" => $basket["message"]]);
        }
        $rate = $cart->get_rate($basket["productprice"],$basket["taxrate"]);
        if(!$rate["status"]){
            return ["status" => false,"message" => $rate["message"]];
        }
        return beAjaxSuccess([
            "periodoptions" => $basket["periodoptions"],
            "addonoptions" => $basket["addonoptions"],
            "addonoptionshtml" => $basket["addonoptionshtml"],
            "productprice" => beMoneyFormat($basket["productprice"]),
            "totalrate" => beMoneyFormat($rate["rate"]),
            "totalprice" => beMoneyFormat($basket["totalprice"]+$rate["rate"]),
            "icon" => $basket["icon"],
            "taxrate" => $basket["taxrate"]
        ]);
    }
}

?>