<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Model\AccountingModel;
use App\System\Model\AccountingPeriodModel;
use App\System\Model\CurrencyModel;
use App\System\Model\UserProductLogsModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beTask;
use App\System\Vendor\beUpload;

class AccountingController extends beContoller {
    public function bank_list(){
        beLanguage::beReadLang("accounting");
        $banks = beModel::beTable("be_banks")->beGetAll();
        return beGetView("admin.accounting.bank.list",["banks" => $banks]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","bank_add") -> "e2084355121f110af68a2f01d70761a4" RANDOM
    public function bank_add(){
        beLanguage::beReadLang("accounting");
        return beGetView("admin.accounting.bank.add");
    }
    //@ioncube.dk beEncrypt("be_diyocp","bank_add_post") -> "35b3e4e41101595841869050c46231c7" RANDOM
    public function bank_add_post(){
        beLanguage::beReadLang("accounting");
        $file = $_FILES["file"];
        $insert = [
            "bname" => $_POST["bname"],
            "buser" => $_POST["buser"],
            "bdescription" => $_POST["bdescription"],
            "biban" => $_POST["biban"]
        ];
        if($file["name"]){
            $upload = beUpload::beUploadFile($file,$file["name"],BE_ROOT."app/resources/upload/bank",0,null,false);
            if(!$upload["status"]){
                return beAjaxError(["message" => $upload["message"]." yüklenemedi!"]);
            }
            $insert["bimage"] = $upload["filename"];
        }
        beModel::beInsert($insert,"be_banks");
        return beAjaxSuccess(["message" => beGetLang("accounting_bank_created")]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","bank_edit") -> "7870bd6d976ead72df1c9d4ffbf67977" RANDOM
    public function bank_edit($bid){
        beLanguage::beReadLang("accounting");
        $bank = beModel::beTable("be_banks")->beWhere("bid",$bid)->beGet();
        if(!$bank){
            beError(beGetLang("accounting"),beGetLang("accounting_bank_not_found"));
        }
        return beGetView("admin.accounting.bank.edit",["bank" => $bank]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","bank_edit_post") -> "4a1509afffba3d683f8327a73de59771" RANDOM
    public function bank_edit_post(){
        beLanguage::beReadLang("accounting");
        $bid = (int)$_POST["bid"];
        $bank = beModel::beSelect("bid")->beTable("be_banks")->beWhere("bid",$bid)->beGet();
        if(!$bank){
            return beAjaxError(["message" => beGetLang("accounting_bank_not_found")]);
        }
        $file = $_FILES["file"];
        $update = [
            "bname" => $_POST["bname"],
            "buser" => $_POST["buser"],
            "bdescription" => $_POST["bdescription"],
            "biban" => $_POST["biban"]
        ];
        if($file["name"]){
            $upload = beUpload::beUploadFile($file,$file["name"],BE_ROOT."app/resources/upload/bank",0,null,false);
            if(!$upload["status"]){
                return beAjaxError(["message" => $upload["message"]." yüklenemedi!"]);
            }
            $update["bimage"] = $upload["filename"];
        }
        beModel::beUpdate($update,"be_banks")->beWhere("bid",$bank["bid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("accounting_bank_updated")]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","bank_delete_post") -> "19b8e0e430f0576372fd0fa72d50175d" RANDOM
    public function bank_delete_post(){
        beLanguage::beReadLang("accounting");
        $bid = (int)$_POST["bid"];
        $bank = beModel::beSelect("bid")->beTable("be_banks")->beWhere("bid",$bid)->beGet();
        if(!$bank){
            return beAjaxError(["message" => beGetLang("accounting_bank_not_found")]);
        }
        beModel::beDelete("be_banks")->beWhere("bid",$bank["bid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("accounting_bank_deleted")]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","list") -> "9101db8b3142404cffbb15d98d4e633a" RANDOM
    public function list(){
        global $be;
        $systemcid = $be->settings["system_cid"];
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        return beGetView("admin.accounting.list",["currencies" => $currencies,"systemcid" => $systemcid,"systemcurrency" => $currencies[$systemcid]]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","periodiclist") -> "edb104d18f530bf41cce94b74ffd818d" RANDOM
    public function periodiclist(){
        global $be;
        $systemcid = $be->settings["system_cid"];
        $accountingperiods = AccountingPeriodModel::beGetAll();
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $accountingtypes = AccountingModel::beGetAccountingTypes();
        return beGetView("admin.accounting.periodiclist",["accountingperiods" => $accountingperiods,"currencies" => $currencies,"accountingtypes" => $accountingtypes,"systemcid" => $systemcid]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","add_post") -> "ffadff297f0a97a2330891c534e5ce93" RANDOM
    public function add_post(){
        $name = $_POST["name"];
        if(!$name){
            return beAjaxError(["message" => "Bir işlem ismi girmeniz gerekiyor!"]);
        }
        $total = (double)$_POST["total"];
        if(!$total){
            return beAjaxError(["message" => "Bir tutar belirtmeniz gerekiyor!"]);
        }
        $cid = (int)$_POST["currencie"];
        $currencie = CurrencyModel::beGetCurrencies("cid",$cid);
        if(!$currencie){
            return beAjaxError(["message" => "Belirtilen para birimi bulunamadı!"]);
        }
        $type = $_POST["type"];
        if(!in_array($type,["expense","income"])){
            return beAjaxError(["message" => "Belirtilen tür bulunamadı!"]);
        }
        $dateline = 0;
        if(is_numeric($_POST["time"])){
            $dateline = (int)$_POST["time"];
        }
        else{
            if($_POST["time"]){
                $dateline = strtotime($_POST["time"]);
            }
        }
        AccountingModel::beInsert([
            "cid" => $currencie["cid"],
            "aname" => $name,
            "atype" => $type,
            "atotal" => $total,
            "adateline" => $dateline,
        ]);
        return beAjaxSuccess(["message" => "Başarılı bir şekilde muhasebe girişi eklendi!"]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","addperiodic_post") -> "71dd0ac52db1236c80fda7dfe9bc938a" RANDOM
    public function addperiodic_post(){
        $name = $_POST["name"];
        if(!$name){
            return beAjaxError(["message" => "Bir işlem ismi girmeniz gerekiyor!"]);
        }
        $day = (int)$_POST["day"];
        if($day < 1 || $day > 30){
            return beAjaxError(["message" => "Gün doğru şekilde seçilmedi!"]);
        }
        $total = (double)$_POST["total"];
        if(!$total){
            return beAjaxError(["message" => "Bir tutar belirtmeniz gerekiyor!"]);
        }
        $cid = (int)$_POST["currencie"];
        $currencie = CurrencyModel::beGetCurrencies("cid",$cid);
        if(!$currencie){
            return beAjaxError(["message" => "Belirtilen para birimi bulunamadı!"]);
        }
        $type = $_POST["type"];
        if(!in_array($type,["expense","income"])){
            return beAjaxError(["message" => "Belirtilen tür bulunamadı!"]);
        }
        AccountingPeriodModel::beInsert([
            "cid" => $currencie["cid"],
            "apname" => $name,
            "apdate" => $day,
            "aptype" => $type,
            "aptotal" => $total,
            "apdateline" => BE_TIME,
        ]);
        return beAjaxSuccess(["message" => "Başarılı bir şekilde muhasebe için periyodik işlem eklendi!"]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","deleteperiodic_post") -> "a81142c7d44c7c9e66cee919b1661588" RANDOM
    public function deleteperiodic_post(){
        $apid = (int)$_POST["apid"];
        $accountingperiod = AccountingPeriodModel::beSelect("apid")->beWhere("apid",$apid)->beGet();
        if(!$accountingperiod){
            return beAjaxError(["message" => "Belirtilen periyodik işlem bulunamadı!"]);
        }
        AccountingPeriodModel::beDelete()->beWhere("apid",$accountingperiod["apid"])->beExecute();
        return beAjaxSuccess(["message" => "Başarılı bir şekilde periyodik işlem silindi!"]);
    }
    //@ioncube.dk beEncrypt("be_diyocp","search_post") -> "86c60ec2ca926334438a4ae77fc2cdaa" RANDOM
    public function search_post(){
        global $be;
        $pageitems = (int)$_POST["pageitems"];
        $name = $_POST["name"];
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $status = $_POST["status"];
        $startdate = $enddate = 0;
        if(is_numeric($_POST["start"])){
            $startdate = (int)$_POST["start"];
        }
        else{
            if($_POST["start"]){
                $startdate = strtotime($_POST["start"]);
            }
        }
        if(is_numeric($_POST["end"])){
            $enddate = (int)$_POST["end"];
        }
        else{
            if($_POST["end"]){
                $enddate = strtotime($_POST["end"]);
            }
        }
        $diffrencedate = round(($enddate-$startdate)/86400);
        $accountingsearch = AccountingModel::beSelect("COUNT(aid) as total");
        if($name){
            $accountingsearch = $accountingsearch->beWhere("aname",$name,"LIKE");
        }
        if($status && $status != "all"){
            $accountingsearch = $accountingsearch->beWhere("atype",$status);
        }
        if($startdate){
            $accountingsearch = $accountingsearch->beWhere("adateline",$startdate,">");
        }
        if($enddate){
            $accountingsearch = $accountingsearch->beWhere("adateline",$enddate,"<");
        }
        $accountingcount = (int)$accountingsearch->beGet()["total"];
        $paganation = bePaganation($page,$accountingcount,"",$pageitems);
        $accountings = AccountingModel::beSelect("*");
        if($name){
            $accountings = $accountings->beWhere("aname",$name,"LIKE");
        }
        if($status && $status != "all"){
            $accountings = $accountings->beWhere("atype",$status);
        }
        if($startdate){
            $accountings = $accountings->beWhere("adateline",$startdate,">");
        }
        if($enddate){
            $accountings = $accountings->beWhere("adateline",$enddate,"<");
        }
        switch($sort){
            case 1 :
                $accountings = $accountings->beOrder("adateline","DESC");
                break;
            case 2 :
                $accountings = $accountings->beOrder("adateline","ASC");
                break;
        }
        $accountings = $accountings->beGetAll();
        $systemcid = $be->settings["system_currency"];
        $totalincomemoney = 0.0;
        $totalexpensemoney = 0.0;
        foreach($accountings as $accounting){
            $money = 0;
            if($accounting["cid"] == $systemcid){
                $money = $accounting["atotal"];
            }
            else{
                $money = beConvertCurrencie($accounting["atotal"],$accounting["cid"],$systemcid);
            }
            if($accounting["atype"] == "income"){
                $totalincomemoney += $money;
            }
            else{
                $totalexpensemoney += $money;
            }
        }
        $moneyperday = round($totalincomemoney/$diffrencedate,2);
        $daycount = date("t");
        $currencies = CurrencyModel::beGetCurrencies("cid,crate,cicon");
        $accountingtypes = AccountingModel::beGetAccountingTypes();
        if($paganation["itemstart"] == 0){
            $accountings = array_slice($accountings,0,$paganation["itemlimit"]);
        }
        else{
            $accountings = array_slice($accountings,$paganation["itemstart"],$paganation["itemlimit"]);
        }
        $accountinghtml = beGetView("admin.accounting.listrows",["accountings" => $accountings,"currencies" => $currencies,"accountingtypes" => $accountingtypes]); 
        return beAjaxSuccess(["html" => $accountinghtml,"paganation" => $paganation["paganation"],"accountingcount" => $accountingcount,"financetotal" => beMoneyFormat($totalincomemoney-$totalexpensemoney),"incomemoneytotal" => beMoneyFormat($totalincomemoney),"expensemoneytotal" => beMoneyFormat($totalexpensemoney),"moneyperday" => beMoneyFormat($moneyperday),"monthmoney" => beMoneyFormat($daycount*$moneyperday),"daycount" => $diffrencedate]);
    }
}

?>