<?php

namespace App\System\Task;

use App\System\Controller\OrderController;
use App\System\Model\InvoiceModel;
use App\System\Model\InvoiceItemModel;
use App\System\Model\MessageTemplateModel;
use App\System\Model\ProductModel;
use App\System\Model\ServerModel;
use App\System\Model\SettingModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserProductLogsModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\beAlert;
use App\System\Vendor\beMail;
use App\System\Vendor\beModule;
use App\System\Vendor\beSms;
use \Exception;

class OrderModuleActionsTask {
    public function run_task($task){
        $settings = SettingModel::beGetSettings("automation_order_terminate,automation_order_terminate_module");
        $messages = MessageTemplateModel::beGetMessages("order_suspended,order_terminated",1);
        $sitename = beGetConfig("sitename");
        $order = new OrderController();
        $timenow = BE_TIME;
        $timesearch = BE_TIME+864000;
        $userproducts = UserProductModel::beTable("be_user_products as up")->beSelect("up.*,p.pstock,p.pterminatetype,p.pactive,u.lid,u.name,u.surname,u.email")->beWhere("upstatus",["2","0"],"IN")->beWhere("upntime",$timesearch,"<")->beWhere("upstime",0,"!=")->beJoin("INNER JOIN be_products as p ON p.pid = up.pid INNER JOIN be_users as u ON u.uid = up.uid")->beGetAll();
        foreach($userproducts as $userproduct){
            $upsystemdata = json_decode($userproduct["upsystemdata"],true);
            $invoiceday = round(($userproduct["upntime"]-$timenow)/86400);
            $endday = round(($userproduct["upetime"]-$timenow)/86400);
            $userinfo = UserInfoModel::beSelect("uisettings")->beWhere("uid",$userproduct["uid"])->beGet();
            $uisettings = json_decode($userinfo["uisettings"],true);
            if($endday < 0 && $endday > $settings["automation_order_terminate"]*-1 && $userproduct["upstatus"] != "0"){
                if($uisettings["never_suspend"] == 1){
                    continue;
                }
                if($userproduct["upmodule"]){
                    beModule::beLoadModule("product.{$userproduct['upmodule']}");
                    if(beModule::beCheckModuleFunction($userproduct["upmodule"],"suspend")){
                        $data = [];
                        if($userproduct["sid"]){
                            $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
                            $server["spassword"] = beDecryptData($server["spassword"]);
                            $data["server"] = $server;
                        }
                        $data["userproduct"] = $userproduct;
                        $response = beModule::beRunModuleFunction($userproduct["upmodule"],"suspend",$data);
                        if(!$response["status"]){
                            UserProductLogsModel::beInsert([
                                "uid" => $userproduct["uid"],
                                "upid" => $userproduct["upid"],
                                "upltype" => "order_suspend_module_error",
                                "upldata" => json_encode([
                                    "message" => $response["message"]
                                ]),
                                "upldateline" => BE_TIME
                            ]);
                            continue;
                        }
                        UserProductLogsModel::beInsert([
                            "uid" => $userproduct["uid"],
                            "upid" => $userproduct["upid"],
                            "upltype" => "order_suspend_module",
                            "upldata" => json_encode([
                                "message" => $response["message"]
                            ]),
                            "upldateline" => BE_TIME
                        ]);
                    }
                }
                $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$userproduct["uid"])->beGet();
                $uisettings = json_decode($userinfo["uisettings"],true);
                if($messages["order_suspended"]["alert"] && $uisettings["notification_alert"]){
                    $message = str_replace(["{sitename}","{productname}","{namesurname}"],[$sitename,$userproduct["upname"]." ".$userproduct["uptag"],$userproduct["name"]." ".$userproduct["surname"]],$messages["order_suspended"]["alert"]["mttmessage"]);
                    beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),beGetRoute("client.userproduct.userproducts"),$userinfo["uid"]);
                }
                if($messages["order_suspended"]["sms"] && $uisettings["sms_alert"]){
                    $message = str_replace(["{sitename}","{productname}","{namesurname}"],[$sitename,$userproduct["upname"]." ".$userproduct["uptag"],$userproduct["name"]." ".$userproduct["surname"]],$messages["order_suspended"]["sms"]["mttmessage"]);
                    beSms::beCreateSms($message,1,$userinfo["uid"]);
                }
                if($messages["order_suspended"]["mail"] && $uisettings["mail_alert"]){
                    $message = str_replace(["{sitename}","{productname}","{namesurname}"],[$sitename,$userproduct["upname"]." ".$userproduct["uptag"],$userproduct["name"]." ".$userproduct["surname"]],$messages["order_suspended"]["mail"]["mttmessage"]);
                    beMail::beCreateMail($messages["order_suspended"]["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                }
                UserProductModel::beUpdate([
                    "upstatus" => 0
                ])->beWhere("upid",$userproduct["upid"])->beExecute();
            }
            if($endday < $settings["automation_order_terminate"]*-1){
                if($userproduct["pterminatetype"] != "terminate"){
                    continue;
                }
                if($uisettings["never_terminate"] == 1){
                    continue;
                }
                if($userproduct["upmodule"] && $settings["automation_order_terminate_module"] == 1){
                    beModule::beLoadModule("product.{$userproduct['upmodule']}");
                    if(beModule::beCheckModuleFunction($userproduct["upmodule"],"terminate")){
                        $data = [];
                        if($userproduct["sid"]){
                            $server = ServerModel::beWhere("sid",$userproduct["sid"])->beGet();
                            $server["spassword"] = beDecryptData($server["spassword"]);
                            $data["server"] = $server;
                        }
                        $data["userproduct"] = $userproduct;
                        $response = beModule::beRunModuleFunction($userproduct["upmodule"],"terminate",$data);
                        if(!$response["status"]){
                            UserProductLogsModel::beInsert([
                                "uid" => $userproduct["uid"],
                                "upid" => $userproduct["upid"],
                                "upltype" => "order_terminate_module_error",
                                "upldata" => json_encode([
                                    "message" => $response["message"]
                                ]),
                                "upldateline" => BE_TIME
                            ]);
                            continue;
                        }
                        UserProductLogsModel::beInsert([
                            "uid" => $userproduct["uid"],
                            "upid" => $userproduct["upid"],
                            "upltype" => "order_terminate_module",
                            "upldata" => json_encode([
                                "message" => $response["message"]
                            ]),
                            "upldateline" => BE_TIME
                        ]);
                    }
                }
                $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$userproduct["uid"])->beGet();
                $uisettings = json_decode($userinfo["uisettings"],true);
                if($messages["order_terminated"]["alert"] && $uisettings["notification_alert"]){
                    $message = str_replace(["{sitename}","{productname}","{namesurname}"],[$sitename,$userproduct["upname"]." ".$userproduct["uptag"],$userproduct["name"]." ".$userproduct["surname"]],$messages["order_terminated"]["alert"]["mttmessage"]);
                    beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),beGetRoute("client.userproduct.userproducts"),$userinfo["uid"]);
                }
                if($messages["order_terminated"]["sms"] && $uisettings["sms_alert"]){
                    $message = str_replace(["{sitename}","{productname}","{namesurname}"],[$sitename,$userproduct["upname"]." ".$userproduct["uptag"],$userproduct["name"]." ".$userproduct["surname"]],$messages["order_terminated"]["sms"]["mttmessage"]);
                    beSms::beCreateSms($message,1,$userinfo["uid"]);
                }
                if($messages["order_terminated"]["mail"] && $uisettings["mail_alert"]){
                    $message = str_replace(["{sitename}","{productname}","{namesurname}"],[$sitename,$userproduct["upname"]." ".$userproduct["uptag"],$userproduct["name"]." ".$userproduct["surname"]],$messages["order_terminated"]["mail"]["mttmessage"]);
                    beMail::beCreateMail($messages["order_terminated"]["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                }
                $invoices = InvoiceModel::beSelect("iid")->beWhere("uid",$userproduct["uid"])->beWhere("itype","2")->beWhere("istatus","0")->beGetAll();
                foreach($invoices as $invoice){
                    $invoiceitem = InvoiceItemModel::beSelect("iiid")->beWhere("iid",$invoice["iid"])->beWhere("iiobject","ExtendOrder")->beWhere("iiobjectid",$userproduct["upid"])->beGet();
                    if($invoiceitem){
                        InvoiceModel::beUpdate(["istatus" => "-1"])->beWhere("iid",$invoice["iid"])->beExecute(); 
                        break;
                    }  
                }
                UserProductModel::beUpdate([
                    "upstatus" => -1
                ])->beWhere("upid",$userproduct["upid"])->beExecute();
                if($userproduct["pactive"]-1 < 1){
                    $userproduct["pactive"] = 1;
                }
                ProductModel::beUpdate(["pactive" => $userproduct["pactive"]-1])->beWhere("pid",$userproduct["pid"])->beExecute();
            }
        }
    }
}

?>