<?php

namespace App\System\Task;

use App\System\Basic\beModel;
use App\System\Controller\OrderController;
use App\System\Model\InvoiceItemModel;
use App\System\Model\InvoiceModel;
use App\System\Model\MessageTemplateModel;
use App\System\Model\SettingModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserProductCancellationsModel;
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;
use Stripe\InvoiceItem;

class OrderInvoiceActionsTask {
    public function run_task($task){
        $settings = SettingModel::beGetSettings("automation_invoice_remember");
        $timerange = explode(",",$settings["automation_invoice_remember"]);
        $messages = MessageTemplateModel::beGetMessages("order_time_invoice_dasyremain,order_time_invoice_created",1);
        $sitename = beGetConfig("sitename");
        $order = new OrderController();
        $timenow = BE_TIME;
        $timesearch = BE_TIME+864000;
        $setting = SettingModel::beSelect("scode,svalue")->beWhere("scode","system_sms_module")->beGet();
        $smsmodule = "";
        if($setting["svalue"]){ 
            $smsmodule = $setting["svalue"];
        }
        $userproducts = UserProductModel::beTable("be_user_products as up")->beSelect("up.*,u.lid,u.name,u.surname,u.email")->beWhere("upstatus","2")->beWhere("upntime",$timesearch,"<")->beWhere("upstime",0,"!=")->beJoin("INNER JOIN be_users as u ON u.uid = up.uid")->beGetAll();
        foreach($userproducts as $userproduct){
            $userproductcancellation = UserProductCancellationsModel::beWhere("upid",$userproduct["upid"])->beWhere("upcstatus","1")->beGet();
            if($userproductcancellation){
                continue;
            }
            $upsystemdata = json_decode($userproduct["upsystemdata"],true);
            $invoiceday = round(($userproduct["upntime"]-$timenow)/86400);
            $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$userproduct["uid"])->beGet();
            $uisettings = json_decode($userinfo["uisettings"],true);
            $orderurl = beGetRoute("client.userproduct.userproducts");
            foreach($timerange as $time){
                if($invoiceday == $time && $upsystemdata["lastsend"] != $time){
                    $upsystemdata["lastsend"] = $invoiceday;
                    if($messages["order_time_invoice_dasyremain"]["mail"] && $uisettings["mail_alert"]){
                        $message = str_replace(["{sitename}","{namesurname}","{productname}","{dayremaining}","{orderurl}"],[$sitename,$userproduct["name"]." ".$userproduct["surname"],$userproduct["upname"],$invoiceday,$orderurl],$messages["order_time_invoice_dasyremain"]["mail"]["mttmessage"]);
                        beMail::beCreateMail($messages["order_time_invoice_dasyremain"]["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                    }
                    if($messages["order_time_invoice_dasyremain"]["alert"] && $uisettings["notification_alert"]){
                        $message = str_replace(["{sitename}","{namesurname}","{productname}","{dayremaining}","{orderurl}"],[$sitename,$userproduct["name"]." ".$userproduct["surname"],$userproduct["upname"],$invoiceday,$orderurl],$messages["order_time_invoice_dasyremain"]["alert"]["mttmessage"]);
                        beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),beGetRoute("client.userproduct.userproducts"),$userinfo["uid"]);
                    }
                    if($messages["order_time_invoice_dasyremain"]["sms"] && $uisettings["sms_alert"] && $smsmodule){
                        $message = str_replace(["{sitename}","{namesurname}","{productname}","{dayremaining}","{orderurl}"],[$sitename,$userproduct["name"]." ".$userproduct["surname"],$userproduct["upname"],$invoiceday,$orderurl],$messages["order_time_invoice_dasyremain"]["sms"]["mttmessage"]);
                        beSms::beCreateSms($message,1,$userinfo["uid"]);
                    }
                    UserProductModel::beUpdate(["upsystemdata" => json_encode($upsystemdata,JSON_UNESCAPED_UNICODE)])->beWhere("upid",$userproduct["upid"])->beExecute();
                }
            }
            if($invoiceday < 1){
                $haveinvoice = false;
                $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){
                        $haveinvoice = true;
                        break;
                    }
                }
                if(!$haveinvoice){
                    $response = $order->create_order_invoice($userproduct["upid"],"extend",true,-1);
                    if($response["status"]){
                        if($messages["order_time_invoice_created"]["alert"] && $uisettings["notification_alert"]){
                            $message = str_replace(["{sitename}","{namesurname}","{productname}","{orderurl}"],[$sitename,$userproduct["name"]." ".$userproduct["surname"],$userproduct["upname"],$orderurl],$messages["order_time_invoice_created"]["alert"]["mttmessage"]);
                            beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),beGetRoute("client.userproduct.userproducts"),$userinfo["uid"]);
                        }
                        if($messages["order_time_invoice_created"]["sms"] && $uisettings["sms_alert"] && $smsmodule){
                            $message = str_replace(["{sitename}","{namesurname}","{productname}","{orderurl}"],[$sitename,$userproduct["name"]." ".$userproduct["surname"],$userproduct["upname"],$orderurl],$messages["order_time_invoice_created"]["sms"]["mttmessage"]);
                            beSms::beCreateSms($message,1,$userinfo["uid"]);
                        }
                        if($messages["order_time_invoice_created"]["mail"] && $uisettings["mail_alert"]){
                            $message = str_replace(["{sitename}","{namesurname}","{productname}","{orderurl}"],[$sitename,$userproduct["name"]." ".$userproduct["surname"],$userproduct["upname"],$orderurl],$messages["order_time_invoice_created"]["mail"]["mttmessage"]);
                            beMail::beCreateMail($messages["order_time_invoice_created"]["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                        }
                    }
                    if(!$response["status"]){
                        beModel::beInsert([
                            "uid" => 0,
                            "sltitle" => "Sipariş uzatım faturası oluşturulamadı!",
                            "slcontent" => $response["message"],
                            "sldata" => json_encode([
                                "upid" => (int)$userproduct["upid"]
                            ]),
                            "sldateline" => BE_TIME
                        ],"be_system_logs");
                    }
                }
            }
        }
    }
}

?>