<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Basic\beRouter;
use App\System\Model\AuthModel;
use App\System\Model\CartModel;
use App\System\Model\CouponModel;
use App\System\Model\CouponUsageModel;
use App\System\Model\CurrencyModel;
use App\System\Model\InvoiceItemModel;
use App\System\Model\InvoiceModel;
use App\System\Model\MessageTemplateModel;
use App\System\Model\ProductAddonModulesModel;
use App\System\Model\ProductAddonTranslationsModel;
use App\System\Model\ProductExtraConfigModel;
use App\System\Model\ProductModel;
use App\System\Model\ProductModulesModel;
use App\System\Model\ReferralModel;
use App\System\Model\ServerModel;
use App\System\Model\SettingModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserLogModel;
use App\System\Model\UserProductExtensionsModel;
use App\System\Model\UserProductLogsModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\Basic\beCookie;
use App\System\Vendor\beAlert;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beMail;
use App\System\Vendor\beModule;
use App\System\Vendor\beSms;

class CartController extends beContoller {
    public function show(){
        beLanguage::beReadLang("cart");
        NavController::beAddBreadcumb(beGetLang("cart"));
        beSetHeaderContent();
        $cart = $this->get_user_cart();
        if(empty($cart)){
            beError("Sepetiniz Boş",beGetLang("cart_empty"));
        }
        return beGetView("product.cart",["cart" => $cart]);
    }
    public function getcart_post(){
        beLanguage::beReadLang("cart");
        $user = Auth::beGetUser();
        $cart = $this->get_user_cart();
        if(empty($cart)){
            return beAjaxError(["message" => beGetLang("cart_empty")]);
        }
        $couponcode = $_POST["coupon"];
        $cproducts = [];
        $cdiscounttype = 0;
        $cdiscount = 0;
        $chaveproduct = false;
        $coupon = [];
        if($couponcode){
            $coupon = $this->get_coupon($couponcode);
            if($coupon["status"]){
                if($coupon["cproducts"]){
                    $cproducts = json_decode($coupon["cproducts"],true);
                    if(count($cproducts) != 0){
                        $chaveproduct = true;
                    }
                }
                $cdiscounttype = (int)$coupon["cdiscounttype"];
                $cdiscount = $coupon["cdiscount"];
            }
            else{
                $couponerror = $coupon["message"];
            }
        }
        $products_rows = "";
        $productsmainprice = 0;
        $productsdiscountprice = 0;
        $productsprice = 0;
        $totalprice = 0;
        $icon = "";
        $taxrate = 0;
        $itemcount = 0;
        $cartproducts = [];
        foreach($cart as $upid => $value){
            $iteminfo = [
                "pid" => $value["pid"]
            ];
            foreach($value["data"] as $config => $data){
                $iteminfo[$config] = $data["key"];
            }
            if($cdiscount){
                if($chaveproduct){
                    if(in_array($value["pid"],$cproducts)){
                        $item = $this->calculate_basket($iteminfo,$cdiscounttype,$cdiscount,0,1);
                    }
                    else{
                        $item = $this->calculate_basket($iteminfo,0,0,0,1);
                    }
                }
                else{
                    $item = $this->calculate_basket($iteminfo,$cdiscounttype,$cdiscount,0,1);
                }
            }
            else{
                $item = $this->calculate_basket($iteminfo,0,0,0,1);
            }
            if(!$item["status"]){
                return beAjaxError(["message" => $item["message"]]);
            }
            if(!$icon){
                $icon = $item["icon"];
            }
            if(!$taxrate){
                $taxrate = $item["taxrate"];
            }
            $item["productprice"] *= $value["count"];
            $item["count"] = $value["count"];
            $productsprice += $item["productprice"];
            $productsdiscountprice += $item["discountprice"]*$value["count"];
            $productsmainprice += $item["productmainprice"];
            $cartproducts[$upid] = $item;
            $itemcount += 1;
        }
        if($coupon["status"]){
            $coupon = $this->get_coupon($couponcode,2,0,["price" => $productsmainprice,"itemcount" => $itemcount]);
            if(!$coupon["status"]){
                return beAjaxError(["message" => $coupon["message"]]);
            }
        }
        foreach($cartproducts as $upid => $item){
            $producturl = beGetRoute("product.product",["slug" => $item["product"]["pslug"]]);
            $products_rows .= beGetView("product.cartitem",["item" => $item,"upid" => $upid,"producturl" => $producturl,"count" => $item["count"]]);
        }
        $invoice_tax_exemption = 0;
        if($user["uid"]){
            $userinfo = UserInfoModel::beSelect("uisettings")->beWhere("uid",$user["uid"])->beGet();
            $uisettings = json_decode($userinfo["uisettings"],true);
            $invoice_tax_exemption = $uisettings["invoice_tax_exemption"];
        }
        if($invoice_tax_exemption == 0){
            $rate = $this->get_rate($productsprice,$taxrate);
            if(!$rate["status"]){
                return beAjaxError(["message" => $rate["message"]]);
            }
        }
        $rateprice = $rate["rate"];
        $totalprice = $productsprice+$rateprice;
        return beAjaxSuccess([
            "html" => $products_rows,
            "icon" => $icon,
            "taxrate" => $taxrate,
            "productsprice" => beMoneyFormat($productsmainprice),
            "productsallprice" => beMoneyFormat($productsprice),
            "productsdiscount" => beMoneyFormat($productsdiscountprice),
            "productsrate" => beMoneyFormat($rateprice),
            "totalprice" => beMoneyFormat($totalprice),
            "couponerror" => $couponerror
        ]);
    }
    public function setcountitem_post(){
        beLanguage::beReadLang("cart");
        beLanguage::beReadLang("product");
        $upid = (int)$_POST["upid"];
        $counter = $_POST["counter"];
        if(!isset($_POST["upid"])){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $cart = $this->get_user_cart();
        if(!array_key_exists($upid,$cart)){
            return beAjaxError(["message" => beGetLang("cart_item_not_found")]);
        }
        if($counter == "+"){
            $cart[$upid]["count"] += 1;
        }
        else if($counter == "-"){
            if($cart[$upid]["count"]-1 == 0){
                return $this->removeitem_post();
            }
            $cart[$upid]["count"] -= 1;
        }
        $this->set_user_cart($cart);
        return beAjaxSuccess([]);
    }
    public function additem_post($item = []){
        beLanguage::beReadLang("cart");
        if(!$item){
            $item = $_POST;
        }
        $user = Auth::beGetUser();
        $basket = $this->calculate_basket($item,0,0,0,1);
        if(!$basket["status"]){
            return beAjaxError(["message" => $basket["message"]]);
        }
        $product = $basket["product"];
        if($product["pstock"] != -1 && $product["pstock"] < 1){
            return beAjaxError(["message" => beGetLang("product_not_have_stock")]);
        }
        if($product["pstocktype"] != "unlimited"){
            switch($product["pstocktype"]){
                case "activeone" :
                    $total = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("pid",$product["pid"])->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGet()["total"];
                    if($total){
                        return beAjaxError(["message" => beGetLang("product_stock_active_one")]);
                    }
                    break;
                case "onetime" :
                    $total = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("pid",$product["pid"])->beWhere("uid",$user["uid"])->beGet()["total"];
                    if($total){
                        return beAjaxError(["message" => beGetLang("product_stock_only_one")]);
                    }
                    break;
            }
        }
        if($product["pmodule"]){
            $data = ["product" => $product,"periodoptions" => $basket["periodoptions"],"addonoptions" => $basket["addonoptions"]];
            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"],"preaddcart")){
                beModule::beRunModuleFunction($product["pmodule"],"preaddcart",$data);
            }
        }
        $cartitem = [
            "pid" => $product["pid"],
            "count" => 1,
            "data" => $basket["optionsdata"]
        ];
        $cart = $this->get_user_cart();
        $cart[] = $cartitem;
        $this->set_user_cart($cart);
        return beAjaxSuccess(["message" => beGetLang("cart_item_added"),"url" => beGetRoute("cart.show")]);
    }
    public function removeitem_post(){
        beLanguage::beReadLang("cart");
        beLanguage::beReadLang("product");
        $user = Auth::beGetUser();
        $upid = (int)$_POST["upid"];
        if(!isset($_POST["upid"])){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $cart = $this->get_user_cart();
        if(!array_key_exists($upid,$cart)){
            return beAjaxError(["message" => beGetLang("cart_item_not_found")]);
        }
        $userproduct = $cart[$upid];
        $pid = $userproduct["pid"];
        if(!$pid){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $product = ProductModel::beSelect("be_products.pid,be_products.pimage,pt.pname,pt.pslug")->beWhere("pt.lid",$user["lid"])->beWhere("pt.pid",$pid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGet();
        $producturl = beGetRoute("product.product",["slug" => $product["pslug"]]);
        $oldproduct = beGetView("product.productback",["product" => $product,"producturl" => $producturl]);
        beCookie::beCreateCookie("becart_last",json_encode($userproduct),true,true,BE_TIME+3600);
        unset($cart[$upid]);
        $empty = false;
        if(empty($cart)){
            $empty = true;
        }
        $this->set_user_cart($cart);
        return beAjaxSuccess(["message" => beGetLang("cart_item_deleted"),"isempty" => $empty,"oldproduct" => $oldproduct]);
    }
    public function addretryitem_post(){
        beLanguage::beReadLang("cart");
        beLanguage::beReadLang("product");
        $user = Auth::beGetUser();
        $cart_last = json_decode(beCookie::beGetCookie("becart_last"),true);
        if(empty($cart_last)){
            return beAjaxError(["message" => beGetLang("cart_item_add_error")]);            
        }
        $pid = (int)$cart_last["pid"];
        if(!$pid){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $iteminfo["pid"] = $pid;
        foreach($cart_last["data"] as $config => $data){
            $iteminfo[$config] = $data["key"];
        }
        $basket = $this->calculate_basket($iteminfo,0,0,0,1);
        if(!$basket["status"]){
            return beAjaxError(["message" => $basket["message"]]);
        }
        $product = $basket["product"];
        if($product["pstock"] != -1 && $product["pstock"] < 1){
            return beAjaxError(["message" => beGetLang("product_not_have_stock")]);
        }
        if($product["pstocktype"] != "unlimited"){
            switch($product["pstocktype"]){
                case "activeone" :
                    $total = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("pid",$product["pid"])->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGet()["total"];
                    if($total){
                        return beAjaxError(["message" => beGetLang("product_stock_active_one")]);
                    }
                    break;
                case "onetime" :
                    $total = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("pid",$product["pid"])->beWhere("uid",$user["uid"])->beGet()["total"];
                    if($total){
                        return beAjaxError(["message" => beGetLang("product_stock_only_one")]);
                    }
                    break;
            }
        }
        if($product["pmodule"]){
            $data = ["product" => $product,"periodoptions" => $basket["periodoptions"],"addonoptions" => $basket["addonoptions"]];
            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"],"preaddcart")){
                beModule::beRunModuleFunction($product["pmodule"],"preaddcart",$data);
            }
        }
        $cartitem = [
            "pid" => $product["pid"],
            "count" => 1,
            "data" => $basket["optionsdata"]
        ];
        $cart = $this->get_user_cart();
        $cart[] = $cartitem;
        $this->set_user_cart($cart);
        return beAjaxSuccess(["message" => beGetLang("cart_item_added")]);
    }
    public function checkcoupon_post(){
        beLanguage::beReadLang("coupon");
        $code = $_POST["coupon"];
        $coupon = CouponModel::beSelect("cpid")->beWhere("ccode",$code)->beGet();
        if(!$coupon){
            return beAjaxError(["message" => beGetLang("coupon_not_found")]);
        }
        return beAjaxSuccess(["message" => beGetLang("coupon_found")]);
    }
    public function agreecart_post(){
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("cart");
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("invoice");
        $user = Auth::beGetUser();
        if(!$user["uid"]){
            return beAjaxError(["message" => beGetLang("need_account"),"url" => beGetRoute("auth.login")."?reredirect=".urlencode(beGetRoute("cart.show"))]);
        }
        $cart = $this->get_user_cart();
        if($this->get_user_cartstatus() == 1){
            return beAjaxError(["message" => beGetLang("cart_proccessing")]);           
        }
        $this->set_user_cartstatus(1);
        if(empty($cart)){
            $this->set_user_cartstatus(0);
            return beAjaxError(["message" => beGetLang("cart_empty")]); 
        }
        $systemdata = [];
        $userinfo = UserInfoModel::beSelect("uisettings")->beWhere("uid",$user["uid"])->beGet();
        $uisettings = json_decode($userinfo["uisettings"],true);
        $invoice_tax_exemption = $uisettings["invoice_tax_exemption"];
        $couponcode = $_POST["coupon"];
        $cproducts = [];
        $cdiscounttype = 0;
        $cdiscount = 0;
        $chaveproduct = false;
        if($couponcode){
            $coupon = $this->get_coupon($couponcode);
            if($coupon["status"]){
                if($coupon["cproducts"]){
                    $cproducts = json_decode($coupon["cproducts"],true);
                    if(count($cproducts) != 0){
                        $chaveproduct = true;
                    }
                }
                $cdiscounttype = (int)$coupon["cdiscounttype"];
                $cdiscount = $coupon["cdiscount"];
            }
        }
        $productsmainprice = 0;
        $productsdiscountprice = 0;
        $productsprice = 0;
        $itemcount = 0;
        foreach($cart as $upid => $value){
            $iteminfo = [
                "pid" => $value["pid"]
            ];
            foreach($value["data"] as $config => $data){
                $iteminfo[$config] = $data["key"];
            }
            if($cdiscount){
                if($chaveproduct){
                    if(in_array($value["pid"],$cproducts)){
                        $item = $this->calculate_basket($iteminfo,$cdiscounttype,$cdiscount,0,1);
                    }
                    else{
                        $item = $this->calculate_basket($iteminfo,0,0,0,1);
                    }
                }
                else{
                    $item = $this->calculate_basket($iteminfo,$cdiscounttype,$cdiscount,0,1);
                }
            }
            else{
                $item = $this->calculate_basket($iteminfo,0,0,0,1);
            }
            if($item["product"]["pstock"] != -1 && $item["product"]["pstock"] < 1){
                return beAjaxError(["message" => beGetLang("product_not_have_stock")]);
            }
            if($item["product"]["pstocktype"] != "unlimited"){
                switch($item["product"]["pstocktype"]){
                    case "activeone" :
                        $total = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("pid",$item["product"]["pid"])->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGet()["total"];
                        if($total){
                            return beAjaxError(["message" => beGetLang("product_stock_active_one")]);
                        }
                        break;
                    case "onetime" :
                        $total = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("pid",$item["product"]["pid"])->beWhere("uid",$user["uid"])->beGet()["total"];
                        if($total){
                            return beAjaxError(["message" => beGetLang("product_stock_only_one")]);
                        }
                        break;
                }
            }
            if($item["product"]["pmodule"]){
                $product = $item["product"];
                $data = ["product" => $product,"periodoptions" => $item["periodoptions"],"addonoptions" => $item["addonoptions"]];
                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"],"preaddcart")){
                    beModule::beRunModuleFunction($product["pmodule"],"preaddcart",$data);
                }
            }
            if(!$item["status"]){
                return beAjaxError(["message" => $item["message"]]);
            }
            $productsdiscountprice += $item["discountprice"]*$value["count"];
            $productsmainprice += $item["productmainprice"];
            $itemcount += 1;
            $basket[] = [$item["product"]["pid"],$item["product"]["pname"],$item["currency"],$item["productprice"],$value["count"],$item["period"]["operiod"],$invoice_tax_exemption == 0 ? $item["taxrate"]:0];
        }
        $cpid = 0;
        if($coupon["status"]){
            $coupon = $this->get_coupon($couponcode,2,0,["price" => $productsmainprice,"itemcount" => $itemcount]);
            if(!$coupon["status"]){
                return beAjaxError(["message" => $coupon["message"]]);
            }
            $cpid = $coupon["cpid"];
        }
        $invoice = new InvoiceController();
        $iid = InvoiceModel::beInsert([
            "cid" => $user["cid"],
            "cpid" => $cpid,
            "uid" => $user["uid"],
            "iname" => beGetLang("invoice_order_buy_name"),
            "idescription" => beGetLang("invoice_order_buy_name"),
            "itype" => "1",
            "istatus" => "0",
            "ibill" => "0",
            "iprice" => 0,
            "itaxprice" => 0,
            "idiscount" => $productsdiscountprice > 0 ? $productsdiscountprice:0,
            "ifee" => 0,
            "idata" => json_encode($cart,JSON_UNESCAPED_UNICODE),
            "iexpiredate" => BE_TIME+3600,
            "idateline" => BE_TIME 
        ]);
        foreach($basket as $item){
            InvoiceItemModel::beInsert([
                "iid" => $iid,
                "cid" => $item[2],
                "iiobject" => "BuyProduct",
                "iiobjectid" => $item[0],
                "iiname" => $item[1],
                "iiunitprice" => $item[3],
                "iiunitcount" => $item[4],
                "iitaxrate" => $item[6],
                "iiunittype" => $item[5],
                "iidata" => "",
                "iidateline" => BE_TIME
            ]);
        }
        $invoice->beCalculateInvoicePrices($iid);
        $this->set_user_cart([]);
        return beAjaxSuccess(["message" => beGetLang("invoice_created"),"url" => beGetRoute("client.invoice.invoice",["iid" => $iid])."?action=pay"]);
    }
    public function cart_invoice_approve($iid){
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("cart");
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("order");
        beLanguage::beReadLang("module");
        $invoice = InvoiceModel::beSelect("iid,cid,cpid,uid,iname,itype,istatus,idata,isystemdata,iprice,itaxprice,idiscount")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return ["status" => false,"message" => beGetLang("invoice_not_found")];
        }
        if($invoice["istatus"] != 0){
            return ["status" => false,"message" => beGetLang("invoice_already_processed")];
        }    
        $user = Auth::beGetUser($invoice["uid"]);
        $sitename = beGetConfig("sitename");
        $invoicelink = beGetRoute("client.invoice.invoice",["iid" => $invoice["iid"]]);
        $messages = MessageTemplateModel::beGetMessages("invoice_payed",1)["invoice_payed"];
        $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$user["uid"])->beGet();
        $currency = CurrencyModel::beGetCurrencies("cid,cicon",$user["cid"]);
        $uisettings = json_decode($userinfo["uisettings"],true);
        if($messages["alert"] && $uisettings["notification_alert"]){
            $message = str_replace(["{sitename}","{invoicename}","{namesurname}","{invoicelink}"],[$sitename,$invoice["iname"],$user["name"]." ".$user["surname"],$invoicelink],$messages["alert"]["mttmessage"]);
            beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),$invoicelink,$userinfo["uid"]);
        }
        if($messages["sms"] && $uisettings["sms_alert"]){
            $message = str_replace(["{sitename}","{invoicename}","{namesurname}","{invoicelink}"],[$sitename,$invoice["iname"],$user["name"]." ".$user["surname"],$invoicelink],$messages["sms"]["mttmessage"]);
            beSms::beCreateSms($message,1,$userinfo["uid"]);
        }
        if($messages["mail"] && $uisettings["mail_alert"]){
            $message = str_replace(["{sitename}","{invoicename}","{namesurname}","{invoicelink}"],[$sitename,$invoice["iname"],$user["name"]." ".$user["surname"],$invoicelink],$messages["mail"]["mttmessage"]);
            beMail::beCreateMail($messages["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
        }
        $settings = SettingModel::beGetSettings("automation_invoice_create_day,referral_status,referral_price_type,referral_price");
        switch($invoice["itype"]){
            case 1 : {
                $productsname = "";
                $productsprice = 0;
                $itemcount = 0;
                $periodtimes = ProductModel::beGetPeriodsTimes();
                $idata = json_decode($invoice["idata"],true);
                foreach($idata as $upid => $value){
                    $iteminfo = [
                        "pid" => $value["pid"]
                    ];
                    foreach($value["data"] as $config => $data){
                        $iteminfo[$config] = $data["key"];
                    }
                    $item = $this->calculate_basket($iteminfo,0,0,$invoice["uid"]);
                    if($uisettings["invoice_tax_exemption"] == 1){
                        $item["taxrate"] = 0;
                    }
                    if(!$item["status"]){
                        return ["status" => false,"message" => $item["message"]];
                    }
                    $item["productprice"] = round($item["productprice"],2);
                    $productsprice += $item["productprice"]*$value["count"];
                    $productsname .= $item["product"]["pname"].",";
                    $systime = $value["data"]["period"]["time"]*$periodtimes[$value["data"]["period"]["period"]];
                    ProductModel::beUpdate(["psold" => $item["product"]["psold"]+$value["count"],"pactive" => $item["product"]["pactive"]+$value["count"]])->beWhere("pid",$value["pid"])->beExecute();
                    if(!$settings["automation_invoice_create_day"]){
                        $settings["automation_invoice_create_day"] = 3;
                    }
                    for($i = 0; $i < $value["count"]; $i++){
                        $upid = UserProductModel::beInsert([
                            "uid" => $invoice["uid"],
                            "cid" => $user["cid"],
                            "pid" => $value["pid"],
                            "sid" => $item["product"]["sid"],
                            "upname" => $item["product"]["pname"],
                            "upoptions" => json_encode($value["data"],JSON_UNESCAPED_UNICODE),
                            "upstatus" => 1,
                            "upprice" => $this->calculate_basket_nextprice($value["data"],$user["cid"]),
                            "uptaxrate" => $item["taxrate"],
                            "upmodule" => $item["product"]["pmodule"],
                            "upstime" => BE_TIME,
                            "upntime" => $systime ? BE_TIME+$systime-(86400*$settings["automation_invoice_create_day"]):0,
                            "upetime" => $systime ? BE_TIME+$systime:0
                        ]);
                        UserProductLogsModel::beInsert([
                            "uid" => $invoice["uid"],
                            "upid" => $upid,
                            "upltype" => "order_buy",
                            "upldata" => json_encode([
                                "pid" => (int)$value["pid"],
                                "cid" => (int)$user["cid"],
                                "price" => $item["productprice"]
                            ]),
                            "uplipaddress" => beRouter::$beUserIP,
                            "upldateline" => BE_TIME
                        ]);
                        $itemcount += 1; 
                    }
                }
                if($invoice["cpid"]){
                    $coupon = CouponModel::beSelect("cpid,cusage")->beWhere("cpid",$invoice["cpid"])->beGet();
                    if($coupon){
                        CouponModel::beUpdate(["cusage" => $coupon["cusage"]+1])->beWhere("cpid",$coupon["cpid"])->beExecute();
                        CouponUsageModel::beInsert([
                            "cpid" => $coupon["cpid"],
                            "iid" => $invoice["iid"],
                            "uid" => $invoice["uid"],
                            "cuearned" => $invoice["idiscount"],
                            "cudateline" => BE_TIME
                        ]);
                    }
                }
                $productsname = substr($productsname,0,-1);
                $sitename = beGetConfig("sitename");
                InvoiceModel::beUpdate([
                    "istatus" => "1",
                    "ipaydate" => BE_TIME
                ])->beWhere("iid",$invoice["iid"])->beExecute();
                $pricecurrency = $productsprice." ".$currency["cicon"];
                $orderlink = beGetRoute("admin.order.show",["upid" => $upid]);
                if($itemcount == 1){
                    $data =  ["url" => beGetRoute("client.userproduct.userproduct",["upid" => $upid])];
                }
                else{
                    $data = ["url" => beGetRoute("client.userproduct.userproducts")];
                }
                $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$invoice["uid"])->beGet();
                $uisettings = json_decode($userinfo["uisettings"],true);
                $messages = MessageTemplateModel::beGetMessages("order_created",1)["order_created"];
                if($messages["alert"] && $uisettings["notification_alert"]){
                    $message = str_replace(["{sitename}","{namesurname}","{productprice}","{productsname}","{orderurl}"],[$sitename,$user["name"]." ".$user["surname"],$pricecurrency,$productsname,$data["url"]],$messages["alert"]["mttmessage"]);
                    beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),$data["url"],$userinfo["uid"]);
                }
                if($messages["sms"] && $uisettings["sms_alert"]){
                    $message = str_replace(["{sitename}","{namesurname}","{productprice}","{productsname}","{orderurl}"],[$sitename,$user["name"]." ".$user["surname"],$pricecurrency,$productsname,$data["url"]],$messages["sms"]["mttmessage"]);
                    beSms::beCreateSms($message,1,$userinfo["uid"]);
                }
                if($messages["mail"] && $uisettings["mail_alert"]){
                    $message = str_replace(["{sitename}","{namesurname}","{productprice}","{productsname}","{orderurl}"],[$sitename,$user["name"]." ".$user["surname"],$pricecurrency,$productsname,$data["url"]],$messages["mail"]["mttmessage"]);
                    beMail::beCreateMail($messages["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                }
                $admins = AuthModel::beSelect("uid")->beWhere("usergroup",4)->beGetAll();
                if($admins){
                    $messages = MessageTemplateModel::beGetMessages("order_created_admin",1)["order_created_admin"];
                    foreach($admins as $admin){
                        $adminuserinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$admin["uid"])->beGet();
                        $adminuisettings = json_decode($adminuserinfo["uisettings"],true);
                        if($messages["alert"] && $adminuisettings["notification_alert"]){
                            $message = str_replace(["{productsname}","{productprice}","{username}","{orderlink}"],[$productsname,$pricecurrency,$user["name"]." ".$user["surname"],$orderlink],$messages["alert"]["mttmessage"]);
                            beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),$orderlink,$adminuserinfo["uid"]);
                        }
                        if($messages["sms"] && $adminuisettings["sms_alert"]){
                            $message = str_replace(["{productsname}","{productprice}","{username}","{orderlink}"],[$productsname,$pricecurrency,$user["name"]." ".$user["surname"],$orderlink],$messages["sms"]["mttmessage"]);
                            beSms::beCreateSms($message,1,$adminuserinfo["uid"]);
                        }
                        if($messages["mail"] && $adminuisettings["mail_alert"]){
                            $message = str_replace(["{productsname}","{productprice}","{username}","{orderlink}"],[$productsname,$pricecurrency,$user["name"]." ".$user["surname"],$orderlink],$messages["mail"]["mttmessage"]);
                            $messagesubject = str_replace(["{productsname}","{productprice}","{username}","{orderlink}"],[$productsname,$pricecurrency,$user["name"]." ".$user["surname"],$orderlink],$messages["mail"]["mttsubject"]);
                            beMail::beCreateMail($messagesubject,$message,2,1,$adminuserinfo["uid"]);
                        }
                    }
                }
                if($settings["referral_status"] == 1){
                    $referral = ReferralModel::beWhere("uid",$invoice["uid"])->beGet();
                    if($referral){
                        $earnprice = 0;
                        switch($settings["referral_price_type"]){
                            case 1 :
                                $earnprice = round(($productsprice*$settings["referral_price"])/100,2);
                                break;
                            case 2 :
                                $earnprice = $settings["referral_price"];
                                break;
                        }
                        $refuser = Auth::beGetUser($referral["rfuid"],"uid,money");
                        $refuser["money"] += $earnprice;
                        AuthModel::beUpdate(["money" => $refuser["money"]])->beWhere("uid",$refuser["uid"])->beExecute();
                        ReferralModel::beUpdate(["rfprice" => $referral["rfprice"]+$earnprice,"rfpricetotal" => $referral["rfpricetotal"]+$earnprice])->beWhere("rid",$referral["rid"])->beExecute();
                        UserLogModel::beInsert([
                            "uid" => $refuser["uid"],
                            "ltype" => "money_change_referral",
                            "ldata" => json_encode([
                                "referenced_uid" => $invoice["uid"],
                                "earned_price" => $earnprice,
                                "total_price" => $refuser["money"]
                            ]),
                            "lipaddress" => "0.0.0.0",
                            "ldateline" => BE_TIME
                        ]);
                    }
                }
                $data["status"] = true;
                $data["message"] = beGetLang("invoice_paid");
                return $data;
                break;
            }
            case 2 : {
                $invoiceitems = InvoiceItemModel::beSelect("iiid,iiobjectid,iiunitcount")->beWhere("iid",$invoice["iid"])->beWhere("iiobject","ExtendOrder")->beGetAll();
                foreach($invoiceitems as $item){
                    $itemcount = (int)$item["iiunitcount"];
                    $userproduct = UserProductModel::beSelect("pname,pperiods,be_user_products.*")->beWhere("upid",$item["iiobjectid"])->beJoin("INNER JOIN be_products as p ON p.pid = be_user_products.pid INNER JOIN be_product_translations as pt ON pt.pid = be_user_products.pid")->beGet();
                    if(!$userproduct){
                        return ["status" => false,"message" => beGetLang("order_not_found")];
                    }      
                    if(!$userproduct["upetime"]){
                        return ["status" => false,"message" => beGetLang("product_cant_extend")];                
                    } 
                    $upoptions = json_decode($userproduct["upoptions"],true);
                    if(empty($upoptions)){
                        return ["status" => false,"message" => beGetLang("product_options_not_found")];
                    }
                    $pperiods = json_decode($userproduct["pperiods"],true);
                    if(!$pperiods[$user["lid"]]){
                        return ["status" => false,"message" => beGetLang("product_period_currency_not_found")];
                    }
                    $periodtimes = ProductModel::beGetPeriodsTimes();
                    $pperiods = $pperiods[$user["lid"]];
                    $period = $upoptions["period"];
                    if(!array_key_exists($period["key"],$pperiods)){
                        return ["status" => false,"message" => beGetLang("product_period_not_found")];
                    }
                    $timeadd = $periodtimes[$period["period"]]*$period["time"]*$itemcount;
                    $userproduct["upetime"] += $timeadd;
                    $upstatus = (int)$userproduct["upstatus"];
                    $newupstatus = $upstatus;
                    if($userproduct["upetime"] > BE_TIME && $upstatus == 0){
                        $newupstatus = 2;
                    }
                    UserProductModel::beUpdate([
                        "upstatus" => $newupstatus,
                        "upntime" => $userproduct["upetime"]-(86400*3),
                        "upetime" => $userproduct["upetime"]
                    ])->beWhere("upid",$userproduct["upid"])->beExecute();
                    UserProductExtensionsModel::beUpdate(["upetype" => "1"])->beWhere("upid",$userproduct["upid"])->beWhere("upetype","onetime")->beExecute();
                    InvoiceModel::beUpdate([
                        "istatus" => "1",
                        "ipaydate" => BE_TIME
                    ])->beWhere("iid",$invoice["iid"])->beExecute();
                    UserProductLogsModel::beInsert([
                        "uid" => $userproduct["uid"],
                        "upid" => $userproduct["upid"],
                        "upltype" => "order_extend",
                        "upldata" => json_encode([
                            "iid" => (int)$invoice["iid"],
                            "extratime" => $timeadd,
                            "totaltime" => $userproduct["upetime"]
                        ]),
                        "uplipaddress" => beRouter::$beUserIP,
                        "upldateline" => BE_TIME
                    ]);
                    if($userproduct["upmodule"]){
                        $product = ProductModel::beSelect("be_products.*,pt.pname")->beWhere("be_products.pid",$userproduct["pid"])->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGet();
                        $productmoduleslist = ProductModulesModel::beSelect("pmid,pmmodulekey,pmvalue")->beWhere("pid",$product["pid"])->beWhere("pmmodule",$userproduct["upmodule"])->beGetAll();
                        $productmodules = [];
                        foreach($productmoduleslist as $productmodule){
                            $productmodules[$productmodule["pmmodulekey"]] = $productmodule["pmvalue"];
                        }
                        $product["paddons"] = json_decode($product["paddons"],true);
                        $addonmodules = [];
                        if($product["paddons"]){
                            $productaddons = ProductAddonTranslationsModel::beSelect("patid,paid")->beWhere("paid",$product["paddons"],"IN")->beWhere("lid",$user["lid"])->beGetAll();
                            foreach($upoptions as $key => $upoption){
                                foreach($productaddons as $productaddon){
                                    if($key == $productaddon["paid"]){
                                        $productaddonmodules = ProductAddonModulesModel::beSelect("pamodulekey,pavalue")->beWhere("patid",$productaddon["patid"])->beWhere("pamodule",$userproduct["upmodule"])->beWhere("pakey",$upoption["key"])->beGetAll();
                                        foreach($productaddonmodules as $productaddonmodule){
                                            $addonmodules[$productaddonmodule["pamodulekey"]][] = $productaddonmodule["pavalue"];
                                        }
                                    }
                                }
                            }
                        }
                        $data = [
                            "userproduct" => $userproduct,
                            "productmodules" => $productmodules,
                            "addonmodules" => $addonmodules
                        ];
                        if($userproduct["sid"]){
                            $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
                            $server["spassword"] = beDecryptData($server["spassword"]);
                            $data["server"] = $server;
                        }
                        beModule::beLoadModule("product.{$userproduct['upmodule']}");
                        if($upstatus == 0){
                            if(beModule::beCheckModuleFunction($userproduct["upmodule"],"unsuspend")){
                                $response = beModule::beRunModuleFunction($userproduct["upmodule"],"unsuspend",$data);
                                if(!$response["status"]){
                                    UserProductLogsModel::beInsert([
                                        "uid" => $userproduct["uid"],
                                        "upid" => $userproduct["upid"],
                                        "upltype" => "order_unsuspend_module_error",
                                        "upldata" => json_encode([
                                            "iid" => (int)$invoice["iid"],
                                            "message" => $response["message"]
                                        ]),
                                        "upldateline" => BE_TIME
                                    ]);
                                }
                                UserProductLogsModel::beInsert([
                                    "uid" => $userproduct["uid"],
                                    "upid" => $userproduct["upid"],
                                    "upltype" => "order_unsuspend_module",
                                    "upldata" => json_encode([
                                        "iid" => (int)$invoice["iid"],
                                        "message" => $response["message"]
                                    ]),
                                    "upldateline" => BE_TIME
                                ]);
                            }
                        }
                        if(beModule::beCheckModuleFunction($userproduct["upmodule"],"extended")){
                            $response = beModule::beRunModuleFunction($userproduct["upmodule"],"extended",$data);
                            if(!$response["status"]){
                                UserProductLogsModel::beInsert([
                                    "uid" => $userproduct["uid"],
                                    "upid" => $userproduct["upid"],
                                    "upltype" => "order_extended_module_error",
                                    "upldata" => json_encode([
                                        "iid" => (int)$invoice["iid"],
                                        "message" => $response["message"]
                                    ]),
                                    "upldateline" => BE_TIME
                                ]);
                            }
                            UserProductLogsModel::beInsert([
                                "uid" => $userproduct["uid"],
                                "upid" => $userproduct["upid"],
                                "upltype" => "order_extended_module",
                                "upldata" => json_encode([
                                    "iid" => (int)$invoice["iid"],
                                    "message" => $response["message"]
                                ]),
                                "upldateline" => BE_TIME
                            ]);
                        }
                    }
                }
                return ["status" => true,"message" => beGetLang("invoice_paid"),"type" => 2];
            }
            case 3 : {
                InvoiceModel::beUpdate([
                    "istatus" => "1",
                    "ipaydate" => BE_TIME
                ])->beWhere("iid",$invoice["iid"])->beExecute();
                $invoiceitems = InvoiceItemModel::beWhere("iid",$invoice["iid"])->beWhere("iiobject","","!=")->beGetAll();
                foreach($invoiceitems as $item){
                    $item["iidata"] = json_decode($item["iidata"],true);
                    switch($item["iiobject"]){
                        case "Invoice" :
                            $this->cart_invoice_approve($item["iiobjectid"]);
                            break;
                        case "DepositMoney" :
                            $invoiceuser = Auth::beGetUser($invoice["uid"],"uid,money");
                            $invoiceuser["money"] += round(($item["iiunitprice"]*(100+$item["iitaxrate"]))/100,2);
                            AuthModel::beUpdate([
                                "money" => $invoiceuser["money"],
                            ])->beWhere("uid",$invoiceuser["uid"])->beExecute();
                            break;
                        case "Upgrade" :
                            $upid = (int)$item["iidata"]["upid"];
                            $newpid = (int)$item["iidata"]["newpid"];
                            $userproduct = UserProductModel::beSelect("pt.pname,pt.pmetadescription,p.paddons,p.pimage,p.pextend,be_user_products.*")->beWhere("uid",$user["uid"])->beWhere("lid",$user["lid"])->beWhere("upid",$upid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_user_products.pid INNER JOIN be_products as p ON p.pid = be_user_products.pid")->beGet();
                            if(!$userproduct){
                                return ["status" => false,"message" => beGetLang("order_not_found")];
                            }
                            if(!$userproduct["upmodule"]){
                                return ["status" => false,"message" => beGetLang("order_module_not_found")];
                            }
                            $newproduct = ProductModel::beSelect("be_products.pid,paddons,pt.pname")->beWhere("be_products.pid",$newpid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGet();
                            if(!$newproduct){
                                return beAjaxError(["message" => beGetLang("product_not_found")]);
                            }
                            $module = $userproduct["upmodule"];
                            $productmoduleslist = ProductModulesModel::beSelect("pmid,pmmodulekey,pmvalue")->beWhere("pid",$userproduct["pid"])->beWhere("pmmodule",$userproduct["upmodule"])->beGetAll();
                            $productmodules = [];
                            foreach($productmoduleslist as $productmodule){
                                $productmodules[$productmodule["pmmodulekey"]] = $productmodule["pmvalue"];
                            }
                            $productmoduleslist = ProductModulesModel::beSelect("pmid,pmmodulekey,pmvalue")->beWhere("pid",$newpid)->beWhere("pmmodule",$userproduct["upmodule"])->beGetAll();
                            $newproductmodules = [];
                            foreach($productmoduleslist as $productmodule){
                                $newproductmodules[$productmodule["pmmodulekey"]] = $productmodule["pmvalue"];
                            }
                            $upoptions = json_decode($userproduct["upoptions"],true);
                            $product["paddons"] = json_decode($userproduct["paddons"],true);
                            $addonmodules = [];
                            if($product["paddons"]){
                                $productaddons = ProductAddonTranslationsModel::beSelect("patid,paid")->beWhere("paid",$product["paddons"],"IN")->beWhere("lid",$user["lid"])->beGetAll();
                                foreach($upoptions as $key => $upoption){
                                    foreach($productaddons as $productaddon){
                                        if($key == $productaddon["paid"]){
                                            $productaddonmodule = ProductAddonModulesModel::beSelect("pamodulekey,pavalue")->beWhere("patid",$productaddon["patid"])->beWhere("pamodule",$userproduct["upmodule"])->beWhere("pakey",$upoption["key"])->beGet();
                                            if($productaddonmodule){
                                                $addonmodules[$productaddonmodule["pamodulekey"]][] = $productaddonmodule["pavalue"];
                                            }
                                        }
                                    }
                                }
                            }
                            $url = beGetRoute("client.userproduct.userproduct.show",["upid" => $userproduct["upid"]]);
                            $data = [
                                "userproduct" => $userproduct,
                                "productmodules" => $productmodules,
                                "newproductmodules" => $newproductmodules,
                                "addonmodules" => $addonmodules,
                                "url" => $url,
                            ];
                            $data = array_merge($data,$item["iidata"]);
                            if($userproduct["sid"]){
                                $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
                                $server["spassword"] = beDecryptData($server["spassword"]);
                                $data["server"] = $server;
                            }
                            beModule::beLoadModule("product.{$module}");
                            if(beModule::beCheckModuleFunction($module,"upgrade")){
                                $response = beModule::beRunModuleFunction($module,"upgrade",$data);
                                if(!$response["status"]){
                                    UserProductLogsModel::beInsert([
                                        "uid" => $userproduct["uid"],
                                        "upid" => $userproduct["upid"],
                                        "upltype" => "invoice_upgrade_error",
                                        "upldata" => json_encode([
                                            "iid" => (int)$invoice["iid"],
                                            "message" => $response["message"]
                                        ]),
                                        "upldateline" => BE_TIME
                                    ]);
                                }
                                UserProductLogsModel::beInsert([
                                    "uid" => $userproduct["uid"],
                                    "upid" => $userproduct["upid"],
                                    "upltype" => "invoice_upgrade",
                                    "upldata" => json_encode([
                                        "iid" => (int)$invoice["iid"],
                                        "message" => $response["message"]
                                    ]),
                                    "upldateline" => BE_TIME
                                ]);
                            }
                            $updatedata["pid"] = $newproduct["pid"];
                            $updatedata["upprice"] = $item["iidata"]["newprice"];
                            $upoptions["period"]["price"] = $item["iidata"]["newprice"];
                            $updatedata["upoptions"] = json_encode($upoptions,JSON_UNESCAPED_UNICODE);
                            if($userproduct["upname"] == $userproduct["pname"]){
                                $updatedata["upname"] = $newproduct["pname"];
                            }
                            UserProductModel::beUpdate($updatedata)->beWhere("upid",$userproduct["upid"])->beExecute();
                            break;
                        case "Module" :
                            $upid = (int)$item["iiobjectid"];
                            $userproduct = UserProductModel::beSelect("pt.pname,pt.pmetadescription,p.paddons,p.pimage,p.pextend,be_user_products.*")->beWhere("uid",$user["uid"])->beWhere("lid",$user["lid"])->beWhere("upid",$upid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_user_products.pid INNER JOIN be_products as p ON p.pid = be_user_products.pid")->beGet();
                            if(!$userproduct){
                                return ["status" => false,"message" => beGetLang("order_not_found")];
                            }
                            if(!$userproduct["upmodule"]){
                                return ["status" => false,"message" => beGetLang("order_module_not_found")];
                            }
                            $module = $userproduct["upmodule"];
                            $productmoduleslist = ProductModulesModel::beSelect("pmid,pmmodulekey,pmvalue")->beWhere("pid",$userproduct["pid"])->beWhere("pmmodule",$userproduct["upmodule"])->beGetAll();
                            $productmodules = [];
                            foreach($productmoduleslist as $productmodule){
                                $productmodules[$productmodule["pmmodulekey"]] = $productmodule["pmvalue"];
                            }
                            $product["paddons"] = json_decode($userproduct["paddons"],true);
                            $addonmodules = [];
                            if($product["paddons"]){
                                $upoptions = json_decode($userproduct["upoptions"],true);
                                $productaddons = ProductAddonTranslationsModel::beSelect("patid,paid")->beWhere("paid",$product["paddons"],"IN")->beWhere("lid",$user["lid"])->beGetAll();
                                foreach($upoptions as $key => $upoption){
                                    foreach($productaddons as $productaddon){
                                        if($key == $productaddon["paid"]){
                                            $productaddonmodule = ProductAddonModulesModel::beSelect("pamodulekey,pavalue")->beWhere("patid",$productaddon["patid"])->beWhere("pamodule",$userproduct["upmodule"])->beWhere("pakey",$upoption["key"])->beGet();
                                            if($productaddonmodule){
                                                $addonmodules[$productaddonmodule["pamodulekey"]][] = $productaddonmodule["pavalue"];
                                            }
                                        }
                                    }
                                }
                            }
                            $url = beGetRoute("client.userproduct.userproduct.show",["upid" => $userproduct["upid"]]);
                            $data = [
                                "userproduct" => $userproduct,
                                "productmodules" => $productmodules,
                                "addonmodules" => $addonmodules,
                                "url" => $url,
                                "invoice" => $invoice,
                                "item" => $item
                            ];
                            if($userproduct["sid"]){
                                $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
                                $server["spassword"] = beDecryptData($server["spassword"]);
                                $data["server"] = $server;
                            }
                            beModule::beLoadModule("product.{$module}");
                            if(beModule::beCheckModuleFunction($module,"special_invoice")){
                                $response = beModule::beRunModuleFunction($module,"special_invoice",$data);
                                if(!$response["status"]){
                                    UserProductLogsModel::beInsert([
                                        "uid" => $userproduct["uid"],
                                        "upid" => $userproduct["upid"],
                                        "upltype" => "invoice_special_module_error",
                                        "upldata" => json_encode([
                                            "iid" => (int)$invoice["iid"],
                                            "message" => $response["message"]
                                        ]),
                                        "upldateline" => BE_TIME
                                    ]);
                                }
                                UserProductLogsModel::beInsert([
                                    "uid" => $userproduct["uid"],
                                    "upid" => $userproduct["upid"],
                                    "upltype" => "invoice_special_module",
                                    "upldata" => json_encode([
                                        "iid" => (int)$invoice["iid"],
                                        "message" => $response["message"]
                                    ]),
                                    "upldateline" => BE_TIME
                                ]);
                            }
                        break;
                    }
                }
                return ["status" => true,"message" => beGetLang("invoice_paid"),"type" => 3];
            }
        }
    }
    public function get_user_cart(){
        $userip = beRouter::$beUserIP;
        $cart = CartModel::beSelect("cbasket")->beWhere("cipadress",$userip)->beGet();
        if($cart){
            return json_decode($cart["cbasket"],true);
        }
        else{
            CartModel::beInsert([
                "cipadress" => $userip,
                "cbasket" => "[]",
                "cprocess" => "0",
                "cdateline" => BE_TIME
            ]);
            return [];
        }
    }
    public function set_user_cart($basket){
        beLanguage::beReadLang("cart");
        $userip = beRouter::$beUserIP;
        $cart = CartModel::beSelect("cid")->beWhere("cipadress",$userip)->beGet();
        if(!$cart){
            return ["success" => false,"message" => beGetLang("cart_empty")];
        }
        CartModel::beUpdate([
            "cbasket" => json_encode($basket,JSON_UNESCAPED_UNICODE)
        ])->beWhere("cid",$cart["cid"])->beExecute();
        return ["success" => true];
    }
    function get_user_cartstatus(){
        beLanguage::beReadLang("cart");
        $userip = beRouter::$beUserIP;
        $cart = CartModel::beSelect("cid")->beWhere("cprocess",$userip)->beGet();
        if(!$cart){
            return ["success" => false,"message" => beGetLang("cart_empty")];
        }
        return (int)$cart["cprocess"];
    }
    function set_user_cartstatus($status){
        beLanguage::beReadLang("cart");
        $userip = beRouter::$beUserIP;
        $cart = CartModel::beSelect("cid")->beWhere("cid",$userip)->beGet();
        if(!$cart){
            return ["success" => false,"message" => beGetLang("cart_empty")];
        }
        CartModel::beUpdate([
            "cprocess" => $status
        ])->beWhere("cid",$cart["cid"])->beExecute();
        return ["success" => true];
    }
    public function get_coupon($code,$type = 1,$uid = 0,$data = []){
        beLanguage::beReadLang("coupon");
        $user = Auth::beGetUser($uid);
        $coupon = CouponModel::beWhere("ccode",$code)->beGet();
        if(!$coupon){
            return ["status" => false,"message" => beGetLang("coupon_not_found")];
        }
        switch($type){
            case 1 :
                if($coupon["lid"] && $coupon["lid"] != $user["lid"]){
                    return ["status" => false,"message" => beGetLang("coupon_not_using_country")];
                }
                if($coupon["usage"] > $coupon["climit"]){
                    return ["status" => false,"message" => beGetLang("coupon_limit_full")];
                }
                if($coupon["cenddateline"] < BE_TIME){
                    return ["status" => false,"message" => beGetLang("coupon_date_out")];
                }
                return ["status" => true,"message" => "beValidated1","cpid" => $coupon["cpid"],"cdiscounttype" => $coupon["cdiscounttype"],"cdiscount" => $coupon["cdiscount"],"cproducts" => $coupon["cproducts"]];
            case 2 :
                $total = $data["price"];
                $itemcount = $data["itemcount"];
                if($coupon["cminprice"] && $total < $coupon["cminprice"]){
                    return ["status" => false,"message" => beGetLang("coupon_price_less_than_min",["minprice" => $coupon["cminprice"]])];
                }
                if($coupon["cmaxprice"] && $total > $coupon["cmaxprice"]){
                    return ["status" => false,"message" => beGetLang("coupon_price_greater_than_max",["minprice" => $coupon["cmaxprice"]])];
                }
                if($coupon["citemcount"] && $itemcount > $coupon["citemcount"]){
                    return ["status" => false,"message" => beGetLang("coupon_item_greater_than_max",["itemcount" => $coupon["citemcount"]])];
                }
                return ["status" => true,"message" => "beValidated2","cpid" => $coupon["cpid"]];
                break;
        }
    }
    public function calculate_basket($data,$discountype = 0,$discountprice = 0,$uid = 0,$compulsory = 0,$htmladdons = 0,$adminhtmladdons = false){
        beLanguage::beReadLang("product");
        $user = Auth::beGetUser($uid);
        $pid = (int)$data["pid"];
        $periodkey = (int)$data["period"];
        if(!$pid){
            return ["status" => false,"message" => beGetLang("product_not_found")];
        }
        $product = ProductModel::beSelect("be_products.pid,sid,pperiods,pimage,paddons,pstock,pstocktype,pactive,psold,pmodule,pname,pdescription,pslug")->beWhere("lid",$user["lid"])->beWhere("be_products.pid",$pid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGet();
        if(!$product){
            return ["status" => false,"message" => beGetLang("product_not_found")];
        }
        if($product["pstock"] != -1 && $product["pstock"]-$product["pactive"] < 1){
            return ["status" => false,"message" => beGetLang("product_not_have_stock")];
        }
        $pperiods = json_decode($product["pperiods"],true);
        if(!$pperiods[$user["cid"]]){
            return ["status" => false,"message" => beGetLang("product_periods_not_found")];
        }
        $pperiods = $pperiods[$user["cid"]];
        if(!array_key_exists($periodkey,$pperiods)){
            return ["status" => false,"message" => beGetLang("product_period_not_found")];
        }
        $periods = ProductModel::beGetPeriods();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon,ctaxrate");
        $period = $pperiods[$periodkey];
        $originalprice = $period["oprice"];
        if($period["ocid"] != $user["cid"]){
            $originalprice = $period["oprice"];
            $period["oprice"] = beConvertCurrencie($period["oprice"],$period["ocid"],$user["cid"]);
        }
        $productprice = $period["oprice"];
        $periodoptions = [$product["pname"],$period["operiodtime"],$periods[$period["operiod"]],beMoneyFormat($period["oprice"])];
        $optionsdata["period"] = [
            "key" => $periodkey,
            "price" => round($originalprice,2),
            "currency" => $period["ocid"],
            "periodcounter" => $period["operiodtime"],
            "periodfullcounter" => $period["operiodtime"],
            "time" => $period["operiodtime"],
            "period" => $period["operiod"]
        ];
        $paddons = json_decode($product["paddons"],true);
        $addonoptions = [];
        $addonoptionshtml = "";
        if($paddons){
            $productaddons = ProductAddonTranslationsModel::beSelect("patid,paid,paname,pacode,padescription,patype,paoptions,pacompulsory,paovveridecurrency,pamatchperiod")->beWhere("lid",$user["lid"])->beWhere("paid",$paddons,"IN")->beWhere("pastatus",1)->beOrder("paposition","ASC")->beGetAll();
            if(!$productaddons){
                return ["status" => false,"message" => beGetLang("product_addons_not_found")];
            }
            foreach($productaddons as $productaddon){
                $addonkey = $data[$productaddon["paid"]];
                switch($productaddon["patype"]){
                    case "text" :
                        if(!$addonkey && $_GET[$productaddon["paid"]]){
                            $addonkey = $_GET[$productaddon["paid"]];
                        }
                        if(!$addonkey && $_GET[$productaddon["pacode"]]){
                            $addonkey = $_GET[$productaddon["pacode"]];
                        }
                        if(!$addonkey && $_POST[$productaddon["paid"]]){
                            $addonkey = $_POST[$productaddon["paid"]];
                        }
                        if(!$addonkey && $_POST[$productaddon["pacode"]]){
                            $addonkey = $_POST[$productaddon["pacode"]];
                        }
                        if(!$addonkey && $_COOKIE[$productaddon["paid"]]){
                            $addonkey = $_COOKIE[$productaddon["paid"]];
                        }
                        if(!$addonkey && $_COOKIE[$productaddon["pacode"]]){
                            $addonkey = $_COOKIE[$productaddon["pacode"]];
                        }
                        if($htmladdons){
                            if(!$adminhtmladdons){
                                $addonoptionshtml .= beGetView("product.configurerow",["productaddon" => $productaddon,"paoptions" => [],"usercid" => 0,"usercurrency" => [],"periods" => [],"currencies" => [],"addonkey" => $addonkey]);
                            }
                            else{
                                $addonoptionshtml .= beGetView("product.configurerow-admin",["productaddon" => $productaddon,"paoptions" => [],"usercid" => 0,"usercurrency" => [],"periods" => [],"currencies" => [],"addonkey" => $addonkey]);
                            }
                        }
                        if(!$addonkey){
                            $addonkey = "Girilmedi!";
                        }
                        $optionsdata[$productaddon["paid"]] = [
                            "key" => $addonkey,
                            "code" => $productaddon["pacode"]
                        ];
                        $addonoptions[] = [$productaddon["paname"],$addonkey,"","",0,$productaddon["pacode"]];
                        break;
                    case "select" :
                        if(!$addonkey && $_GET[$productaddon["paid"]]){
                            $addonkey = $_GET[$productaddon["paid"]];
                        }
                        if(!$addonkey && $_COOKIE[$productaddon["paid"]]){
                            $addonkey = $_COOKIE[$productaddon["paid"]];
                        }
                        $getpacode = $_GET[$productaddon["pacode"]];
                        $postpacode = $_POST[$productaddon["pacode"]];
                        $cookiepacode = $_COOKIE[$productaddon["pacode"]];
                        $paoptions = json_decode($productaddon["paoptions"],true);
                        foreach($paoptions as $key => $paoption){
                            if($getpacode == $paoption["oname"]){
                                $addonkey = $key;
                            }
                            if($postpacode == $paoption["oname"]){
                                $addonkey = $key;
                            }
                            if($cookiepacode == $paoption["oname"]){
                                $addonkey = $key;
                            }
                            if($productaddon["pamatchperiod"] == 1 && $paoption["operiod"] != "none"){
                                $paoptions[$key]["operiod"] = $period["operiod"];
                                if($paoption["operiod"] == $period["operiod"]){
                                    $paoptions[$key]["oprice"] *= $period["operiodtime"];
                                    $paoptions[$key]["operiodtime"] = $period["operiodtime"];
                                }
                                else{
                                    $convertperiod = ProductModel::beConvertPeriods($period["operiod"],$paoption["operiod"]);
                                    $paoptions[$key]["oprice"] *= $convertperiod;
                                    $paoptions[$key]["operiodcounter"] = $convertperiod;
                                }
                            }
                        }
                        if($addonkey == 0){
                            if($compulsory && $productaddon["pacompulsory"]){
                                return ["status" => false,"message" => beGetLang("product_compulsory",["addonname" => $productaddon["paname"]])];
                            }
                            if($htmladdons){
                                if(!$adminhtmladdons){
                                    $addonoptionshtml .= beGetView("product.configurerow",["productaddon" => $productaddon,"paoptions" => $paoptions,"usercid" => $user["cid"],"usercurrency" => $currencies[$user["cid"]],"periods" => $periods,"currencies" => $currencies,"addonkey" => $addonkey]);
                                }
                                else{
                                    $addonoptionshtml .= beGetView("product.configurerow-admin",["productaddon" => $productaddon,"paoptions" => $paoptions,"usercid" => $user["cid"],"usercurrency" => $currencies[$user["cid"]],"periods" => $periods,"currencies" => $currencies,"addonkey" => $addonkey]);
                                    
                                }
                            }
                            $addonoptions[] = [$productaddon["paname"],beGetLang("product_not_want"),0,0,0,$productaddon["pacode"]];
                            continue;
                        }
                        if(!array_key_exists($addonkey,$paoptions)){
                            return ["status" => false,"message" => beGetLang("product_option_not_found")];
                        }
                        $addon = $paoptions[$addonkey];
                        if($addon["ocid"] == $user["cid"]){
                            $addonprice = $addon["oprice"];
                        }
                        else{
                            $addonprice = beConvertCurrencie($addon["oprice"],$addon["ocid"],$user["cid"]);
                        }
                        $optionsdata[$productaddon["paid"]] = [
                            "key" => $addonkey,
                            "code" => $productaddon["pacode"],
                            "name" => $addon["oname"],
                            "price" => round($addon["oprice"],2),
                            "currency" => $addon["ocid"],
                            "periodcounter" => $addon["operiodtime"],
                            "periodfullcounter" => $addon["operiodtime"],
                            "time" => $addon["operiodtime"],
                            "period" => $addon["operiod"]
                        ];
                        if($htmladdons){
                            if(!$adminhtmladdons){
                                $addonoptionshtml .= beGetView("product.configurerow",["productaddon" => $productaddon,"paoptions" => $paoptions,"usercid" => $user["cid"],"usercurrency" => $currencies[$user["cid"]],"periods" => $periods,"currencies" => $currencies,"addonkey" => $addonkey]);
                            }
                            else{
                                $addonoptionshtml .= beGetView("product.configurerow-admin",["productaddon" => $productaddon,"paoptions" => $paoptions,"usercid" => $user["cid"],"usercurrency" => $currencies[$user["cid"]],"periods" => $periods,"currencies" => $currencies,"addonkey" => $addonkey]);
                            }
                        }
                        $addonoptions[] = [$productaddon["paname"],$addon["oname"],$addon["operiodtime"],$periods[$addon["operiod"]],beMoneyFormat($addonprice),$productaddon["pacode"]];
                        $productprice += $addonprice; 
                        break;
                }
            }
        }
        $havediscount = false;
        $taxrate = $currencies[$user["cid"]]["ctaxrate"];
        switch($discountype){
            case 0 :
                $lastprice = $productprice;
                break;
            case 1 :
                $havediscount = true;
                $lastprice = round($productprice*(100-$discountprice)/100,2);
                $discountprice = $productprice-$lastprice;
                break;
            case 2 :
                $havediscount = true;
                $lastprice = $productprice-$discountprice;
                if($lastprice < 0){
                    $lastprice = 0;
                }
                break;
        }
        return [
            "status" => true,
            "product" => $product,
            "period" => $period,
            "periodoptions" => $periodoptions,
            "addonoptions" => $addonoptions,
            "addonoptionshtml" => $addonoptionshtml,
            "optionsdata" => $optionsdata,
            "productprice" => $lastprice,
            "productmainprice" => $productprice,
            "discountprice" => $discountprice,
            "havediscount" => $havediscount,
            "totalprice" => $lastprice,
            "currency" => (int)$user["cid"],
            "icon" => $currencies[$user["cid"]]["cicon"],
            "taxrate" => $taxrate
        ];
    }
    public function calculate_basket_nextprice($data,$currency = 1){
        $price = 0;
        $periodtype = $data["period"]["period"];
        $itemcount = 0;
        foreach($data as $key => $value){
            if($value["price"] == 0){
                continue;
            }
            if($value["period"] == "none"){
                continue;
            }
            if($value["periodcounter"]-1 == 0){
                $itemcount += 1;
                if($value["currency"] == $currency){
                    $price += $value["price"];
                }
                else{
                    $price += beConvertCurrencie($value["price"],$value["currency"],$currency);
                }
            }
        }
        if($itemcount == 0){
            foreach($data as $key => $value){
                if($value["price"] == 0){
                    continue;
                }
                if($value["period"] != $periodtype){
                    continue;
                }
                if($value["currency"] == $currency){
                    $price += $value["price"];
                }
                else{
                    $price += beConvertCurrencie($value["price"],$value["currency"],$currency);
                }
            }
        }
        return $price;
    }
    public function calculate_extension_nextprice($upid = 0){
        $extensions = UserProductExtensionsModel::beSelect("upeid,cid,upename,upeunitcount,upeunitprice,upeunittype,uperate,upetype,upestatus")->beWhere("upid",$upid)->beGetAll();
        if($extensions){
            $price = 0;
            $rate = 0;
            $basket = [];
            foreach($extensions as $extension){
                if($extension["upetype"] == "onetime" && $extension["upestatus"] == "1"){
                    continue;
                }
                $itemprice = $extension["upeunitprice"]*$extension["upeunitcount"];
                $price += $itemprice;
                if($extension["uperate"]){
                    $rate += $this->get_rate($itemprice,$extension["uperate"])["rate"];
                }
                $basket[] = [
                    "cid" => $extension["cid"],
                    "name" => $extension["upename"],
                    "unitprice" => $extension["upeunitprice"],
                    "unitcount" => $extension["upeunitcount"],
                    "taxrate" => $extension["uperate"],
                    "unittype" => $extension["upeunittype"]
                ];
            }
            return [
                "status" => true,
                "price" => $price,
                "rate" => $rate,
                "basket" => $basket
            ];
        }
        else{
            return [
                "status" => false
            ];
        }
    }
    public function get_rate($price,$rate){
        return ["status" => true,"rate" => $price*$rate/100];
    }
}
?>