<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Basic\beRouter;
use App\System\Model\AccountingModel;
use App\System\Model\AuthModel;
use App\System\Model\CurrencyModel;
use App\System\Model\InvoiceItemModel;
use App\System\Model\InvoiceModel;
use App\System\Model\MessageTemplateModel;
use App\System\Model\ModuleLogModel;
use App\System\Model\PaymentModel;
use App\System\Model\SettingModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserLogModel;
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 InvoiceController extends beContoller {
    public function list(){
        return beGetView("admin.invoice.list");
    }
    public function add(){
        global $be;
        $uid = (int)$_GET["user"];
        $usersearch = [];
        if($uid){
            $user = Auth::beGetUser($uid,"uid,name,surname,email");
            if($user){
                $usersearch = [
                    "uid" => $user["uid"],
                    "text" => $user["name"]." ".$user["surname"]." # ".$user["email"]
                ];
            }
        }
        $unittypes = InvoiceModel::beGetUnitTypes();
        $currencies = CurrencyModel::beGetCurrencies("cid,cname");
        return beGetView("admin.invoice.add",["unittypes" => $unittypes,"currencies" => $currencies,"usersearch" => $usersearch,"system_currency" => $be->settings["system_currency"],"system_taxrate" => $be->settings["system_taxrate"]]);
    }
    public function add_post(){
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("user");
        beLanguage::beReadLang("currency");
        $name = htmlspecialchars($_POST["name"]);
        $description = htmlspecialchars($_POST["description"]);
        $type = (int)$_POST["type"];
        if(!in_array($type,[3,4])){
            return beAjaxError(["message" => beGetLang("invoice_type_not_found")]);
        }
        $bill = (int)$_POST["bill"];
        if(!in_array($bill,[0,1])){
            return beAjaxError(["message" => beGetLang("invoice_bill_type_not_found")]);
        }
        $uid = (int)$_POST["user"];
        $user = Auth::beGetUser($uid,"uid,name,surname");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $unittypes = InvoiceModel::beGetUnitTypes();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon,ctaxrate");
        $cid = (int)$_POST["currency"];
        $maincurrency = $currencies[$cid];
        if(!$maincurrency){
            return beAjaxError(["message" => beGetLang("currency_not_found")]);
        }
        if(is_numeric($_POST["expiredate"])){
            $expiredate = (int)$_POST["expiredate"];
        }
        else{
            $expiredate = strtotime($_POST["expiredate"]);
        }
        if(!$expiredate){
            return beAjaxError(["message" => beGetLang("invoice_time_empty")]);
        }
        if(is_numeric($_POST["dateline"])){
            $dateline = (int)$_POST["dateline"];
        }
        else{
            $dateline = strtotime($_POST["dateline"]);
        }
        if(!$dateline){
            return beAjaxError(["message" => beGetLang("invoice_time_empty")]);
        }
        $note = htmlspecialchars($_POST["note"]);
        $itemcount = (int)$_POST["itemCount"];
        $basket = [];
        $totalprice = 0;
        $ratetotalprice = 0;
        $cart = new CartController();
        for($i = 0; $i < $itemcount+1; $i++){
            $rowname = htmlspecialchars($_POST["rowName".$i]);
            if(!$rowname){
                continue;
            }
            $price = (double)$_POST["rowPrice".$i];
            $unit = $_POST["rowCount".$i];
            $tax = (int)$_POST["rowTax".$i];
            if(!$tax){
                $tax = $maincurrency["ctaxrate"];
            }
            $unittype = $_POST["rowUnitType".$i];
            if(!$unittypes[$unittype]){
                return beAjaxError(["message" => beGetLang("invoice_unit_not_found")]);
            }
            $cid = (int)$_POST["rowCurrency".$i];
            if(!$currencies[$cid]){
                return beAjaxError(["message" => beGetLang("currency_not_found")]);
            }
            $itemprice = $price*$unit;
            if($cid != $maincurrency["cid"]){
                $itemprice = beConvertCurrencie($itemprice,$cid,$maincurrency["cid"]);
            }
            $totalprice += $itemprice;
            if($tax){
                $rate = $cart->get_rate($itemprice,$tax);
                if(!$rate["status"]){
                    return beAjaxError(["message" => $rate["message"]]);
                }
                $ratetotalprice +=  $rate["rate"];
            }
            $basket[] = [$rowname,$cid,$price,$unit,$unittype,$tax];
        }
        $rateprice = $ratetotalprice;
        $iid = InvoiceModel::beInsert([
            "cid" => $maincurrency["cid"],
            "uid" => $user["uid"],
            "iname" => $name,
            "idescription" => $description,
            "itype" => $type,
            "istatus" => "0",
            "ibill" => $bill,
            "iprice" => $totalprice,
            "itaxprice" => $rateprice,
            "idiscount" => 0,
            "ifee" => 0,
            "idata" => "",
            "inote" => $note,
            "ipaymethod" => "",
            "ipaydata" => "",
            "iexpiredate" => $expiredate,
            "ipaydate" => 0,
            "idateline" => $dateline
        ]);
        foreach($basket as $item){
            InvoiceItemModel::beInsert([
                "iid" => $iid,
                "cid" => $item[1],
                "iiobject" => "",
                "iiobjectid" => 0,
                "iiname" => $item[0],
                "iiunitprice" => $item[2],
                "iiunitcount" => $item[3],
                "iitaxrate" => $item[5],
                "iiunittype" => $item[4],
                "iidata" => "",
                "iidateline" => BE_TIME
            ]);
        }
        $sitename = beGetConfig("sitename");
        $invoicelink = beGetRoute("client.invoice.invoice",["iid" => $iid]);
        $messages = MessageTemplateModel::beGetMessages("invoice_created",1)["invoice_created"];
        $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$user["uid"])->beGet();
        $uisettings = json_decode($userinfo["uisettings"],true);
        if($messages["alert"] && $uisettings["notification_alert"]){
            $message = str_replace(["{sitename}","{invoicename}","{namesurname}","{invoicelink}"],[$sitename,$name,$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,$name,$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,$name,$user["name"]." ".$user["surname"],$invoicelink],$messages["mail"]["mttmessage"]);
            beMail::beCreateMail($messages["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
        }
        return beAjaxSuccess(["message" => beGetLang("invoice_created"),"url" => beGetRoute("admin.invoice.show",["iid" => $iid])]);
    }
    public function itemadd_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $invoice = InvoiceModel::beSelect("iid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $iiid = InvoiceItemModel::beInsert([
            "iid" => $iid,
            "iidateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("invoice_item_created"),"iiid" => $iiid]);
    }
    public function itemsave_post(){
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("currency");
        $iid = (int)$_POST["iid"];
        $invoice = InvoiceModel::beSelect("iid,cid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $unittypes = InvoiceModel::beGetUnitTypes();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon,ctaxrate");
        $cid = (int)$_POST["currency"];
        $maincurrency = $currencies[$invoice["cid"]];
        if(!$maincurrency){
            return beAjaxError(["message" => beGetLang("currency_not_found")]);
        }
        $totalprice = 0;
        $rateprice = 0;
        $cart = new CartController();
        foreach($_POST["item"] as $iiid => $item){
            $invoiceitem = InvoiceItemModel::beSelect("iiid")->beWhere("iiid",$iiid)->beGet();
            if(!$invoiceitem){
                return beAjaxError(["message" => beGetLang("invoice_item_not_found")]);
            }
            $rowname = htmlspecialchars($item["rowName"]);
            if(!$rowname){
                continue;
            }
            $price = (double)$item["rowPrice"];
            $unit = $item["rowCount"];
            $tax = (int)$item["rowTax"];
            $unittype = $item["rowUnitType"];
            if(!$unittypes[$unittype]){
                return beAjaxError(["message" => beGetLang("invoice_unit_not_found")]);
            }
            $cid = (int)$item["rowCurrency"];
            if(!$currencies[$cid]){
                return beAjaxError(["message" => beGetLang("currency_not_found")]);
            }
            $itemprice = $price*$unit;
            if($cid != $maincurrency["cid"]){
                $itemprice = beConvertCurrencie($itemprice,$cid,$maincurrency["cid"]);
            }
            $totalprice += $itemprice;
            if($tax){
                $rate = $cart->get_rate($itemprice,$tax);
                if(!$rate["status"]){
                    return beAjaxError(["message" => $rate["message"]]);
                }
                $rateprice += $rate["rate"];
            }
            $basket[] = [$rowname,$cid,$price,$unit,$unittype,$tax];
            InvoiceItemModel::beUpdate([
                "cid" => $cid,
                "iiname" => $rowname,
                "iiunitprice" => $price,
                "iiunitcount" => $unit,
                "iitaxrate" => $tax,
                "iiunittype" => $unittype,
            ])->beWhere("iiid",$invoiceitem["iiid"])->beExecute();
        }
        InvoiceModel::beUpdate([
            "iprice" => $totalprice,
            "itaxprice" => $rateprice
        ])->beWhere("iid",$invoice["iid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("invoice_updated")]);
    }
    public function itemdelete_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $iiid = (int)$_POST["iiid"];
        $invoice = InvoiceModel::beSelect("iid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $invoiceitem = InvoiceItemModel::beSelect("iiid")->beWhere("iiid",$iiid)->beGet();
        if(!$invoiceitem){
            return beAjaxError(["message" =>  beGetLang("invoice_item_not_found")]);
        }
        InvoiceItemModel::beDelete()->beWhere("iiid",$invoiceitem["iiid"])->beWhere("iid",$invoice["iid"])->beExecute();
        $response = $this->beCalculateInvoicePrices($iid);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => beGetLang("invoice_item_deleted")]);
    }
    public function show($iid){
        beLanguage::beReadLang("invoice");
        $invoice = InvoiceModel::beTable("be_invoices as i")->beSelect("i.*,u.lid,u.name,u.surname,u.email")->beWhere("iid",$iid)->beJoin("INNER JOIN be_users as u ON u.uid = i.uid")->beGet();
        if(!$invoice){
            beError(beGetLang("invoice"),beGetLang("invoice_not_found"));
        }
        $status = InvoiceModel::beGetInvoiceStatus();
        $types = InvoiceModel::beGetInvoiceTypes();
        $bills = InvoiceModel::beGetInvoiceBillStatus();
        $unittypes = InvoiceModel::beGetUnitTypes();
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $invoice["ibilldata"] = json_decode($invoice["ibilldata"],true);
        $invoiceitems = InvoiceItemModel::beWhere("iid",$invoice["iid"])->beGetAll();
        return beGetView("admin.invoice.show",["invoice" => $invoice,"invoiceitems" => $invoiceitems,"unittypes" => $unittypes,"currencies" => $currencies,"status" => $status,"types" => $types,"bills" => $bills]);
    }
    public function merge_post(){
        beLanguage::beReadLang("invoice");
        $iids = $_POST["iids"];
        if(empty($iids)){
            return beAjaxError(["message" => beGetLang("invoice_not_selected")]);
        }
        $newiid = end($iids);
        $invoices = InvoiceModel::beSelect("iid,istatus")->beWhere("iid",$iids,"IN")->beGetAll();
        if(!$invoices){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        foreach($invoices as $invoice){
            if($invoice["istatus"] != 0){
                return beAjaxError(["message" => beGetLang("invoice_merge_status_error")]);
            }
        }
        foreach($invoices as $invoice){
            if($invoice["iid"] == $newiid){
                continue;
            }
            InvoiceItemModel::beUpdate(["iid" => $newiid])->beWhere("iid",$invoice["iid"])->beExecute();
            InvoiceModel::beDelete()->beWhere("iid",$invoice["iid"])->beExecute();
        }
        $this->beCalculateInvoicePrices($newiid);
        return beAjaxSuccess(["message" => beGetLang("invoice_merged")]);
    }
    public function status_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $iids = $_POST["iids"];
        if(!$iids && $iid){
            $iids[] = $iid;
        }
        $status = (int)$_POST["status"];
        $oncontent = (int)$_POST["oncontent"];
        $onaccounting = (int)$_POST["onaccounting"];
        $onmoney = (int)$_POST["onmoney"];
        $statustypes = [-1,0,1];
        if(empty($iids)){
            return beAjaxError(["message" => beGetLang("invoice_not_selected")]);
        }
        $invoices = InvoiceModel::beWhere("iid",$iids,"IN")->beGetAll();
        if(!$invoices){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        foreach($invoices as $invoice){
            if(!in_array($status,$statustypes)){
                return beAjaxError(["message" => beGetLang("invoice_type_not_found")]);
            }
            if($status == 1){
                if($onmoney){
                    $invoice["itotal"] = $invoice["iprice"]+$invoice["itaxprice"];
                    $invoiceuser = Auth::beGetUser($invoice["uid"],"uid,money");
                    if($invoiceuser["money"] < $invoice["itotal"]){
                        return beAjaxError(["message" => beGetLang("invoice_user_money_not_enought")]);
                    }
                    $invoiceuser["money"] -= $invoice["itotal"];
                    AuthModel::beUpdate(["money" => $invoiceuser["money"]])->beWhere("uid",$invoiceuser["uid"])->beExecute();
                }
                if($oncontent){
                    if(!beCheckPermission("admin_invoice_status_on_content",0)){
                        return beAjaxError(["message" => beGetLang("usergroup_permission_denied",["permission" => "admin_invoice_status_on_content"])]);
                    }
                    $cart = new CartController();
                    $response = $cart->cart_invoice_approve($invoice["iid"]);
                    if(!$response["status"]){
                        return beAjaxError(["message" => $response["message"]]);
                    }
                }
            }
            if($onaccounting){
                if(!beCheckPermission("admin_invoice_status_on_accounting",0)){
                    return beAjaxError(["message" => beGetLang("usergroup_permission_denied",["permission" => "admin_invoice_status_on_accounting"])]);
                }
                AccountingModel::beInsert([
                    "cid" => $invoice["cid"],
                    "aname" => "Fatura Ödemesi #{$invoice['iid']}",
                    "atype" => "income",
                    "atotal" => round($invoice["iprice"]+$invoice["itaxprice"],2),
                    "adateline" => BE_TIME
                ]);
            }
            InvoiceModel::beUpdate([
                "istatus" => $status
            ])->beWhere("iid",$invoice["iid"])->beExecute();
        }
        return beAjaxSuccess(["message" => beGetLang("invoice_updated")]);
    }
    public function billstatus_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $status = (int)$_POST["status"];
        $onrealinvoice = (int)$_POST["onrealinvoice"];
        $statustypes = [0,1];
        $invoice = InvoiceModel::beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $user = Auth::beGetUser($invoice["uid"]);
        if(!in_array($status,$statustypes)){
            return beAjaxError(["message" => beGetLang("invoice_bill_type_not_found")]);
        }
        if($invoice["ibill"] == 2){
            return beAjaxError(["message" => beGetLang("invoice_bill_already_sended")]);
        }
        if(!$invoice["ipaydate"]){
            $invoice["ipaydate"] = 0;
        }
        $updatedata = [
            "ibill" => $status,
            "ibilldate" => BE_TIME
        ];
        if($onrealinvoice == 1 && $status == 1){
            $setting = SettingModel::beSelect("scode,svalue")->beWhere("scode","system_invoice_module")->beGet();
            if($setting["svalue"] == ""){ 
                return beAjaxError(["message" => beGetLang("invoice_bill_module_not_found")]);
            }
            $userinfo = UserInfoModel::beWhere("uid",$invoice["uid"])->beGet();
            if(!$userinfo){
                return beAjaxError(["message" => beGetLang("invoice_bill_empty_user_data")]);
            }
            $invoiceitems = InvoiceItemModel::beWhere("iid",$invoice["iid"])->beGetAll();
            $invoicemodule = $setting["svalue"];
            if(!$invoicemodule){
                return beAjaxError(["message" => beGetLang("invoice_bill_module_not_found")]);
            }
            beModule::beLoadModule("invoice.{$invoicemodule}");
            $logindata = [];
            if(beModule::beCheckModuleFunction($invoicemodule,"login")){
                $logindata = beModule::beRunModuleFunction($invoicemodule,"login");
                if(!$logindata["status"]){
                    if(!$logindata["message"]){
                        $logindata["message"] = beGetLang("invoice_bill_login_error");
                    }
                    return beAjaxError(["message" => $logindata["message"]]);
                }
            }
            if(!$invoice["ipaydate"]){
                $invoice["ipaydate"] = BE_TIME;
                $updatedata["ipaydate"] = $invoice["ipaydate"];
            }
            $response = beModule::beRunModuleFunction($invoicemodule,"create_invoice",array_merge($logindata,[
                "invoice" => $invoice,
                "invoiceitems" => $invoiceitems,
                "user" => $user,
                "userinfo" => $userinfo,
                "datetime" => $invoice["ipaydate"]
            ]));
            if(!$response["status"]){
                if($response["invoicedata"]["ibilldata"]){
                    InvoiceModel::beUpdate(["ibilldata" => $response["invoicedata"]["ibilldata"]])->beWhere("iid",$invoice["iid"])->beExecute();
                }
                return beAjaxError(["message" => $response["message"]]);
            }
            if($response["invoicedata"]){
                foreach($response["invoicedata"] as $key => $value){
                    $updatedata[$key] = $value;
                }
            }
            if(beModule::beCheckModuleFunction($invoicemodule,"logout")){
                beModule::beRunModuleFunction($invoicemodule,"logout",$logindata);
            }
        }
        InvoiceModel::beUpdate($updatedata)->beWhere("iid",$invoice["iid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("invoice_bill_updated")]);
    }
    public function namesave_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $invoice = InvoiceModel::beSelect("iid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $name = htmlspecialchars($_POST["name"]);
        $description = htmlspecialchars($_POST["description"]);
        if(empty($name)){
            return beAjaxError(["message" => beGetLang("invoice_name_empty")]);
        }
        InvoiceModel::beUpdate([
            "iname" => $name,
            "idescription" => $description
        ])->beWhere("iid",$invoice["iid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("invoice_updated")]);
    }
    public function notesave_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $invoice = InvoiceModel::beSelect("iid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $note = htmlspecialchars($_POST["note"]);
        InvoiceModel::beUpdate([
            "inote" => $note
        ])->beWhere("iid",$invoice["iid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("invoice_updated")]);
    }
    public function pricesave_post(){
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("currency");
        $iid = (int)$_POST["iid"];
        $invoice = InvoiceModel::beSelect("iid,cid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $cid = (int)$_POST["currency"];
        $currency = CurrencyModel::beGetCurrencies("cid,ctaxrate",$cid);
        if(!$currency){
            return beAjaxError(["message" => beGetLang("currency_not_found")]);
        }
        $invoice["cid"] = $currency["cid"];
        InvoiceModel::beUpdate([
            "cid" => $currency["cid"],
        ])->beWhere("iid",$invoice["iid"])->beExecute();
        $this->beCalculateInvoicePrices($invoice["iid"]);
        return beAjaxSuccess(["message" => beGetLang("invoice_updated")]);
    }
    public function timesave_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $invoice = InvoiceModel::beSelect("iid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $expiredate = $dateline = 0;
        if(is_numeric($_POST["expiredate"])){
            $expiredate = (int)$_POST["expiredate"];
        }
        else{
            $expiredate = strtotime($_POST["expiredate"]);
        }
        if(!$expiredate){
            return beAjaxError(["message" => beGetLang("invoice_time_empty")]);
        }
        if(is_numeric($_POST["dateline"])){
            $dateline = (int)$_POST["dateline"];
        }
        else{
            $dateline = strtotime($_POST["dateline"]);
        }
        if(!$dateline){
            return beAjaxError(["message" => beGetLang("invoice_time_empty")]);
        }
        InvoiceModel::beUpdate([
            "iexpiredate" => $expiredate,
            "idateline" => $dateline
        ])->beWhere("iid",$invoice["iid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("invoice_updated")]);
    }
    public function delete_post(){
        beLanguage::beReadLang("invoice");
        $iid = (int)$_POST["iid"];
        $invoice = InvoiceModel::beSelect("iid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        InvoiceItemModel::beDelete()->beWhere("iid",$invoice["iid"])->beExecute();
        InvoiceModel::beDelete()->beWhere("iid",$invoice["iid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("invoice_deleted")]);
    }
    public function search_post(){
        $pageitems = (int)$_POST["pageitems"];
        $name = $_POST["name"];
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $status = (int)$_POST["status"];
        $type = (int)$_POST["type"];
        $bill = (int)$_POST["bill"];
        $username = $_POST["username"];
        $maxlimit = (int)$_POST["maxlimit"];
        if(!$maxlimit){
            $maxlimit = 20;
        }
        $userid = 0;
        if($username){
            $userdata = explode(" ",$username);
            $namecount = count($userdata);
            switch($namecount){
                case 1 :
                    $userid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0])->beGet()["uid"];
                    if(!$userid){
                        $userid = AuthModel::beSelect("uid")->beWhere("email",$userdata[0])->beGet()["uid"];
                    }
                    break;
                case 2 :
                    $userid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0])->beWhere("surname",$userdata[1])->beGet()["uid"];
                    break;
                case 3 :
                    $userid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0]." ".$userdata[1])->beWhere("surname",$userdata[2])->beGet()["uid"];
                    break;
            }
        }
        $uid = (int)$_POST["user"];
        if($uid){
            $userid = $uid;
        }
        $invoicesearch = InvoiceModel::beSelect("COUNT(iid) as total");
        if($name){
            $invoicesearch = $invoicesearch->beWhere("iname",$name,"LIKE");
        }
        if($status > -2 && $status < 2){
            $invoicesearch = $invoicesearch->beWhere("istatus",$status);
        }
        if($type > -1 && $type < 5){
            $invoicesearch = $invoicesearch->beWhere("itype",$type);
        }
        if($bill > -1 && $bill < 2){
            $invoicesearch = $invoicesearch->beWhere("itype",$type);
        }
        if($userid){
            $invoicesearch = $invoicesearch->beWhere("uid",$userid);
        }
        $invoicecount = (int)$invoicesearch->beGet()["total"];
        $paganation = bePaganation($page,$invoicecount,"",$pageitems);
        $invoices = InvoiceModel::beTable("be_invoices as i")->beSelect("iid,i.cid,idescription,itype,istatus,ibill,iprice,itaxprice,ifee,idiscount,ipaymethod,iexpiredate,ipaydate,idateline,u.uid,u.name,u.surname");
        if($name){
            $invoices = $invoices->beWhere("iname",$name,"LIKE");
        }
        if($status > -2 && $status < 2){
            $invoices = $invoices->beWhere("istatus",$status);
        }
        if($type > -1 && $type < 5){
            $invoices = $invoices->beWhere("itype",$type);
        }
        if($bill > -1 && $bill < 2){
            $invoices = $invoices->beWhere("itype",$type);
        }
        if($userid){
            $invoices = $invoices->beWhere("i.uid",$userid);
        }
        if($paganation["itemstart"] == 0){
            $invoices = $invoices->beLimit($paganation["itemlimit"]);
        }
        else{
            $invoices = $invoices->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        $orderkey = "iid";
        $ordertype = $_POST["ordertype"];
        if($ordertype){
            if(in_array($ordertype,["iid","ipaydate","iprice"])){
                $orderkey = $ordertype;
            }
        }
        switch($sort){
            case 1 :
                $invoices = $invoices->beOrder($orderkey,"DESC");
                break;
            case 2 :
                $invoices = $invoices->beOrder($orderkey,"ASC");
                break;
        }
        $invoices = $invoices->beJoin("INNER JOIN be_users as u ON u.uid = i.uid")->beGetAll();
        $status = InvoiceModel::beGetInvoiceStatus();
        $types = InvoiceModel::beGetInvoiceTypes();
        $bills = InvoiceModel::beGetInvoiceBillStatus();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon");
        beModule::beLoadModules("payment");
        $invoicehtml = beGetView("admin.invoice.listrows",["invoices" => $invoices,"status" => $status,"types" => $types,"bills" => $bills,"currencies" => $currencies,"modules" => beModule::$beModules]);
        return beAjaxSuccess(["html" => $invoicehtml,"paganation" => $paganation["paganation"],"invoicecount" => $invoicecount]);
    }
    public function invoices($type){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("invoice");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        $user = Auth::beGetUser();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon");
        $invoice_count = InvoiceModel::beSelect("COUNT(iid) as total")->beWhere("uid",$user["uid"])->beWhere("istatus","0")->beGet()["total"];
        $page = (int)$_GET["page"];
        if(!$page){
            $page = 1;
        }
        $paganation = [];
        switch($type){
            case 9 : {
                $table_name = beGetLang("invoice_all");
                NavController::beAddBreadcumb($table_name);
                $itemcount = InvoiceModel::beSelect("COUNT(iid) as total")->beWhere("uid",$user["uid"])->beGet()["total"];
                $paganation = bePaganation($page,$itemcount,beGetRoute("client.invoice.invoices"),10,"user");
                $invoices = InvoiceModel::beWhere("uid",$user["uid"]);
                if($paganation["itemstart"] == 0){
                    $invoices = $invoices->beLimit($paganation["itemlimit"]);
                }
                else{
                    $invoices = $invoices->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
                }
                $invoices = $invoices->beOrder("iid","DESC")->beGetAll();
                break;
            }
            case 1 : {
                $table_name = beGetLang("invoice_paid");
                NavController::beAddBreadcumb($table_name);
                $itemcount = InvoiceModel::beSelect("COUNT(iid) as total")->beWhere("uid",$user["uid"])->beWhere("istatus","1")->beGet()["total"];
                $paganation = bePaganation($page,$itemcount,beGetRoute("client.invoice.invoices"),10,"user");
                $invoices = InvoiceModel::beWhere("uid",$user["uid"])->beWhere("istatus","1");
                if($paganation["itemstart"] == 0){
                    $invoices = $invoices->beLimit($paganation["itemlimit"]);
                }
                else{
                    $invoices = $invoices->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
                }
                $invoices = $invoices->beOrder("iid","DESC")->beGetAll();
                break;
            }
            case 0 : {
                $table_name = beGetLang("invoice_unpaid");
                NavController::beAddBreadcumb($table_name);
                $itemcount = InvoiceModel::beSelect("COUNT(iid) as total")->beWhere("uid",$user["uid"])->beWhere("istatus","0")->beGet()["total"];
                $paganation = bePaganation($page,$itemcount,beGetRoute("client.invoice.invoices"),10,"user");
                $invoices = InvoiceModel::beWhere("uid",$user["uid"])->beWhere("istatus","0");
                if($paganation["itemstart"] == 0){
                    $invoices = $invoices->beLimit($paganation["itemlimit"]);
                }
                else{
                    $invoices = $invoices->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
                }
                $invoices = $invoices->beOrder("iid","DESC")->beGetAll();
                break;
            }
            case -1 : {
                $table_name = beGetLang("invoice_canceled");
                NavController::beAddBreadcumb($table_name);
                $itemcount = InvoiceModel::beSelect("COUNT(iid) as total")->beWhere("uid",$user["uid"])->beWhere("istatus","-1")->beGet()["total"];
                $paganation = bePaganation($page,$itemcount,beGetRoute("client.invoice.invoices"),10,"user");
                $invoices = InvoiceModel::beWhere("uid",$user["uid"])->beWhere("istatus","-1");
                if($paganation["itemstart"] == 0){
                    $invoices = $invoices->beLimit($paganation["itemlimit"]);
                }
                else{
                    $invoices = $invoices->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
                }
                $invoices = $invoices->beOrder("iid","DESC")->beGetAll();
                break;
            }
        }
        $invoicestatus = InvoiceModel::beGetInvoiceStatus();
        beSetHeaderContent("",1);
        return beGetView("clientarea.invoice.invoicesall",["table_name" => $table_name,"invoices" => $invoices,"invoicestatus" => $invoicestatus,"invoice_count" => $invoice_count,"paganation" => $paganation,"currencies" => $currencies]);
    }
    public function invoice($iid){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("invoice");
        $user = Auth::beGetUser();
        $invoice = InvoiceModel::beWhere("iid",$iid)->beWhere("uid",$user["uid"])->beGet();
        if(!$invoice){
            beError(beGetLang("invoice"),beGetLang("invoice_not_found"));
        }
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("invoice_all"),beGetRoute("client.invoice.invoices"));
        NavController::beAddBreadcumb($invoice["iname"]);
        beSetHeaderContent("",1);
        $invoice["itotal"] = $invoice["iprice"]+$invoice["itaxprice"];
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon");
        if($_GET["action"] == "pay"){
            beModule::beLoadModules("payment");
            $modules = beModule::$beModules;
            foreach($modules as $module => $data){
                if(!beModule::beRunModuleFunction($module,"is_activated")){
                    continue;
                }
                if(beModule::beCheckModuleFunction($module,"template")){
                    $methods[$module] = beModule::beRunModuleFunction($module,"template",[
                        "total" => $invoice["itotal"],
                        "currency" => $currencies[$invoice["cid"]]
                    ]);
                }
            }
            if(!$methods){
                beError(beGetLang("invoice"),"Sistem üzerinde hiç bir ödeme yöntemi bulunamadı!");
            }
            return beGetView("clientarea.invoice.invoicepaymethod",["invoice" => $invoice,"methods" => $methods]);
        }
        $invoiceitems = InvoiceItemModel::beWhere("iid",$invoice["iid"])->beGetAll();
        return beGetView("clientarea.invoice.invoice",["invoice" => $invoice,"invoiceitems" => $invoiceitems,"istatus" => ["-1" => "İptal Edildi","0" => "Ödeme Bekleniyor","1" => "Ödeme Yapıldı"],"currencies" => $currencies]);
    }
    public function pay($iid){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("module");
        $user = Auth::beGetUser();
        $invoice = InvoiceModel::beWhere("iid",$iid)->beWhere("uid",$user["uid"])->beGet();
        if(!$invoice){
            beError(beGetLang("invoice"),beGetLang("invoice_not_found"));
        }
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("invoice_all"),beGetRoute("client.invoice.invoices"));
        NavController::beAddBreadcumb($invoice["iname"]);
        beSetHeaderContent("",1);
        $invoice["itotal"] = $invoice["iprice"]+$invoice["itaxprice"];
        $invoice["items"] = InvoiceItemModel::beWhere("iid",$invoice["iid"])->beGetAll();
        $method = $invoice["ipaymethod"];
        $response = beModule::beLoadModule("payment.{$method}");
        if(!$response["status"]){
            return beAjaxError(["message" => beGetLang("module_not_found")]);
        }
        if(!beModule::beCheckModuleFunction($method,"pay_page")){
            return beAjaxError(["message" => beGetLang("module_not_support")]);
        }
        $paydata = beModule::beRunModuleFunction($method,"pay_page",$invoice);
        if(!$paydata["status"]){
            beError(beGetLang("invoice"),$paydata["message"]);
        }
        return beGetView("clientarea.invoice.invoicepay",["paymentcontent" => $paydata["template"]]);
    }
    public function pay_post(){
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("module");
        $method = $_POST["method"];
        if(!$method){
            $method = $_GET["method"];
        }
        if(!$method){
            return beAjaxError(["message" => beGetLang("module_not_found")]);
        }
        $iid = (int)$_POST["iid"];
        $user = Auth::beGetUser();
        $invoice = InvoiceModel::beWhere("iid",$iid)->beWhere("uid",$user["uid"])->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        $invoice["itotal"] = $invoice["iprice"]+$invoice["itaxprice"];
        $response = beModule::beLoadModule("payment.{$method}");
        if(!$response["status"]){
            return beAjaxError(["message" => beGetLang("module_not_found")]);
        }
        $paycurrnecy = beModule::beRunModuleFunction($method,"currency");
        if($paycurrnecy != $invoice["cid"]){
            $invoice["itotal"] = beConvertCurrencie($invoice["itotal"],$invoice["cid"],$paycurrnecy);
        }
        if(!beModule::beCheckModuleFunction($method,"pay_page") || $_POST["onprocess"] == 1){
            if(!beModule::beCheckModuleFunction($method,"create_payment")){
                return beAjaxError(["message" => beGetLang("module_not_support")]);
            }
            $oid = PaymentModel::beInsert([
                "cid" => $paycurrnecy,
                "uid" => $user["uid"],
                "iid" => $invoice["iid"],
                "ptotal" => $invoice["itotal"],
                "pstatus" => "0",
                "pdateline" => BE_TIME
            ]);
            $invoice["oid"] = $oid;
            $paydata = beModule::beRunModuleFunction($method,"create_payment",$invoice);
            if(!$paydata["status"]){
                PaymentModel::beUpdate(["pstatus" => "-1"])->beWhere("pid",$oid)->beExecute();
                return beAjaxError(["message" => $paydata["message"]]);
            }
            UserLogModel::beInsert([
                "uid" => $invoice["uid"],
                "ltype" => "invoice_create_payment",
                "lipaddress" => beRouter::$beUserIP,
                "ldata" => json_encode([
                    "iid" => $invoice["iid"],
                    "oid" => $oid,
                    "method" => $method,
                ],JSON_UNESCAPED_UNICODE),
                "ldateline" => BE_TIME
            ]);
            InvoiceModel::beUpdate([
                "ipaymethod" => $method,
                "ipaydata" => $paydata["payment"] ? (json_encode($paydata["payment"])):"",
                "ifee" => $paydata["invoice"]["ifee"]
            ])->beWhere("iid",$invoice["iid"])->beExecute();
            return beAjaxSuccess($paydata);
        }
        else{
            InvoiceModel::beUpdate([
                "ipaymethod" => $method
            ])->beWhere("iid",$invoice["iid"])->beExecute();
            return beAjaxSuccess(["message" => beGetLang("invoice_routing_to_pay_page"),"url" => beGetRoute("client.invoice.pay",["iid" => $invoice["iid"]])]);
        }
    }
    public function paymentcallback(){
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("module");
        $user = Auth::beGetUser();
        $module = $_GET["module"];
        $response = beModule::beLoadModule("payment.{$module}");
        if(!$response["status"]){
            return beAjaxError(["message" => beGetLang("module_not_found")]);
        }
        if(!beModule::beCheckModuleFunction($module,"pay_callback")){
            return beAjaxError(["message" => beGetLang("module_not_support")]);
        }
        $paydata = beModule::beRunModuleFunction($module,"pay_callback");
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "invoice_payment_callback",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode([
                "postdata" => $_POST,
                "iid" => $paydata["payment"]["iid"],
            ],JSON_UNESCAPED_UNICODE),
            "ldateline" => BE_TIME
        ]);
        if(!$paydata["status"]){
            return beAjaxError(["message" => $paydata["message"]]);
        }
        $invoice = InvoiceModel::beWhere("iid",$paydata["payment"]["iid"])->beGet();
        if(!$invoice){
            return beAjaxError(["message" => beGetLang("invoice_not_found")]);
        }
        if($invoice["istatus"] == 1){
            return beAjaxError(["message" => beGetLang("invoice_already_approved")]);
        }
        $cart = new CartController(); 
        $invoice = $cart->cart_invoice_approve($paydata["payment"]["iid"]);
        if($invoice["error"]){
            ModuleLogModel::beCreateModuleLog($module,"Fatura Onaylama Hatası","Fatura Onaylanırken bir sorun oluştu {$invoice['error']}",["iid" => $paydata["payment"]["iid"],"pid" => $paydata["payment"]["pid"]]);
        }
        if($paydata["add_accounting"]){
            AccountingModel::beInsert([
                "cid" => $paydata["payment"]["cid"],
                "aname" => beGetLang("invoice_accounting_type",["iid" => $paydata["payment"]["iid"]]),
                "atype" => "income",
                "atotal" => $paydata["payment"]["ptotal"],
                "adateline" => BE_TIME
            ]);
        }
        if($paydata["url"]){
            beRouter::beRedirect($paydata["url"]);
        }
        return $paydata["message"];
    }
    public function paymentnotification(){
        beLanguage::beReadLang("invoice");
        beLanguage::beReadLang("module");
        $user = Auth::beGetUser();
        $module = $_GET["module"];
        $response = beModule::beLoadModule("payment.{$module}");
        if(!$response["status"]){
            return beAjaxError(["message" => beGetLang("module_not_found")]);
        }
        if(!beModule::beCheckModuleFunction($module,"pay_notification")){
            return beAjaxError(["message" => beGetLang("module_not_support")]);
        }
        $paydata = beModule::beRunModuleFunction($module,"pay_notification");
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "invoice_payment_callback",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode([
                "postdata" => $_POST,
                "iid" => $paydata["payment"]["iid"],
            ],JSON_UNESCAPED_UNICODE),
            "ldateline" => BE_TIME
        ]);
        if(!$paydata["status"]){
            return beAjaxError(["message" => $paydata["message"]]);
        }
        $invoice = InvoiceModel::beWhere("iid",$paydata["payment"]["iid"])->beGet();
        if(!$invoice){
            return beAjaxError(["message" => "Belirtilen fatura sistem üzerinde bulunamadı!"]);
        }
        if($invoice["istatus"] == 1){
            return beAjaxError(["message" => "Belirtilen fatura zaten onaylanmış!"]);
        }
        $cart = new CartController(); 
        $invoice = $cart->cart_invoice_approve($paydata["payment"]["iid"]);
        if($invoice["error"]){
            ModuleLogModel::beCreateModuleLog($module,"Fatura Onaylama Hatası","Fatura Onaylanırken bir sorun oluştu {$invoice['error']}",["iid" => $paydata["payment"]["iid"],"pid" => $paydata["payment"]["pid"]]);
        }
        if($paydata["add_accounting"]){
            AccountingModel::beInsert([
                "cid" => $paydata["payment"]["cid"],
                "aname" => "Fatura Ödemesi #{$paydata['payment']['iid']}",
                "atype" => "income",
                "atotal" => $paydata["payment"]["ptotal"],
                "adateline" => BE_TIME
            ]);
        }
        return $paydata["message"];
    }
    public function process_post(){
        beLanguage::beReadLang("invoice");
        $user = Auth::beGetUser();
        $action = $_POST["action"];
        switch($action){
            case "merge" :
                $currencies = CurrencyModel::beGetCurrencies("cid,ctaxrate");
                $iidlist = $_POST["iids"];
                $iids = [];
                foreach($iidlist as $iid){
                    $iids[] = (int)$iid;
                }
                if(empty($iids)){
                    return beAjaxError(["message" => beGetLang("invoice_not_selected")]);
                }
                $invoices = InvoiceModel::beSelect("iid,cid,iname,istatus,iprice")->beWhere("iid",$iids,"IN")->beGetAll();
                if(!$invoices){
                    return beAjaxError(["message" => beGetLang("invoice_not_found")]);
                }
                if(count($invoices) == 1){
                    return beAjaxError(["message" => beGetLang("invoice_merge_single_error")]);
                }
                $invoiceitems = [];
                foreach($invoices as $invoice){
                    if($invoice["istatus"] != 0){
                        return beAjaxError(["message" => beGetLang("invoice_merge_status_error")]);
                    }
                    $checkifitem = InvoiceItemModel::beSelect("iiid")->beWhere("iiobject","Invoice")->beWhere("iiobjectid",$invoice["iid"])->beGet();
                    if($checkifitem){
                        return beAjaxError(["message" => beGetLang("invoice_merge_added_error")]);
                    }
                    $invoiceitems[] = [
                        "cid" => $invoice["cid"],
                        "iiobject" => "Invoice",
                        "iiobjectid" => $invoice["iid"],
                        "iiname" => $invoice["iname"],
                        "iiunitprice" => $invoice["iprice"],
                        "iiunitcount" => 1,
                        "iitaxrate" => $currencies[$invoice["cid"]]["ctaxrate"],
                        "iiunittype" => "none",
                        "iidata" => "",
                        "iidateline" => BE_TIME
                    ];
                }
                $invoice = new InvoiceController();
                $iid = InvoiceModel::beInsert([
                    "cid" => $user["cid"],
                    "uid" => $user["uid"],
                    "iname" => beGetLang("invoice_merge_name"),
                    "idescription" => beGetLang("invoice_merge_name"),
                    "itype" => "3",
                    "istatus" => "0",
                    "ibill" => "0",
                    "iprice" => 0,
                    "itaxprice" => 0,
                    "idiscount" => 0,
                    "ifee" => 0,
                    "idata" => "",
                    "iexpiredate" => BE_TIME+3600,
                    "idateline" => BE_TIME 
                ]);
                foreach($invoiceitems as $item){
                    InvoiceItemModel::beInsert(array_merge([
                        "iid" => $iid
                    ],$item));
                }
                $invoice->beCalculateInvoicePrices($iid);
                return beAjaxSuccess(["message" => beGetLang("invoice_merge_created"),"url" => beGetRoute("client.invoice.invoice",["iid" => $iid])]);
                break;
        }
    }
    public function money(){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("invoice");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("invoice_money_deposit_name"));
        $user = Auth::beGetUser();
        beSetHeaderContent("",1);
        return beGetView("clientarea.invoice.money",["user" => $user]);
    }
    public function money_post(){
        beLanguage::beReadLang("invoice");
        $user = Auth::beGetUser();
        $currencie = CurrencyModel::beGetCurrencies("cid,cicon,ctaxrate",$user["cid"]);
        $price = (int)$_POST["price"];
        if($price < 1){
            return beAjaxError(["message" => beGetLang("invoice_money_min_price",["price" => 1,"icon" => $currencie["cicon"]])]);
        }
        $price = round(($price*100)/(100+$currencie["ctaxrate"]),2);
        $invoice = new InvoiceController();
        $iid = InvoiceModel::beInsert([
            "cid" => $currencie["cid"],
            "uid" => $user["uid"],
            "iname" => beGetLang("invoice_money_deposit_name"),
            "idescription" => beGetLang("invoice_money_deposit_name"),
            "itype" => "3",
            "istatus" => "0",
            "ibill" => "0",
            "iprice" => 0,
            "itaxprice" => 0,
            "idiscount" => 0,
            "ifee" => 0,
            "idata" => "",
            "iexpiredate" => BE_TIME+3600,
            "idateline" => BE_TIME 
        ]);
        InvoiceItemModel::beInsert([
            "iid" => $iid,
            "cid" => $currencie["cid"],
            "iiobject" => "DepositMoney",
            "iiobjectid" => 0,
            "iiname" => beGetLang("invoice_money_deposit_name"),
            "iiunitprice" => $price,
            "iiunitcount" => 1,
            "iitaxrate" => $currencie["ctaxrate"],
            "iiunittype" => "none",
            "iidata" => "",
            "iidateline" => BE_TIME
        ]);
        $invoice->beCalculateInvoicePrices($iid);
        return beAjaxSuccess(["message" => "Başarılı bir şekilde ödeme işlemi oluşturuldu.","url" => beGetRoute("client.invoice.invoice",["iid" => $iid])]);
    }
    public function beCalculateInvoicePrices($iid){
        $invoice = InvoiceModel::beSelect("iid,cid")->beWhere("iid",$iid)->beGet();
        if(!$invoice){
            return ["status" => false,"message" => "Belirtilen fatura sistemde bulunamadı!"];
        }
        $invoiceitems = InvoiceItemModel::beWhere("iid",$invoice["iid"])->beGetAll();
        $totalprice = 0;
        $rateprice = 0;
        $itemprice = 0;
        $cart = new CartController();
        foreach($invoiceitems as $item){
            $itemprice = $item["iiunitprice"]*$item["iiunitcount"];
            if($item["cid"] != $invoice["cid"]){
                $itemprice = beConvertCurrencie($itemprice,$item["cid"],$invoice["cid"]);
            }
            $totalprice += $itemprice;
            if($item["iitaxrate"]){
                $rate = $cart->get_rate($itemprice,$item["iitaxrate"]);
                if(!$rate["status"]){
                    return beAjaxError(["message" => $rate["message"]]);
                }
                $rateprice += $rate["rate"];
            }
        }
        InvoiceModel::beUpdate([
            "iprice" => $totalprice,
            "itaxprice" => $rateprice
        ])->beWhere("iid",$invoice["iid"])->beExecute();
        return ["status" => true,"message" => "Başarılı bir şekilde fatura içeriği silindi!"];
    }
}
?>