<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
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\ProductModel;
use App\System\Model\ProductModulesModel;
use App\System\Model\ServerModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserProductCancellationsModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\beAlert;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beMail;
use App\System\Vendor\beModule;
use App\System\Vendor\bePlugin;
use App\System\Vendor\beSms;

class UserProductController extends beContoller {
    public function userproducts(){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("order");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_userproducts"));
        $user = Auth::beGetUser();
        $product_count = 0;
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $userproductstatus = UserProductModel::beGetUserProductStatus();
        $cart = new CartController();
        beModule::beLoadModules("payment");
        $modules = beModule::$beModules;
        $automated_payment_modules = [];
        foreach($modules as $name => $module){
            if($module["module"]->options["order_auto_pay"] == true){
                $automated_payment_modules[$name] = $module["info"];
            }
        }
        $userproducts = UserProductModel::beSelect("p.pextend,p.pextendauto,pt.pname,be_user_products.*")->beWhere("uid",$user["uid"])->beWhere("lid",$user["lid"])->beWhere("upstatus","-1","!=")->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")->beGetAll();
        $userproducts = bePlugin::beRunHook("clientarea_userproducts_pre",["userproducts" => $userproducts])["userproducts"];
        foreach($userproducts as $key => $userproduct){
            $endtime = $userproduct["upetime"];
            if($endtime){
                $userproducts[$key]["enddate"] = beDisplayTime($endtime);
                $day = round(($endtime-BE_TIME)/86400);
                if($endtime > BE_TIME){
                    $userproducts[$key]["endtext"] = beGetLang("order_days_left",["day" => $day]);
                    $userproducts[$key]["endclass"] = "text-success";
                }   
                else{
                    $day *= -1;
                    $userproducts[$key]["endtext"] = beGetLang("order_days_passed",["day" => $day]);
                    $userproducts[$key]["endclass"] = "text-danger";
                }
            }   
            else{
                $userproducts[$key]["endtext"] = "∞";
                $userproducts[$key]["enddate"] = "∞";
                $userproducts[$key]["upprice"] = "∞";
            }
            $extension = $cart->calculate_extension_nextprice($userproduct["upid"]);
            if($extension["status"]){
                $userproducts[$key]["upprice"] += $extension["price"];
            }
            if($userproduct["upstatus"] != -1){
                $product_count += 1;
            }
            
        }
        $cancellationstatus = UserProductCancellationsModel::beGetUserProductCancellationStatus();
        $cancellationtypes = UserProductCancellationsModel::beGetUserProductCancellationTypes();
        $userproductcancellations = UserProductCancellationsModel::beWhere("uid",$user["uid"])->beWhere("upcstatus","-1","!=")->beGetAll();
        foreach($userproductcancellations as $key => $userproductcancellation){
            foreach($userproducts as $userproduct){
                if($userproductcancellation["upid"] == $userproduct["upid"]){
                    $userproductcancellations[$key]["userproduct"] = $userproduct;
                    break;
                }
            }
        }
        $userproducts = bePlugin::beRunHook("clientarea_userproducts_post",["userproducts" => $userproducts])["userproducts"];
        beSetHeaderContent("",1);
        return beGetView("clientarea.userproduct.userproducts",["userproducts" => $userproducts,"userproductstatus" => $userproductstatus,"userproductcancellations" => $userproductcancellations,"cancellationstatus" => $cancellationstatus,"cancellationtypes" => $cancellationtypes,"automated_payment_modules" => $automated_payment_modules,"product_count" => $product_count,"currencies" => $currencies]); 
    }
    public function show($upid = 0,$page = ""){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("order");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_userproducts"),beGetRoute("client.userproduct.userproducts"));
        $user = Auth::beGetUser();
        $userproduct = UserProductModel::beSelect("pt.pname,pt.pmetadescription,p.paddons,p.pimage,p.pextend,p.pupgrade,be_user_products.*")->beWhere("upid",$upid)->beWhere("uid",$user["uid"])->beWhere("lid",$user["lid"])->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){
            beError(beGetLang("order"),beGetLang("order_not_found"));
        }
        if($userproduct["upstatus"] != 2){
            beError(beGetLang("order"),beGetLang("order_not_found"));
        }
        if(!$userproduct["upmodule"]){
            beError(beGetLang("order"),beGetLang("order_module_not_found"));
        }
        $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"];
        }
        $userproduct["paddons"] = json_decode($userproduct["paddons"],true);
        $addonmodules = [];
        if($userproduct["paddons"]){
            $upoptions = json_decode($userproduct["upoptions"],true);
            $productaddons = ProductAddonTranslationsModel::beSelect("patid,paid")->beWhere("paid",$userproduct["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"];
                        }
                    }
                }
            }
        }
        $title = $userproduct["pname"];
        $url = beGetRoute("client.userproduct.userproduct.show",["upid" => $userproduct["upid"]]);
        $data = [
            "userproduct" => $userproduct,
            "productmodules" => $productmodules,
            "addonmodules" => $addonmodules,
            "page" => $page,
            "url" => $url,
            "title" => $title
        ];
        if($userproduct["sid"]){
            $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
            $server["spassword"] = beDecryptData($server["spassword"]);
            $data["server"] = $server;
        }
        NavController::beAddBreadcumb($userproduct["pname"],$url);
        beModule::beLoadModule("product.{$userproduct['upmodule']}");
        if(!beModule::beCheckModuleFunction($userproduct["upmodule"],"clientarea")){
            beError(beGetLang("order"),beGetLang("order_module_function_not_found"));
        }
        $response = beModule::beRunModuleFunction($userproduct["upmodule"],"clientarea",$data);
        if(!$response["status"]){
            beError(beGetLang("order"),$response["message"]);
        }
        beSetHeaderContent("",1);
        return beGetView("clientarea.userproduct.show",["userproduct" => $userproduct,"title" => $response["title"],"content" => $response["content"],"menuitems" => $response["menuitems"],"menus" => $response["menus"]]);
    }
    public function show_post(){
        beLanguage::beReadLang("order");
        $user = Auth::beGetUser();
        $upid = (int)$_POST["upid"];
        $userproduct = UserProductModel::beSelect("pt.pname,p.paddons,be_user_products.*")->beWhere("upid",$upid)->beWhere("uid",$user["uid"])->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 beAjaxError(["message" => beGetLang("order_not_found")]);
        }
        if($userproduct["upstatus"] != 2){
            return beAjaxError(["message" => beGetLang("order_not_found")]);
        }
        if(!$userproduct["upmodule"]){
            return beAjaxError(["message" => beGetLang("order_module_not_found")]);
        }
        $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"]){
                        $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,
            "url" => beGetRoute("client.userproduct.userproduct.show",["upid" => $userproduct["upid"]]),                   
        ];
        if($userproduct["sid"]){
            $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
            $server["spassword"] = beDecryptData($server["spassword"]);
            $data["server"] = $server;
        }
        beModule::beLoadModule("product.{$userproduct['upmodule']}");
        $action = $_POST["action"];
        if(!beModule::beCheckModuleFunction($userproduct["upmodule"],$action)){
            return beAjaxError(["message" => beGetLang("order_module_function_not_found")]);
        }
        $response = beModule::beRunModuleFunction($userproduct["upmodule"],$action,$data);
        return $response;
    }
    public function options_post(){
        beLanguage::beReadLang("order");
        $upid = (int)$_POST["upid"];
        $user = Auth::beGetUser();
        $userproduct = UserProductModel::beSelect("upid,upextendauto")->beWhere("upid",$upid)->beWhere("uid",$user["uid"])->beGet();
        if(!$userproduct){
            return beAjaxError(["message" => beGetLang("order_not_found")]);
        }
        $upextendauto = (int)$_POST["upextendauto"];
        if(!in_array($upextendauto,[0,1])){
            return beAjaxError(["message" => beGetLang("order_autoextend_type_not_found")]);
        }
        UserProductModel::beUpdate(["upextendauto" => $upextendauto])->beWhere("upid",$userproduct["upid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("order_updated")]);
    }
    public function process_post(){
        beLanguage::beReadLang("order");
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("invoice");
        $user = Auth::beGetUser();
        $upid = (int)$_POST["upid"];
        $userproduct = UserProductModel::beSelect("upid,uid,pid,sid,updata,upoptions,upstatus,upprice,uptaxrate,upprocess,upmodule,upetime")->beWhere("upid",$upid)->beWhere("uid",$user["uid"])->beGet();
        if(!$userproduct){
            return beAjaxError(["message" => beGetLang("order_not_found")]);
        }
        UserProductModel::beUpdate(["upprocess" => "1"])->beWhere("upid",$userproduct["upid"])->beExecute();
        $updata = json_decode($userproduct["updata"],true);
        $upoptions = json_decode($userproduct["upoptions"],true);
        $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();
        $pdata = json_decode($product["pdata"],true);
        $poptions = json_decode($product["poptions"],true);
        $action = $_POST["action"];
        switch($action){
            case "manage" :
                if($userproduct["upprocess"] == 1){
                    return beAjaxError(["message" => beGetLang("order_on_process")]);
                }
                switch($userproduct["upstatus"]){
                    case 1 : {
                        if(!$userproduct["upmodule"]){
                            return beAjaxError(["message" => beGetLang("order_module_not_found")]);
                        }
                        beModule::beLoadModule("product.{$userproduct['upmodule']}");
                        if(!beModule::beCheckModuleFunction($userproduct["upmodule"],"create")){
                            return beAjaxError(["message" => beGetLang("order_module_function_not_found")]);
                        }
                        $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;
                        }
                        $response = beModule::beRunModuleFunction($userproduct["upmodule"],"create",$data);
                        if(!$response["status"]){
                            return beAjaxError(["message" => $response["message"]]);
                        }
                        UserProductModel::beUpdate(["upprocess" => "0"])->beWhere("upid",$userproduct["upid"])->beExecute();
                        if(!$response["delete"]){
                            UserProductModel::beUpdate([
                                "upstatus" => 2
                            ])->beWhere("upid",$upid)->beExecute();
                        }
                        else{
                            UserProductModel::beDelete()->beWhere("upid",$upid)->beExecute();
                        }
                        $sitename = beGetConfig("sitename");
                        $orderurl = beGetRoute("client.userproduct.userproduct",["upid" => $upid]);
                        $messages = MessageTemplateModel::beGetMessages("order_activated",1)["order_activated"];
                        $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$userproduct["uid"])->beGet();
                        $uisettings = json_decode($userinfo["uisettings"],true);
                        if($messages["alert"] && $uisettings["notification_alert"]){
                            $message = str_replace(["{sitename}","{productname}","{namesurname}","{orderurl}"],[$sitename,$product["pname"],$user["name"]." ".$user["surname"],$response["activisioninfo"],$orderurl],$messages["alert"]["mttmessage"]);
                            beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),$orderurl,$userinfo["uid"]);
                        }
                        if($messages["sms"] && $uisettings["sms_alert"]){
                            $message = str_replace(["{sitename}","{productname}","{namesurname}","{orderurl}"],[$sitename,$product["pname"],$user["name"]." ".$user["surname"],$response["activisioninfo"],$orderurl],$messages["sms"]["mttmessage"]);
                            beSms::beCreateSms($message,1,$userinfo["uid"]);
                        }
                        if($messages["mail"] && $uisettings["mail_alert"]){
                            $message = str_replace(["{sitename}","{productname}","{namesurname}","{activisioninfo}","{orderurl}"],[$sitename,$product["pname"],$user["name"]." ".$user["surname"],$response["activisioninfo"],$orderurl],$messages["mail"]["mttmessage"]);
                            beMail::beCreateMail($messages["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                        }
                        return beAjaxSuccess($response);
                        break;
                    }
                    case 2 : {         
                        if(!$userproduct["upmodule"]){
                            return beAjaxError(["message" => beGetLang("order_module_not_found")]);
                        }
                        beModule::beLoadModule("product.{$userproduct['upmodule']}");
                        if(!beModule::beCheckModuleFunction($userproduct["upmodule"],"create")){
                            return beAjaxError(["message" => beGetLang("order_module_function_not_found")]);
                        }
                        $data = [
                            "userproduct" => $userproduct                      
                        ];
                        if($userproduct["sid"]){
                            $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
                            $server["spassword"] = beDecryptData($server["spassword"]);
                            $data["server"] = $server;
                        }
                        $response = beModule::beRunModuleFunction($userproduct["upmodule"],"manage",$data);
                        if(!$response["status"]){
                            return beAjaxError(["message" => $response["message"]]);
                        }
                        UserProductModel::beUpdate(["upprocess" => "0"])->beWhere("upid",$userproduct["upid"])->beExecute();
                        return beAjaxSuccess($response);
                        break;
                    }
                    default : 
                        return beAjaxError(["message" => beGetLang("order_on_suspend")]);
                        break;
                }
                UserProductModel::beUpdate(["upprocess" => "0"])->beWhere("upid",$userproduct["upid"])->beExecute();
                break;
            case "extend" :
                UserProductModel::beUpdate(["upprocess" => "0"])->beWhere("upid",$userproduct["upid"])->beExecute();
                if($product["pextend"] != 1){
                    UserProductModel::beUpdate(["upprocess" => "0"])->beWhere("upid",$userproduct["upid"])->beExecute();
                    return beAjaxError(["message" => beGetLang("product_can_extend_by_system")]);  
                }
                if(!$userproduct["upetime"]){
                    UserProductModel::beUpdate(["upprocess" => "0"])->beWhere("upid",$userproduct["upid"])->beExecute();
                    return beAjaxError(["message" => beGetLang("product_cant_extend")]);                 
                }         
                $order = new OrderController();
                $response = $order->create_order_invoice($userproduct["upid"],"extend");
                if(!$response["status"]){
                    $extradata = [];
                    if($response["iid"]){
                        $extradata["url"] = beGetRoute("client.invoice.invoice",["iid" => $response["iid"]]);
                    }
                    return beAjaxError(array_merge(["message" => $response["message"]],$extradata));
                }
                return beAjaxSuccess(["message" => beGetLang("invoice_created"),"url" => beGetRoute("client.invoice.invoices.unpaid")]);
                break;          
        }
    }
    public function upgrade($upid = 0){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("order");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_userproducts"),beGetRoute("client.userproduct.userproducts"));
        $user = Auth::beGetUser();
        $userproduct = UserProductModel::beSelect("pt.pname,pt.pmetadescription,p.paddons,p.pimage,p.pextend,p.pupgrade,p.pupgradeproducts,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){
            beError(beGetLang("order"),beGetLang("order_not_found"));
        }
        if(!$userproduct["pupgrade"]){
            beError(beGetLang("order"),beGetLang("order_upgrade_disabled"));
        }
        if(!$userproduct["upmodule"]){
            beError(beGetLang("order"),beGetLang("order_module_not_found"));
        }
        $invoiceitem = InvoiceItemModel::beSelect("iid")->beWhere("iiobjectid",$userproduct["upid"])->beWhere("iiobject","ExtendOrder")->beOrder("iiid","DESC")->beLimit(1)->beGet();
        if($invoiceitem){
            $invoice = InvoiceModel::beSelect("iid,cid,iname,iprice")->beWhere("iid",$invoiceitem["iid"])->beWhere("istatus","0")->beGet();
            if($invoice){
                beError(beGetLang("order"),beGetLang("order_upgrade_disabled_while_extend"));
            }
        }
        $userproduct["pupgradeproducts"] = json_decode($userproduct["pupgradeproducts"],true);
        $url = beGetRoute("client.userproduct.userproduct.show",["upid" => $userproduct["upid"]]);
        NavController::beAddBreadcumb($userproduct["pname"],$url);
        beModule::beLoadModule("product.{$userproduct['upmodule']}");
        if(!beModule::beCheckModuleFunction($userproduct["upmodule"],"upgrade")){
            beError(beGetLang("order"),beGetLang("order_module_function_not_found"));
        }
        $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();
        beSetHeaderContent("",1);
        return beGetView("clientarea.userproduct.upgrade",["userproduct" => $userproduct,"products" => $products]);
    }
    public function upgrade_post(){
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("order");
        beLanguage::beReadLang("form");
        $user = Auth::beGetUser();
        $upid = (int)$_POST["upid"];
        $userproduct = UserProductModel::beSelect("pt.pname,pt.pmetadescription,p.paddons,p.pimage,p.pextend,p.pupgrade,p.pupgradeproducts,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 beAjaxError(["message" => beGetLang("order_not_found")]);
        }
        if(!$userproduct["pupgrade"]){
            return beAjaxError(["message" => beGetLang("order_upgrade_disabled")]);
        }
        if(!$userproduct["upmodule"]){
            return beAjaxError(["message" => beGetLang("order_module_not_found")]);
        }
        $invoiceitem = InvoiceItemModel::beSelect("iid")->beWhere("iiobjectid",$userproduct["upid"])->beWhere("iiobject","ExtendOrder")->beOrder("iiid","DESC")->beLimit(1)->beGet();
        if($invoiceitem){
            $invoice = InvoiceModel::beSelect("iid,cid,iname,iprice")->beWhere("iid",$invoiceitem["iid"])->beWhere("istatus","0")->beGet();
            if($invoice){
                return beAjaxError(["message" => beGetLang("order_upgrade_disabled_while_extend")]);
            }
        }
        $upoptions = json_decode($userproduct["upoptions"],true);
        if(!in_array($upoptions["period"]["period"],["month","year"])){
            return beAjaxError(["message" => beGetLang("order_upgrade_disabled")]);
        }
        $calculateperiod = "";
        $calculateperiodname = "";
        switch($upoptions["period"]["period"]){
            case "month" :
                $calculateperiod = "day";
                $calculateperiodname = "gün";
                break;
            case "year" :
                $calculateperiod = "month";
                $calculateperiodname = "ay";
                break;
            default :
                return beAjaxError(["message" => beGetLang("order_upgrade_disabled")]);
        }
        $currency = CurrencyModel::beGetCurrencies("cid,cicon",$userproduct["cid"]);
        $calculateperiodtime = ProductModel::beGetPeriodsTimes()[$calculateperiod];
        $fulltime = ProductModel::beGetPeriodsTimes()[$upoptions["period"]["period"]];
        $remainingtime = $userproduct["upetime"]-BE_TIME;
        $remainingprice = round($userproduct["upprice"]*$remainingtime/$fulltime,2);
        $remainingtimeuser = round($remainingtime/$calculateperiodtime);
        $step = (int)$_POST["step"];
        $pid = (int)$_POST["pid"];
        $newproduct = ProductModel::beSelect("be_products.pid,sid,pperiods,paddons,pmodule,pt.pname")->beWhere("be_products.pid",$pid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_products.pid")->beGet();
        if(!$newproduct){
            return beAjaxError(["message" => beGetLang("product_not_found")]);
        }
        $newproductperiod = "";
        $newproduct["pperiods"] = json_decode($newproduct["pperiods"],true);
        foreach($newproduct["pperiods"][$user["lid"]] as $period){
            if($period["operiod"] == $upoptions["period"]["period"]){
                $newproductperiod = $period;
                break;
            }
        }
        if(!$newproductperiod){
            return beAjaxError(["message" => beGetLang("order_upgrade_disabled")]);
        }
        if($newproductperiod["ocid"] != $userproduct["cid"]){
            $newproductperiod["oprice"] = beConvertCurrencie($newproductperiod["oprice"],$newproductperiod["ocid"],$userproduct["cid"]);
        }
        $newprice = ($newproductperiod["oprice"]*$upoptions["period"]["periodcounter"])-$remainingprice;
        switch($step){
            case 1 :
                $oldproductname = $userproduct["pname"];
                $newproductname = $newproduct["pname"];
                return beAjaxSuccess(["oldproductname" => $oldproductname,"newproductname" => $newproductname,"currency" => $currency,"calculateperiod" => $calculateperiod,"calculateperiodname" => $calculateperiodname,"remainingtimeuser" => $remainingtimeuser,"oldfullprice" => $upoptions["period"]["price"],"newfullprice" => $newproductperiod["oprice"],"newprice" => $newprice]);
                break;
            case 2 :
                $invoice = new InvoiceController();
                $iid = InvoiceModel::beInsert([
                    "cid" => $userproduct["cid"],
                    "uid" => $userproduct["uid"],
                    "iname" => $userproduct["upname"]." ".beGetLang("invoice_order_upgrade_name"),
                    "idescription" => beGetLang("invoice_order_upgrade_name"),
                    "itype" => "3",
                    "istatus" => "0",
                    "ibill" => "0",
                    "iprice" => 0,
                    "itaxprice" => 0,
                    "idiscount" => 0,
                    "ifee" => 0,
                    "idata" => "",
                    "iexpiredate" => BE_TIME > $userproduct["upetime"] ? (BE_TIME+86400*3):($userproduct["upetime"]+432000),
                    "idateline" => BE_TIME 
                ]);
                if($userproduct["uptag"]){
                    $userproduct["uptag"] = "(".$userproduct["uptag"].")";
                }
                InvoiceItemModel::beInsert([
                    "iid" => $iid,
                    "cid" => $userproduct["cid"],
                    "iiobject" => "Upgrade",
                    "iiobjectid" => $userproduct["upid"],
                    "iiname" => $userproduct["pname"]." -> ".$newproduct["pname"],
                    "iiunitprice" => $newprice,
                    "iiunitcount" => 1,
                    "iitaxrate" => $userproduct["uptaxrate"],
                    "iiunittype" => "none",
                    "iidata" => json_encode([
                        "upid" => (int)$userproduct["upid"],
                        "oldpid" => (int)$userproduct["pid"],
                        "newpid" => (int)$newproduct["pid"],
                        "newprice" => $newproductperiod["oprice"]
                    ]),
                    "iidateline" => BE_TIME
                ]);
                $invoice->beCalculateInvoicePrices($iid);
                return beAjaxSuccess(["message" => "Başarılı bir şekilde ürün yükseltim faturası oluşturuldu","url" => beGetRoute("client.invoice.invoice",["iid" => $iid])]);
                break;
        }
    }
    public function cancellation($upid = 0){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("order");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_userproducts"),beGetRoute("client.userproduct.userproducts"));
        $user = Auth::beGetUser();
        $userproduct = UserProductModel::beWhere("uid",$user["uid"])->beWhere("upid",$upid)->beGet();
        if(!$userproduct){
            beError(beGetLang("order"),beGetLang("order_not_found"));
        }
        beSetHeaderContent("",1);
        $cancellationtypes = UserProductCancellationsModel::beGetUserProductCancellationTypes();
        return beGetView("clientarea.userproduct.cancellation",["userproduct" => $userproduct,"cancellationtypes" => $cancellationtypes]);
    }
    public function cancel_post(){
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("order");
        beLanguage::beReadLang("form");
        $user = Auth::beGetUser();
        $upid = (int)$_POST["upid"];
        $userproduct = UserProductModel::beWhere("uid",$user["uid"])->beWhere("upid",$upid)->beGet();
        if(!$userproduct){
            return beAjaxError(["message" => beGetLang("order_not_found")]);
        }
        $type = $_POST["type"];
        $reason = htmlspecialchars($_POST["reason"]);
        $cancellationtypes = UserProductCancellationsModel::beGetUserProductCancellationTypes();
        if(!$cancellationtypes[$type] || !$reason){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $cancellation = UserProductCancellationsModel::beWhere("upid",$userproduct["upid"])->beWhere("upcstatus","-1","!=")->beGet();
        if($cancellation){
            return beAjaxError(["message" => beGetLang("order_cancellation_already_request")]);
        }
        UserProductCancellationsModel::beInsert([
            "upid" => $userproduct["upid"],
            "uid" => $user["uid"],
            "upctype" => $type,
            "upcstatus" => "0",
            "upcreason" => $reason,
            "upcdateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("order_cancellation_created"),"url" => beGetRoute("client.userproduct.userproducts")]);
    }
    public function canceldelete_post(){
        beLanguage::beReadLang("product");
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("order");
        $user = Auth::beGetUser();
        $upcid = (int)$_POST["upcid"];
        $cancellation = UserProductCancellationsModel::beSelect("upcid,upid,upctype,upcstatus")->beWhere("upcid",$upcid)->beGet();
        if(!$cancellation){
            return beAjaxError(["message" => beGetLang("order_cancellation_not_found")]);
        }
        if($cancellation["upctype"] == "now" && $cancellation["upcstatus"] == "1"){
            return beAjaxError(["message" => beGetLang("order_cancellation_finished")]);
        }
        $userproduct = UserProductModel::beWhere("uid",$user["uid"])->beWhere("upid",$cancellation["upid"])->beGet();
        if(!$userproduct){
            return beAjaxError(["message" => beGetLang("order_not_found")]);
        }
        UserProductCancellationsModel::beDelete()->beWhere("upcid",$cancellation["upcid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("order_cancellation_deleted"),"refresh" => 1]);
    }
}   
?>