<?php

namespace App\System\Task;

use App\System\Controller\CartController;
use App\System\Model\AuthModel;
use App\System\Model\InvoiceModel;
use App\System\Model\ModuleLogModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use \Exception;

class OrderAutoPayTask {
    public function run_task($task){
        global $be;
        $system_currency = $be->settings["system_currency"];
        $invoices = InvoiceModel::beSelect("iid,cid,uid,idata,iprice,itaxprice,idiscount")->beWhere("itype","2")->beWhere("istatus","0")->beGetAll();
        foreach($invoices as $invoice){
            $user = Auth::beGetUser($invoice["uid"],"uid,money");
            $idata = json_decode($invoice["idata"],true);
            $invoice["itotal"] = $invoice["iprice"]+$invoice["itaxprice"]-$invoice["idiscount"];
            if($system_currency != $invoice["cid"]){
                $invoice["itotal"] = beConvertCurrencie($invoice["itotal"],$invoice["cid"],$system_currency);
            }
            $invoice["itotal"] = round($invoice["itotal"],2);
            if(!$idata["upid"]){
                continue;
            }
            $upid = $idata["upid"];
            $userproduct = UserProductModel::beSelect("p.pextendauto,be_user_products.upid,be_user_products.upextendauto")->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){
                continue;
            }
            if(!$userproduct["pextendauto"]){
                continue;
            }
            if(!$userproduct["upextendauto"]){
                continue;
            }
            if($user["money"] < $invoice["itotal"]){
                continue;
            }
            $user["money"] -= $invoice["itotal"];
            AuthModel::beUpdate(["money" => $user["money"]])->beWhere("uid",$user["uid"])->beExecute();
            $cart = new CartController(); 
            InvoiceModel::beUpdate([
                "ipaymethod" => "wallet",
                "ipaydata" => json_encode(["automaticpay" => BE_TIME],JSON_UNESCAPED_UNICODE),
                "ifee" => 0
            ])->beWhere("iid",$invoice["iid"])->beExecute();
            $invoice = $cart->cart_invoice_approve($invoice["iid"]);
            if($invoice["error"]){
                ModuleLogModel::beCreateModuleLog("OrderAutoPayTask","Fatura Onaylama Hatası","Fatura Onaylanırken bir sorun oluştu {$invoice['error']}",["iid" => $invoice["iid"]]);
            }
        }
    }
}

?>