<?php

//the global file operation
include("../public/impOpreation.php");

//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
include_once("initiateStaticSessionCommingWithCurl.php");
include_once("dailyentryfun.php");
include("../library/uploadImages.php");

//here the db files that include in the file
include("../public/include_dao.php");
require_once('../models/dao/CostcenterDAO.class.php');
require_once('../models/dto/Costcenter.class.php');
require_once('../models/mysql/CostcenterMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterMySqlExtDAO.class.php');

require_once('../models/dao/CostcenterdetailDAO.class.php');
require_once('../models/dto/Costcenterdetail.class.php');
require_once('../models/mysql/CostcenterdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterdetailMySqlExtDAO.class.php');


//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');


//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');


//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');


//Expensetype
require_once('../models/dao/ExpensestypeDAO.class.php');
require_once('../models/dto/Expensestype.class.php');
require_once('../models/mysql/ExpensestypeMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensestypeMySqlExtDAO.class.php');
//ExpensesDAO
require_once('../models/dao/ExpensesDAO.class.php');
require_once('../models/dto/Expense.class.php');
require_once('../models/mysql/ExpensesMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensesMySqlExtDAO.class.php');
//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');
//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');
//User
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');

//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');
//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.class.php');


//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.class.php');

//lang

$lang = $_SESSION['erp_lang'];
include_once("../views/languages/$lang/expenses/expenses.php");
include_once("../views/languages/$lang/success.php");
include_once("../views/languages/$lang/error.php");

//get the do the action
$do = isset($_GET['do']) ? $_GET['do'] : '';
$lang = isset($_GET['lang']) ? $_GET['lang'] : '';
/* ======================

  Controller Name :- expensesCTRL

  OPERTATION in Controller

  1-display add form
  2- add in Expenses tble
  3-update save value (-)
  4-insert into savedaily tbl
  5-display sucess or error
  6-display show and delete
  7-delete from Expenses tbl
  8-update save value (+)
  9-insert into savedaily tbl
  10-display edit
  ======================== */



//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("header.html");
}

//here goes the instances and general variables

$Costcenterdetail = new Costcenterdetail();
$CostcenterdetailDAO = new CostcenterdetailMySqlDAO();
$CostcenterdetailEX = new CostcenterdetailMySqlExtDAO();

//Costcenter
$Costcenter = new Costcenter();
$CostcenterDAO = new CostcenterMySqlDAO();
$CostcenterEX = new CostcenterMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Expensetype
$ExpensetypeDAO = new ExpensestypeMySqlDAO();
$Expensetype = new Expensestype();
$ExpensetypeExt = new ExpensestypeMySqlExtDAO();
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
$Expense = new Expense();
$ExpenseExt = new ExpensesMySqlExtDAO();



//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();

//Client
$myClientRecord = $clientDAO = new ClientMySqlDAO();
$myClient = $client = new Client();
$myClientEx = $clientEX = new ClientMySqlExtDAO();
//save
$Save = new Save();
$SaveDAO = new SaveMySqlDAO();
$SaveExt = new SaveMySqlExtDAO();
//savedaily
$Savedaily = new Savedaily();
$SavedailyDAO = new SavedailyMySqlDAO();
//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupExt = new UsergroupMySqlExtDAO();
//User
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();
eval(base64_decode("ZnVuY3Rpb24gZ2VuZXJhdGVVVUlEKCkgewogICAgJGhvc3RuYW1lID0gZXhwbG9kZSgnY29udHJvbGxlcnMnLCAkX1NFUlZFUlsnU0NSSVBUX1VSSSddKVswXTsgLy9nZXRob3N0bmFtZSgpOwogICAgJGhvc3RuYW1lID0gc3RyX3JlcGxhY2UoYXJyYXkoImh0dHA6Ly8iLCAiaHR0cHM6Ly8iKSwgIiIsICRob3N0bmFtZSk7CgogICAgLy8gR2VuZXJhdGUgYW4gTUQ1IGhhc2ggb2YgdGhlIGlucHV0CiAgICAkZGF0YSA9IG1kNSgkaG9zdG5hbWUpOwogICAgLy8gRm9ybWF0IHRoZSBoYXNoIGFzIGEgVVVJRAogICAgJHV1aWQgPSBzcHJpbnRmKAogICAgICAgICAgICAnJTA4cy0lMDRzLSUwNHgtJTA0eC0lMTJzJywKICAgICAgICAgICAgc3Vic3RyKCRkYXRhLCAwLCA4KSwKICAgICAgICAgICAgc3Vic3RyKCRkYXRhLCA4LCA0KSwKICAgICAgICAgICAgKGhleGRlYyhzdWJzdHIoJGRhdGEsIDEyLCA0KSkgJiAweDBmZmYpIHwgMHg0MDAwLAogICAgICAgICAgICAoaGV4ZGVjKHN1YnN0cigkZGF0YSwgMTYsIDQpKSAmIDB4M2ZmZikgfCAweDgwMDAsCiAgICAgICAgICAgIHN1YnN0cigkZGF0YSwgMjAsIDEyKQogICAgKTsKICAgICR1dWlkID0gc3RyX3JlcGxhY2UoYXJyYXkoJy0nKSwgJycsICR1dWlkKTsKICAgIHJldHVybiAkdXVpZDsKfQ=="));
eval(base64_decode("ZnVuY3Rpb24gc2VyaWFsY2hlY2soKSB7CiAgICBpZiAoc3RydG91cHBlcihzdWJzdHIoUEhQX09TLCAwLCAzKSkgPT09ICdXSU4nKSB7CiAgICAgICAgLy91dWlkIG9mIHdpbmRvd3MKICAgICAgICBleGVjKCdDOlxXaW5kb3dzXFN5c3RlbTMyXHdiZW1cd21pYyBjc3Byb2R1Y3QgZ2V0ICJVVUlEIicsICRtYWNhZGRyZXNzLCAkaXNFeGVjdXRlZCk7CiAgICAgICAgJG1hY2FkZHJlc3MgPSAkbWFjYWRkcmVzc1sxXTsKICAgICAgICAkbWFjID0gc3RyX3JlcGxhY2UoYXJyYXkoJy0nKSwgJycsICRtYWNhZGRyZXNzKTsKICAgIH0gZWxzZSB7Ly9ub3Qgd2luZG93cyB1c2UgbGludXggbWFjCiAgICAgICAgJG1hYyA9IGdlbmVyYXRlVVVJRCgpOwogICAgfQoKICAgICRyYW5kb21fc2FsdCA9IGhhc2goJ3NoYTUxMicsICcxMzA1Jyk7CiAgICAvLyBDcmVhdGUgc2FsdGVkIHBhc3N3b3JkCiAgICAkaGFzaGVkTWFjID0gaGFzaCgnc2hhNTEyJywgJG1hYyAuICRyYW5kb21fc2FsdCk7CiAgICByZXR1cm4gJGhhc2hlZE1hYzsKfQ=="));
eval(base64_decode("JHNlcmlhbENhbCA9IHNlcmlhbGNoZWNrKCk7CmlmICgoJHByb2ctPnNlcmlhbCAhPSAkc2VyaWFsQ2FsICYmICRwcm9nLT5zZXJpYWwyICE9ICRzZXJpYWxDYWwgJiYgJHByb2ctPnNlcmlhbDMgIT0gJHNlcmlhbENhbCkgfHwgJF9TRVNTSU9OWydsaWNfZGF0ZXRvJ10gPCBkYXRlKCdZLW0tZCcpKSB7CiAgICAvL3NlbmQgdGhlIHVzZXIgdG8gdGhlIGxvZ291dCBwYWdlCiAgICBoZWFkZXIoImxvY2F0aW9uOmxvZ291dC5waHAiKTsKICAgIGV4aXQoKTsKfQ=="));
$expensesType = new Expensestype();
$expensesTypeDAO = new ExpensestypeMySqlDAO();

//
$bank = new Bank();
$bankDAO = new BankMySqlDAO();
$bankExt = new BankMySqlExtDAO();

//Bankaccount
$myBankaccount = new Bankaccount();
$myBankaccountRecord = new BankaccountMySqlDAO();
$myBankaccountEx = new BankaccountMySqlExtDAO();

//Product
$myProduct = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = $supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();
//
$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();


//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();


$today = date("Y-m-d");

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
eval(base64_decode("aWYgKCFmdW5jdGlvbl9leGlzdHMoJ3NlcmlhbGNoZWNrJykpIHsKICAgIENVUkxfSVQyKGFycmF5KCksICdzZWxsYmlsbEFqYXhDb250cm9sbGVyLnBocD9kbz1jYXRjaCcpOwogICAgaGVhZGVyKCJsb2NhdGlvbjpsb2dvdXQucGhwIik7Cn0="));
$userData = $myUserRecord->load($_SESSION['userid']);
$smarty->assign("userData", $userData);
$allSave = $SaveDAO->queryAll();
$smarty->assign("allSave", $allSave);
$bank = $bankDAO->queryAll();
$smarty->assign("bank", $bank);

//check and use the condition that suite this action
$smarty->assign("usergroupid", $_SESSION['usergroupid']);
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    $allParents = getExtepensesTypeParents();
    $smarty->assign("allParents", $allParents);

    $suppliersData = $supplierDAO->queryByCondition(0);
    $smarty->assign("suppliersData", $suppliersData);

    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
            $saves = $saveDAO->queryAll();
        } else {
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $SaveExt->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("allSave", $saves);
        $smarty->assign("saveid", $_SESSION['saveid']);
    } else {
        $smarty->assign('allSave', $_SESSION['saveid']);
    }




    if ($_SESSION['bankids'] == 0) {
        $bank = $bankDAO->queryAll();
    } else {
        $queryString = ' and bankid in (' . $_SESSION['bankids'] . ')';
        $bank = $bankExt->queryWithConditionWithQueryString($queryString);
    }
    $smarty->assign("bank", $bank);


    
    $allTags = R::getAll('select * from associatedtags where conditions = 0');
    $smarty->assign('allTags', $allTags);

    $allChasis = R::getAll("select DISTINCT chasisno from importcontract where chasisno != '' and del <2");
    $smarty->assign('allChasis', $allChasis);

    /* // here the function that do the action
      $outputString = display_children(0, 0);  //display the tree
      $smarty->assign("treeHTML", $outputString); */

    $smarty->assign("expensesScripts", 1);



    //here the smarty templates
    if ($lang == "en")
        $smarty->display("expensesview/add_ltr.html");
    else
        $smarty->display("expensesview/add.html");
} elseif ($do == "add") {
    //here the permission check
    // include_once("../public/authentication.php");
    // here the function that do the action
    $saveValuebeforeValid = add();
    $add_print = (int) filter_input(INPUT_POST, 'add_print');
    if ($saveValuebeforeValid[1] > 0) {
        if ($_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success', 'id' => (int) $saveValuebeforeValid[1]);
            echo json_encode($data);
        } else {
            if ($add_print == 1) {
                header("location: expensesController.php?do=editprint&id=" . $saveValuebeforeValid[1]);
            } else {
                header("location:?do=sucess");
            }
        }
    } else {
        $url = "expensesController.php?do=show";
        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى";
        } else {
            $note = "There is not enough amount in the main safe";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");
    $projectid = filter_input(INPUT_GET, "proid");

    // $alldata = $ExpensetypeExt->queryAllChildrenExt2();
    // $smarty->assign("alldata", $alldata);
    $allParents = $ExpensetypeExt->expensetypesave('');
    $smarty->assign("alldata", $allParents);
    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

    $expensestypeid = $_REQUEST['expensestypeid'];
    $from = $_REQUEST['from'];
    $to = $_REQUEST['to'];
    $costCenterId = $_REQUEST['Costcenterid'];
    $id = (int) $_REQUEST['id'];
    if ($projectid > 0) {
        $costCenterId = $projectid;
    }
    $productid = $_REQUEST['productid'];
    $tripid = (int) $_REQUEST['tripid'];
    $smarty->assign("projectid", $projectid);
    //$costCenterId = filter_input(INPUT_GET, 'costcid');







    $queryString = '';
    $userdata = $myUserRecord->load($_SESSION['userid']);
    if ($userdata->searchinonesave == 1) {
        $queryString .= ' and expenses.saveid = ' . $userdata->saveid;
    }

    $message = ' عرض مصروفات ';
    if ($id > 0) {
        $message .= " برقم " . $id;
        $queryString .= ' and expenses.expensesid = ' . $id;
    } else {
        if (!empty($costCenterId)) {
            $costcData = $CostcenterDAO->load($costCenterId);
            $message .= " مشروعات " . $costcData->name;
            $queryString .= ' and expenses.costcenterid = ' . $costCenterId;
        }
        if ($productid > 0) {
            $queryString .= ' and expenses.productid = ' . $productid;
        }
        if ($tripid > 0) {
            $queryString .= ' and expenses.travelTripId = ' . $tripid;
        }
        if (isset($expensestypeid) && $expensestypeid != "-1") {
            $mytypedata = $ExpensetypeDAO->load($expensestypeid);
            $message .= " مصروفات " . $mytypedata->expensestypename;
            $queryString .= ' and expenses . expensestypeid = ' . $expensestypeid;
        }
        if (isset($from) && $from != "") {
            $message .= " من تاريخ : " . $from;
            $queryString .= ' and expenses.expensesdate >= "' . $from . '"';
        }
        if (isset($to) && $to != "") {
            $message .= "  الى تاريخ:  " . $to;
            $queryString .= ' and expenses.expensesdate <= "' . $to . '"';
        }
    }
    $smarty->assign('message', $message);

    if ($queryString != "") {
        $result = R::getAll('SELECT expensestype.expensestypename, expensestype.addOnlyGroupIds, expenses.*, expensestype.conditions as expensestypeConditions, productName, name, client.clientname as clientid, supplier.suppliername as supplier,save.savename,CONCAT(bank.bankname," - ",bankaccount.accountname) as accountname
        FROM expenses
        join expensestype on expensestype.expensestypeid = expenses.expensestypeid
        left join product on expenses.productid = product.productid
        left join client on expenses.clientid = client.clientid
        left join supplier on expenses.supplier = supplier.supplierid
        left join costcenter on expenses.costcenterid = costcenter.id
        left join save on save.saveid = expenses.saveid
        left join bank on bank.bankid = expenses.bankid
        left join bankaccount on bankaccount.accountid = expenses.bankaccountid
        where expensestype.conditions = 0 ' . $queryString . ' order by expensesid desc');
    }

    $sum = 0;
    $expenseData = array();
    foreach ($result as $data) {
        $data = (object) $data;
        $data->addOnlyGroupIds = explode(',  ', $data->addOnlyGroupIds); //this line for group validation from expenseType
        if ($data->conditions == 0) {
            $sum = $data->expensesValue + $sum;
        }

        if ($data->realestateid) {
            $realestate = R::load('realestates', $data->realestateid);
            $data->realestatename = $realestate->realestatename;
            $realestateunit = R::load(' realestatesunits', $data->realestateunitid);
            $data->unitdata = $realestateunit->unitname . ' /' . $realestateunit->unitarea;
        }
        array_push($expenseData, $data);
    }
    $smarty->assign('expenseData', $expenseData);
    $smarty->assign('sum ', $sum);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->assign("customCheck", 1);
    $smarty->display("expensesview/show.html");
} elseif ($do == "executeOperation") {
    try {
        executeOperation();
        show();
        $smarty->assign("customCheck", 1);
        $smarty->display("expensesview/show.html");
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    try {
        $note = delete();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            if ($note != "success") {
                $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            } else {
                $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            }
            echo json_encode($data);
        } else {
            if ($note != "success") {
                $smarty->assign('msgnote', $note);
                $smarty->display("notes.html");
            } else {
                header("location:?do=sucess");
            }
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "returndelete") { //returndelete
    include_once("../public/authentication.php");
    try {
        $note = returndelete();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") { //tempdelete
    include_once("../public/authentication.php");
    try {
        $note = tempdelete();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        //header("location:?do=error");
    }
} elseif ($do == "editprint") { //edit  Expensetype
    //here the permssion check
    include_once("../public/authentication.php");
    $alldata = expensesType();
    $smarty->assign("alldata", $alldata);

    $Expensealldata = edit();
    if(empty($Expensealldata->tagids)) {
        $Expensealldata->tagids = 0;
    }
    $tagNames = R::getCol('select tagname from associatedtags where id in ('.$Expensealldata->tagids.')');
    $tagNamesData = "";
    foreach ($tagNames as $name) {
        $tagNamesData .= $name. ', ';
    }
    $Expensealldata->tagids = rtrim($tagNamesData,', ');
    $smarty->assign("Expensealldata", $Expensealldata);

    $smarty->display("expensesview/editprint.html");
} elseif ($do == "edit") { //edit  Expensetype
    //here the permssion check
    include_once("../public/authentication.php");
    $allParents = getExtepensesTypeParents();
    $smarty->assign("alldata", $allParents);

    $suppliersData = $supplierDAO->queryByCondition(0);
    $smarty->assign("suppliersData", $suppliersData);


    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
            $saves = $saveDAO->queryAll();
        } else {
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $saveEX->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("allSave", $saves);
        $smarty->assign("saveid", $_SESSION['saveid']);
    } else {
        $smarty->assign('allSave', $_SESSION['saveid']);
    }




    if ($_SESSION['bankids'] == 0) {
        $bank = $bankDAO->queryAll();
    } else {
        $queryString = ' and bankid in (' . $_SESSION['bankids'] . ')';
        $bank = $bankExt->queryWithConditionWithQueryString($queryString);
    }
    $smarty->assign("bank", $bank);

    $allTags = R::getAll('select * from associatedtags where conditions = 0');
    $smarty->assign('allTags', $allTags);

    $allChasis = R::getAll("select DISTINCT chasisno from importcontract where chasisno != '' and del <2");
    $smarty->assign('allChasis', $allChasis);

    //    print_r('<pre>');
    //    print_r($allParents);
    //    print_r('<pre>');

    $Expensealldata = edit();

    $expensetype = $ExpensetypeDAO->load($Expensealldata->expensestypeid);
    $smarty->assign("expensetype", $expensetype);


    if ($Expensealldata->sellbillid) {
        $sellbilldata = $mySellbillRecord->load($Expensealldata->sellbillid);
        $smarty->assign("sellbilldata", $sellbilldata);

        $Clientdata = $myClientRecord->load($Expensealldata->clientid);
        $smarty->assign("Clientdata", $Clientdata);
    }


    if ($Expensealldata->realestateid) {
        $realestate = R::load('realestates', $Expensealldata->realestateid);
        $smarty->assign('realestate', $realestate);

        $realestateunit = R::load('realestatesunits', $Expensealldata->realestateunitid);
        $smarty->assign('realestateunit', $realestateunit);
    }

    $productdata = $productDAO->load($Expensealldata->productid);
    $smarty->assign("productdata", $productdata);
    $smarty->assign("Expensealldata", $Expensealldata);

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $bankAccount = $myBankaccountRecord->queryByBankid($Expensealldata->bankid);
    $smarty->assign("bankAccount", $bankAccount);


    $smarty->display("expensesview/edit.html");
} elseif ($do == "update") { //edit update
    //here the permssion check
    include_once("../public/authentication.php");
    //
    // here the function that do the action
    $saveValuebeforeValid = update();
    if ($saveValuebeforeValid == "1" || $saveValuebeforeValid == "2") {
        header("location:?do=sucess");
    } else {
        $url = "expensesController.php?do=show";
        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى";
        } else {
            $note = "There is not enough amount in the main safe";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    //$smarty->display("error.html");
}
$smarty->assign("expensesScripts", 1);

//here the global templates
$smarty->assign("customValidation", 1);
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("footer.html");
}

/* ===============================
  function in this CONTROLLER
  ================================ */

function getExtepensesTypeParents() {
    global $ExpensetypeExt;
    global $ExpensetypeDAO;
    global $userData;

    if ($userData->searchinonesave == 0) {
        $allParents = $ExpensetypeExt->queryAllExtNotParent();
    } else {
        $allParents = $ExpensetypeExt->queryAllWithSaveNotParent($_SESSION['saveid']);
    }

    foreach ($allParents as $value) {
        if ($value->parent > 0) {
            $value->expensestypename = "$value->parentexpensestypename / $value->expensestypename";
        }
    }
    return $allParents;
}

//expensesType
function expensesType() {
    //to use the variable outside the funcion
    global $ExpensetypeExt;

    $alldata=$ExpensetypeExt->queryAllExt();
    //كل التصنيفات التي ليست parent لأي تصنيف آخر
    // $alldata = $ExpensetypeExt->queryAllChildren();
    return $alldata;
}

function getExpensesByType($typeid) {
    global $ExpenseDAO;

    $expensesData = $ExpenseDAO->queryByExpensestypeid($typeid);
    return $expensesData;
}

// add in expenses tbl
function add() {
    global $ExpenseDAO;
    global $Expense;
    global $today;

    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;
    global $ExpensetypeDAO;
    global $Expensetype;
    global $accountsTreeDAO;
    global $accountsTree;

    //save
    global $mySave;
    global $SaveDAO;

    global $myBankaccountRecord;

    $expensesname = $_POST['expensesname'];
    $expensevalue = $_POST['expensevalue'];
    $expensetype = $_POST['expensetype'];
    $expensecomment = $_POST['expensecomment'];
    $Costcenterid = $_POST['Costcenterid'];
    $productid = $_POST['productid'];
    $saveid = (int) $_POST['saveid'];
    $expensenumbrt = $_POST['expensenumbrt'];
    $expenseprice = $_POST['expenseprice'];
    $expensetotaln = $_POST['expensetotaln'];
    $expenseshortfalls = $_POST['expenseshortfalls'];
    $supplier = (int) $_POST['supplier'];
    $suppRemainingVal = (float) $_POST['suppRemainingVal'];
    $clientid = (int) $_POST['clientid'];
    $sellbillid = (int) $_POST['sellbillid'];
    $realestateid = (int) $_POST['realestateid'];
    $realestateunitid = (int) $_POST['realestateunitid'];
    $taxExist = (int) $_POST['taxExist'];
    $tax = (float) $_POST['tax'];
    $taxVal = (float) $_POST['taxVal'];

    $travelDriverId = (int) $_POST['travelDriverId'];
    $travelBusId = (int) $_POST['travelBusId'];
    $travelPathId = (int) $_POST['travelPathId'];
    $travelTripId = (int) $_POST['travelTripId'];
    $travelTripTypeId = (int) $_POST['travelTripTypeId'];
    $travelTripDateId = (int) $_POST['travelTripDateId'];
    $travelOfficeId = (int) $_POST['travelOfficeId'];
    $chasis = filter_input(INPUT_POST, 'chasis');

    $tagids = filter_input(INPUT_POST, 'tagids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);


    $expensevalueAfterTax = $expensevalue + $taxVal;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    global $expensesTypeDAO;
    global $expensesType;

    global $userData;
    global $supplierDAO;


    global $clientDAO;

    global $clientDeptChange;
    global $clientDeptChangeDAO;
    //Transaction
    $mytransactions = new Transaction();
    try {
        $paymethod = (int) $_POST["paymethod"];
        $saveValuebeforeValid = "1";

        //////////////////////////check save value before expenses///////////////////////////
        //check save value
        if ($paymethod == 0 && $expensevalue > 0) {

            //get save value
            if ($userData->searchinonesave == 0) {
                $saveValueBefore = getSaveValue($saveid);
            } else {
                $saveValueBefore = getSaveValue();
            }
            // $saveValuebeforeValid;
            $saveValueafterValid = $saveValueBefore - $expensevalue;

            if ($saveValueafterValid >= 0) {
                $saveValuebeforeValid = "1"; //continue
            } else {
                $saveValuebeforeValid = "0"; //stop and return, show error
                //return $saveValuebeforeValid;
            }
        }
        //////////////////////////////////////////////////////////////////////////////////////
        //add in expenses tbl
        if ($paymethod == 1) {
            ##bank
            $bankid = $_POST["bankid"];
            $bankaccountid = $_POST["bankaccountid"];
            $checkNo = $_POST["checkNo"];
            $Expense->saveid = 0;
            $Expense->bankid = $bankid;
            $Expense->bankaccountid = $bankaccountid;
            $Expense->checknum = $checkNo;
        } else {
            ##save
            $saveid = (int) $_POST["saveid"];
            $Expense->saveid = $saveid;
            $Expense->bankid = 0;
            $Expense->bankaccountid = 0;
            $Expense->checknum = '';
        }
        $Expense->expensesname = $expensesname;
        if ($paymethod < 3) {
            $Expense->expensesValue = $expensevalue;
        } else {
            $Expense->expensesValue = -$expensevalue;
        }
        $Expense->conditions = 0;
        $Expense->expensestypeid = $expensetype;
        $Expense->expensesdate = $today;
        $Expense->userid = $_SESSION["userid"];
        $Expense->expensesdetails = $expensecomment;
        $Expense->costcenterid = $Costcenterid;
        $Expense->productid = $productid;

        $Expense->dailyentryid = 0;
        $Expense->expensenumbrt = $expensenumbrt;
        $Expense->expenseprice = $expenseprice;
        $Expense->expensetotaln = $expensenumbrt * $expensenumbrt;
        $Expense->expenseshortfalls = $expenseshortfalls;
        $Expense->supplier = $supplier;
        $Expense->clientid = $clientid;
        $Expense->sellbillid = $sellbillid;
        $Expense->realestateid = $realestateid;
        $Expense->realestateunitid = $realestateunitid;
        $Expense->suppRemainingVal = $suppRemainingVal;
        $Expense->taxPer = $tax;
        $Expense->taxVal = $taxVal;
        $Expense->travelDriverId = $travelDriverId;
        $Expense->travelBusId = $travelBusId;
        $Expense->travelPathId = $travelPathId;
        $Expense->travelTripId = $travelTripId;
        $Expense->travelTripTypeId = $travelTripTypeId;
        $Expense->travelTripDateId = $travelTripDateId;
        $Expense->travelOfficeId = $travelOfficeId;
        $Expense->webApiId = (int) $_POST['webApiId'];
        $Expense->chasis = $chasis == 'اختر الشاسيه' ? '' : $chasis;


        $handle = new upload($_FILES['file']);
        $file = uploadImageswhioutresize($handle, '../upload/expenseFile');
        $Expense->file = $file;

        if (isset($tagids)) {
            if (in_array("0", $tagids)) {
                $Expense->tagids = '0';
            } else {
                $Expense->tagids = implode(",", $tagids);
            }
        }

        // print_r($expensetype . 'aaaaaaaaaaaaaaaaaaaaaaaaaa');
        $expenseId = $ExpenseDAO->insert($Expense);

        #### affect supplier Debt
        affectSupplierWithExpense($supplier, $expensevalueAfterTax, $suppRemainingVal, $expenseId, $expensecomment, 'add');


        $Costcenterdetail->processname = 'اضافه مصروف';
        $Costcenterdetail->type = 6;
        $Costcenterdetail->costamount = $expensevalueAfterTax;
        $Costcenterdetail->costcenterid = $Costcenterid;
        $Costcenterdetail->costdate = date('Y-m-d');
        $Costcenterdetail->del = 0;
        $Costcenterdetail->modelid = $expenseId;
        $Costcenterdetail->tablename = 'expensesController.php';
        $Costcenterdetail->uesrid = $_SESSION['userid'];

        if ($Costcenterid != -1 && $Costcenterid != '-1') {
            $CostcenterdetailDAO->insert($Costcenterdetail);
        }


        if ($paymethod == 0 && $expensevalue > 0) {
            //get saveVsalue before and saveValue after mins expensesValue
            if ($userData->searchinonesave == 0) {
                $valueData = getSaveValueAndMins($expensevalue, $saveid);
            } else {
                $valueData = getSaveValueAndMins($expensevalue);
            }
            if (count($valueData) > 0) {
                $saveId = $valueData[0];
                $saveValuebefore = $valueData[1];
                $saveValueafter = $valueData[2];

                //update save value after expenses
                updateSave($saveId, $saveValueafter);
                //insert into savedaily tbl
                insertSavedaily($saveValuebefore, $expensevalue, 1, $saveId, "إضافة مصروف", $expenseId, $saveValueafter, "expensesController.php");
            }
        }

        $typeData = $ExpensetypeDAO->load($expensetype);
        $typeTreeId = $typeData->treeId;

        $dailyEntry->entryComment = 'اضافة اسم مصروف( ' . $expensesname . ' )';


        //Dailyentrycreditor دائن
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $expensevalueAfterTax;

        if ($paymethod == 0) {
            //save session
            if ($userData->searchinonesave == 1) {
                $saveid = $_SESSION['saveid'];
            }
            $dataSave = $SaveDAO->load($saveid);

            $idTreeSave = $dataSave->treeId;
            $dailyEntryCreditor->accountstreeid = $idTreeSave;
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        } elseif ($paymethod == 1) {
            $dataBankAccount = $myBankaccountRecord->load($bankaccountid);
            //tree account
            $treeIdBankAccount = $dataBankAccount->treeId;
            $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;

            //decrease account value and write in history
            $accValOld = $dataBankAccount->accountbeginingbalance;
            $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $expensevalue;
            $myBankaccountRecord->update($dataBankAccount);
            insertAccountmovement($accValOld, $expensevalue, 1, $dataBankAccount->accountbeginingbalance, "اضافة مصروف", $expenseId, $dataBankAccount->accountid, $dataBankAccount->bankid, "expensesController.php");
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        } elseif ($paymethod == 2) {

            $dataSupplier = $supplierDAO->load($supplier);
            $idTreeSupplier = $dataSupplier->treeId;
            $dailyEntryCreditor->accountstreeid = $idTreeSupplier;
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        }


        if ($paymethod == 3) {

            $clientData = $clientDAO->load($clientid);
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $expensevalue;
            $treeId = $clientData->treeId;
            $dailyEntryDebtor->accountstreeid = $treeId;
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);


            $debtAfter = $clientData->clientdebt + $expensevalue;
            R::exec("UPDATE `client` SET `clientdebt`= $debtAfter where clientid =  ? ", [$clientid]);
            $clientDeptChange->comment = $expensecomment;
            $clientDeptChange->processname = $expensecomment;
            $clientDeptChange->clientdebtchangeafter = $debtAfter;
            $clientDeptChange->clientdebtchangeamount = $expensevalue;
            $clientDeptChange->totalOperationCost = $expensevalue;
            $clientDeptChange->clientdebtchangebefore = $clientData->clientdebt;
            $clientDeptChange->clientdebtchangedate = date("Y-m-d H:i:s"); //$today;
            $clientDeptChange->clientdebtchangemodelid = $expenseId;
            $clientDeptChange->paySerialNo = 0;
            $clientDeptChange->clientdebtchangetype = 1;
            $clientDeptChange->tablename = "expensesController.php";
            $clientDeptChange->userid = $_SESSION['userid'];
            $clientDeptChange->clientid = $clientData->clientid;
            $clientDeptChange->seller = 0;
            $clientDeptChange->dailyentryid = 0;
            $clientDeptChange->discountearlyRepayment = NULL;
            $clientDeptChange->costcenterid = $Costcenterid;
            $clientDeptChange->currencyId = 1;
            $clientDeptChange->conversionFactor = 1;
            $clientDeptChange->payedInCurrency = $expensevalue;
            $clientDeptChange->totalpayments = NULL;
            $clientDeptChangeDAO->insert($clientDeptChange);



            $expenseTypeData = $expensesTypeDAO->load($expensetype);
            $idTreeexpenseType = $expenseTypeData->treeId;
            $dailyEntryCreditor->accountstreeid = $idTreeexpenseType;
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        } else {

            //end  save data
            //Dailyentrydebtor مدين
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $expensevalue;
            $expenseTypeData = $expensesTypeDAO->load($expensetype);


            $treeId = $expenseTypeData->treeId;
            $dailyEntryDebtor->accountstreeid = $treeId;
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        }
        // //end  save data
        // //Dailyentrydebtor مدين
        // $dailyEntryDebtorArray = array();
        // $dailyEntryDebtor->value = $expensevalue;
        // // load expensestypename using expensestypeid
        // $expenseTypeData = $expensesTypeDAO->load($expensetype);
        // $treeId = $expenseTypeData->treeId;
        // $dailyEntryDebtor->accountstreeid = $treeId;
        // array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

        if ($taxExist == 1) {
            $dailyEntryDebtor = new stdClass();
            $vatTreeId = 76; ##ضريبة القيمة المضافة - مدينة
            //$vatTreeId = 106; ##ضريبة القيمة المضافة - دائنة
            $dailyEntryDebtor->accountstreeid = $vatTreeId;
            $dailyEntryDebtor->value = $taxVal;
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        }
        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $expenseId, "expensesController.php?do=show&id=$expenseId");
        $did = $returnedData[1];

        $rowData = $ExpenseDAO->load($expenseId);
        $rowData->dailyentryid = $did;
        $ExpenseDAO->update($rowData);
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }
    return array($saveValuebeforeValid, $expenseId);
}

function executeOperation() {
    global $ExpenseDAO;
    global $ExpenseExt;
    global $smarty;

    global $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $expensesid) {
            if ($operationType == '1') { //tempdelete
                try {
                    $note = tempdelete($expensesid);
                } catch (Exception $e) {

                }
            } elseif ($operationType == "2") { //returndelete
                $note = returndelete($expensesid);
                //$outputString = "تمت العملية بنجاح";
            } elseif ($operationType == "3") { //delete
                $note = delete($expensesid);
                //$outputString = "تمت العملية بنجاح";
            }

            if ($note != "success") {
                //get product category name
                $expensesData = $ExpenseDAO->load($expensesid);
                if (count($expensesData) > 0) {
                    $expensesName = $expensesData->expensesname;
                    $outputString .= $expensesName . ": " . $note . "<br/>";
                }
            } else {
                $outputString = "تمت العملية بنجاح";
            }

            $i++;
        }
        $smarty->assign("outputString", $outputString);
    }
}

function delete($expenseid) {

    ///////////////////////////////////////////////// لسا مخلصتش
    global $ExpenseDAO;
    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;


    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    global $accountsTreeDAO;
    global $accountsTree;

    //save
    global $mySave;
    global $SaveDAO;

    global $expensesTypeDAO;
    global $expensesType;
    global $myBankaccountRecord;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $expensetype = $_POST['expensestype'];
        $dailyentryid = $_GET['dailyentryid'];
        if (empty($expenseid)) {
            $expenseid = $_GET['id'];
            $expense = $ExpenseDAO->load($expenseid);
        }

        if (!empty($expenseid)) {
            //get expensesvalue by expensesid
            $expenseData = $ExpenseDAO->load($expenseid);
            $expensevalue = $expenseData->expensesValue;
            $tempdelete = $expenseData->conditions;
            //delete from expenses tbl

            $ExpenseDAO->delete($expenseid);
            reverseEntryWithItsID($dailyentryid, 1);
            $CostcenterdetailEX->updatedellbytypeandmodelid('6', $expenseid, 1);


            //check if this expenses tempdeleted or not
            //يجب أن يكون المصروف غير محذوف حذف مؤقت وإلا الخزنة هتزيد مرتين
            if ($tempdelete == 0) {
                #### affect supplier Debt
                affectSupplierWithExpense($expenseData->supplier, $expensevalue, $expenseData->suppRemainingVal, $expenseid, $expenseData->expensesdetails, 'del');
                if ($expensevalue > 0) {
                    if ($expenseData->saveid > 0) {
                        //get saveValue before and saveValue after plus expensesValue
                        $valueData = getSaveValueAndPlus($expensevalue, $expenseData->saveid);
                        if (count($valueData) > 0) {
                            $saveId = $valueData[0];
                            $saveValuebefore = $valueData[1];
                            $saveValueafter = $valueData[2];

                            //update save value after expenses
                            updateSave($saveId, $saveValueafter);

                            //insert into savedaily tbl
                            insertSavedaily($saveValuebefore, $expensevalue, 0, $saveId, "حذف مصروف", $expenseid, $saveValueafter, "expensesController.php");
                        }
                    } elseif ($expenseData->bankid > 0) {
                        $dataBankAccount = $myBankaccountRecord->load($expenseData->bankaccountid);
                        //tree account
                        $treeIdBankAccount = $dataBankAccount->treeId;

                        //decrease account value and write in history
                        $accValOld = $dataBankAccount->accountbeginingbalance;
                        $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $expensevalue;
                        $myBankaccountRecord->update($dataBankAccount, '');
                        insertAccountmovement($accValOld, $expensevalue, 0, $dataBankAccount->accountbeginingbalance, "حذف مصروف", $expenseid, $dataBankAccount->accountid, $dataBankAccount->bankid, "expensesController.php");
                    } elseif ($expenseData->supplier > 0) {

                    }
                }
            }
            $note = "success";
        } else {
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "حدث خطأ أثناء إتمام العملية";
            } else {
                $note = "An error occurred while completing the operation";
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }
    return $note;
}

function tempdelete($expenseid) {
    global $ExpenseExt;
    global $ExpenseDAO;


    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;
    global $userData;
    global $accountsTreeDAO;
    global $myBankaccountRecord;

    //Transaction
    $mytransactions = new Transaction();
    try {
        if (empty($expenseid)) {
            $expenseid = $_GET['id'];
        }
        if (!empty($expenseid)) {
            try {
                //get expensesvalue by expensesid
                $expenseData = $ExpenseDAO->load($expenseid);
                $expensevalue = $expenseData->expensesValue;

                //temp delete from expenses tbl
                $ExpenseExt->deletetemp($expenseid);
                if ($expenseData->saveid > 0) {
                    $paymethod = 0;
                } elseif ($expenseData->bankid > 0) {
                    $paymethod = 1;
                }
                #### affect supplier Debt
                affectSupplierWithExpense($expenseData->supplier, $expensevalue, $expenseData->suppRemainingVal, $expenseid, $expenseData->expensesdetails, 'del');

                $CostcenterdetailEX->updatedellbytypeandmodelid('6', $expenseid, 1);

                if ($paymethod == 0 && $expensevalue > 0) {
                    //get saveValue before and saveValue after adding expensesValue
                    //                    if ($userData->searchinonesave == 0) {
                    //var_dump($expenseData->saveid);
                    $valueData = getSaveValueAndPlus($expensevalue, $expenseData->saveid);
                    //                    } else {
                    //                        $valueData = getSaveValueAndPlus($expensevalue);
                    //                    }
                    //var_dump($valueData);
                    if (count($valueData) > 0) {
                        $saveId = $valueData[0];
                        $saveValuebefore = $valueData[1];
                        $saveValueafter = $valueData[2];

                        //update save value after expenses
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl
                        insertSavedaily($saveValuebefore, $expensevalue, 0, $saveId, "حذف مصروف", $expenseid, $saveValueafter, "expensesController.php");
                    }
                }
                if ($paymethod == 1 && $expensevalue > 0) {
                    $dataBankAccount = $myBankaccountRecord->load($expenseData->bankaccountid);
                    //tree account
                    $treeIdBankAccount = $dataBankAccount->treeId;

                    //decrease account value and write in history
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $expensevalue;
                    $myBankaccountRecord->update($dataBankAccount);
                    insertAccountmovement($accValOld, $expensevalue, 0, $dataBankAccount->accountbeginingbalance, "حذف مصروف", $expenseid, $dataBankAccount->accountid, $dataBankAccount->bankid, "expensesController.php");
                }

                $note = "success";
            } catch (Exception $e) {
                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = "حدث خطأ أثناء إتمام العملية";
                } else {
                    $note = "An error occurred while completing the operation";
                }
            }
        } else {
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "حدث خطأ أثناء إتمام العملية";
            } else {
                $note = "An error occurred while completing the operation";
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }
    return $note;
}

function returndelete($expenseid) {
    global $ExpenseExt;
    global $ExpenseDAO;
    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;
    global $accountsTreeDAO;
    global $myBankaccountRecord;

    //Transaction
    $mytransactions = new Transaction();
    try {
        if (empty($expenseid)) {
            $expenseid = $_GET['id'];
        }

        if (!empty($expenseid)) {
            try {
                //get expensesvalue by expensesid
                $expenseData = $ExpenseDAO->load($expenseid);
                $expensevalue = $expenseData->expensesValue;

                if ($expenseData->saveid > 0) {
                    $paymethod = 0;
                } elseif ($expenseData->bankid > 0) {
                    $paymethod = 1;
                }

                $saveValuebeforeValid = "1";
                //////////////////////////check save value before expenses///////////////////////////
                //check save value
                if ($paymethod == 0 && $expensevalue > 0) {
                    //get save value
                    $saveValueBefore = getSaveValue($expenseData->saveid);
                    $saveValuebeforeValid;
                    $saveValueafterValid = $saveValueBefore - $expensevalue;
                    if ($saveValueafterValid >= 0) {
                        $saveValuebeforeValid = "1";
                    } else {
                        $saveValuebeforeValid = "0";
                        if ($_SESSION['erp_lang'] == 'ar') {
                            $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى";
                        } else {
                            $note = "There is not enough amount in the main safe";
                        }                          //return $note;
                    }
                }
                //////////////////////////////////////////////////////////////////////////////////////
                //return delete from expensetype tbl
                $ExpenseExt->returndelete($expenseid);
                $CostcenterdetailEX->updatedellbytypeandmodelid('6', $expenseid, 0);


                #### affect supplier Debt
                affectSupplierWithExpense($expenseData->supplier, $expensevalue, $expenseData->suppRemainingVal, $expenseid, $expenseData->expensesdetails, 'add');

                if ($paymethod == 0 && $expensevalue > 0) {
                    //get saveVsalue before and saveValue after mins expensesValue
                    $valueData = getSaveValueAndMins($expensevalue, $expenseData->saveid);
                    if (count($valueData) > 0) {
                        $saveId = $valueData[0];
                        $saveValuebefore = $valueData[1];
                        $saveValueafter = $valueData[2];

                        //update save value after expenses
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl
                        insertSavedaily($saveValuebefore, $expensevalue, 1, $saveId, "إضافة مصروف", $expenseid, $saveValueafter, "expensesController.php");
                        //$note = "success";
                    }
                }

                if ($paymethod == 1 && $expensevalue > 0) {
                    $dataBankAccount = $myBankaccountRecord->load($expenseData->bankaccountid);
                    //tree account
                    $treeIdBankAccount = $dataBankAccount->treeId;

                    //decrease account value and write in history
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $expensevalue;
                    $myBankaccountRecord->update($dataBankAccount);
                    insertAccountmovement($accValOld, $expensevalue, 1, $dataBankAccount->accountbeginingbalance, "اضافة مصروف", $expenseid, $dataBankAccount->accountid, $dataBankAccount->bankid, "expensesController.php");
                }
            } catch (Exception $e) {
                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = "حدث خطأ أثناء إتمام العملية";
                } else {
                    $note = "An error occurred while completing the operation";
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }
    return $note;
}

function edit() {
    global $ExpenseDAO;
    global $ExpenseExt;

    $expenseid = $_GET['id'];
    $Expensealldata = $ExpenseDAO->load($expenseid);
    
    $Expensealldata->tagids = explode(',', $Expensealldata->tagids);
    return $Expensealldata;
}

function update() {
    global $Expense;
    global $ExpenseExt;
    global $ExpenseDAO;

    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;

    global $accountsTreeDAO;
    global $accountsTree;

    //save
    global $mySave;
    global $SaveDAO;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    global $ExpensetypeDAO;
    global $Expensetype;

    global $userData;

    global $myBankaccountRecord;

    //    //Transaction
    $mytransactions = new Transaction();
    try {
        $paymethod = (int) $_POST["paymethod"];

        $expensesname = $_POST['expensesname'];
        $expensevalue = $_POST['expensevalue'];
        $expensetype = $_POST['expensetype']; // دا ال Id الجديد
        $expensecomment = $_POST['expensecomment'];
        $expenseid = $_POST['expenseid'];
        $conditions = $_POST['conditions'];
        $oldExpensestypeid = $_POST['oldExpensestypeid'];
        $saveid = (int) $_POST['saveid'];
        $bankid = (int) $_POST['bankid'];
        $bankaccountid = (int) $_POST['bankaccountid'];
        $checkNo = $_POST['checkNo'];
        $productid = $_POST['productid'];
        $dailyentryid = $_POST['dailyentryid'];
        $expensenumbrt = $_POST['expensenumbrt'];
        $expenseprice = $_POST['expenseprice'];
        $expensetotaln = $_POST['expensetotaln'];
        $expenseshortfalls = $_POST['expenseshortfalls'];
        $supplier = (int) $_POST['supplier'];
        $suppRemainingVal = (float) $_POST['suppRemainingVal'];
        $clientid = (int) $_POST['clientid'];
        $sellbillid = (int) $_POST['sellbillid'];
        $realestateid = (int) $_POST['realestateid'];
        $realestateunitid = (int) $_POST['realestateunitid'];
        $taxExist = (int) $_POST['taxExist'];
        $tax = (float) $_POST['tax'];
        $taxVal = (float) $_POST['taxVal'];

        $tagids = filter_input(INPUT_POST, 'tagids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        $chasis = filter_input(INPUT_POST, 'chasis');
        $expensevalueAfterTax = $expensevalue + $taxVal;

        $saveValuebeforeValid = "1";
        $oldData = $ExpenseData = $ExpenseDAO->load($expenseid);
        $dailyentryid = $oldData->dailyentryid;
        $paymethodOld = 0;
        if ($oldData->saveid > 0) {
            $paymethodOld = 0;
        } elseif ($oldData->bankid > 0) {
            $paymethodOld = 1;
        }
        if ($paymethod == 0) {
            $bankid = 0;
            $bankaccountid = 0;
            $checkNo = 0;
        } elseif ($paymethod == 1) {
            $saveid = 0;
        }
        $expensevalueOld = $ExpenseData->expensesValue;
        $expensevalueOldAfterTax = $expensevalueOld + $ExpenseData->taxVal;


        //check conditions value in expenses tbl equal tempdele value of post variable
        //or change to change save value
        if (count($ExpenseData) > 0) {
            $tempdele = $ExpenseData->conditions;


            //            if ($expensevalueOld != $expensevalue || $paymethodOld != $paymethod || $expensevalueOld != $expensevalue) {
            ################################################################
            //revers old effect
            $CostcenterdetailEX->updatedellbytypeandmodelid('6', $expenseid, 1);

            #### affect supplier Debt
            affectSupplierWithExpense($ExpenseData->supplier, $expensevalueOldAfterTax, $ExpenseData->suppRemainingVal, $expenseid, $ExpenseData->expensesdetails, 'del');

            $saveValuebeforeValid = "2";
            if ($paymethodOld == 0 && $expensevalueOld > 0) {
                //get saveVsalue before and saveValue after adding expensesValue
                if ($userData->searchinonesave == 0) {
                    $valueData = getSaveValueAndPlus($expensevalueOld, $ExpenseData->saveid);
                } else {
                    $valueData = getSaveValueAndPlus($expensevalueOld);
                }

                if (count($valueData) > 0) {
                    $saveId = $valueData[0];
                    $saveValuebefore = $valueData[1];
                    $saveValueafter = $valueData[2];

                    //update save value after expenses
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl
                    insertSavedaily($saveValuebefore, $expensevalueOld, 0, $ExpenseData->saveid, "حذف مصروف", $expenseid, $saveValueafter, "expensesController.php");
                }
            }

            if ($paymethodOld == 1 && $expensevalue > 0) {
                $dataBankAccount = $myBankaccountRecord->load($ExpenseData->bankaccountid);
                //tree account
                $treeIdBankAccount = $dataBankAccount->treeId;

                //decrease account value and write in history
                $accValOld = $dataBankAccount->accountbeginingbalance;
                $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $expensevalueOld;
                $myBankaccountRecord->update($dataBankAccount);
                insertAccountmovement($accValOld, $expensevalueOld, 0, $dataBankAccount->accountbeginingbalance, "حذف مصروف", $expenseid, $dataBankAccount->accountid, $dataBankAccount->bankid, "expensesController.php");
            }


            ################################################################
            //add new effect
            $CostcenterdetailEX->updatedellbytypeandmodelid('6', $expenseid, 0);
            #### affect supplier Debt
            affectSupplierWithExpense($supplier, $expensevalueAfterTax, $suppRemainingVal, $expenseid, $expensecomment, 'add');
            $saveValuebeforeValid = "1";
            //////////////////////////check save value before expenses///////////////////////////
            //check save value
            if ($paymethod == 0 && $expensevalue > 0) {
                //get save value
                if ($userData->searchinonesave == 0) {
                    $saveValueBefore = getSaveValue($saveid);
                } else {
                    $saveValueBefore = getSaveValue();
                }
                $saveValuebeforeValid;
                $saveValueafterValid = $saveValueBefore - $expensevalue;
                if ($saveValueafterValid >= 0) {
                    $saveValuebeforeValid = "1"; //continue
                } else {
                    $saveValuebeforeValid = "0"; //stop and return, show error
                    //return $saveValuebeforeValid;
                }
            }

            ////////////////////////////////////////////////////////////////
            //update save
            if ($paymethod == 0 && $expensevalue > 0) {
                //get saveValue before and saveValue after subtractig expensesValue
                if ($userData->searchinonesave == 0) {
                    $valueData = getSaveValueAndMins($expensevalue, $saveid);
                } else {
                    $valueData = getSaveValueAndMins($expensevalue);
                }
                $saveId = $valueData[0];
                $saveValuebefore = $valueData[1];
                $saveValueafter = $valueData[2];

                //update save value after expenses
                updateSave($saveId, $saveValueafter);

                //insert into savedaily tbl
                insertSavedaily($saveValuebefore, $expensevalue, 1, $saveId, "إضافة مصروف", $expenseid, $saveValueafter, "expensesController.php");
            }

            if ($paymethod == 1 && $expensevalue > 0) {
                $dataBankAccount = $myBankaccountRecord->load($bankaccountid);
                //tree account
                $treeIdBankAccount = $dataBankAccount->treeId;

                //decrease account value and write in history
                $accValOld = $dataBankAccount->accountbeginingbalance;
                $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $expensevalue;
                $myBankaccountRecord->update($dataBankAccount);
                insertAccountmovement($accValOld, $expensevalue, 1, $dataBankAccount->accountbeginingbalance, "اضافة مصروف", $expenseid, $dataBankAccount->accountid, $dataBankAccount->bankid, "expensesController.php");
            }
            //            }


            $x = reverseEntryWithItsID($dailyentryid, 1);

            $dailyEntry->entryComment = 'تم تعديل المصروف';
            $dailyEntry->reverseofid = 0;

            //$dailyEntryDebtor  من نوع المصروف الجديد

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $expensevalue;

            // load expensestypename using expensestypeid

            $expenseTypeData = $ExpensetypeDAO->load($expensetype);


            $treeId = $expenseTypeData->treeId;

            $dailyEntryDebtor->accountstreeid = $treeId;


            //$dailyEntryCreditor الى نوع المصروف القديم

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $expensevalueAfterTax;

            if ($paymethod == 0) {
                //save session
                if ($userData->searchinonesave == 1) {
                    $saveid = $_SESSION['saveid'];
                }

                $dataSave = $SaveDAO->load($saveid);

                $idTreeSave = $dataSave->treeId;
                $dailyEntryCreditor->accountstreeid = $idTreeSave;
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            } elseif ($paymethod == 1) {
                $dataBankAccount = $myBankaccountRecord->load($ExpenseData->bankaccountid);
                //tree account
                $treeIdBankAccount = $dataBankAccount->treeId;
                $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

                //"no need to" decrease account value and write in history => "as value didnot change"
                //                $accValOld = $dataBankAccount->accountbeginingbalance;
                //                $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $oldData->expensesValue - $expensevalue;
                //                $myBankaccountRecord->update($dataBankAccount);
                //                insertAccountmovement($dataBankAccount->accountbeginingbalance, 0, 1, $dataBankAccount->accountbeginingbalance, "تعديل مصروف", $expenseid, $dataBankAccount->accountid, $dataBankAccount->bankid, "expensesController.php");
            }

            //end  save data

            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

            if ($taxExist == 1) {
                $dailyEntryDebtor = new stdClass();
                $vatTreeId = 76; ##ضريبة القيمة المضافة - مدينة
                //$vatTreeId = 106; ##ضريبة القيمة المضافة - دائنة
                $dailyEntryDebtor->accountstreeid = $vatTreeId;
                $dailyEntryDebtor->value = $taxVal;
                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            }
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $expenseId, "expensesController.php?do=show&id=$expenseId");

            $did = $returnedData[1];


            //update expenses table
            $Expense->expensesid = $expenseid;
            $Expense->expensesname = $expensesname;
            $Expense->expensesValue = $expensevalue;
            $Expense->conditions = $conditions;
            $Expense->expensestypeid = $expensetype;
            $Expense->expensesdate = $today;
            $Expense->userid = $_SESSION["userid"];
            $Expense->expensesdetails = $expensecomment;
            $Expense->saveid = $saveid;
            $Expense->dailyentryid = $did;
            $Expense->bankid = $bankid;
            $Expense->bankaccountid = $bankaccountid;
            $Expense->checknum = $checkNo;
            $Expense->expensesdate = $ExpenseData->expensesdate;
            $Expense->productid = $productid;
            $Expense->expensenumbrt = $expensenumbrt;
            $Expense->expenseprice = $expenseprice;
            $Expense->expensetotaln = $expenseprice * $expensenumbrt;
            $Expense->expenseshortfalls = $expenseshortfalls;
            $Expense->supplier = $supplier;
            $Expense->clientid = $clientid;
            $Expense->sellbillid = $sellbillid;
            $Expense->realestateid = $realestateid;
            $Expense->realestateunitid = $realestateunitid;
            $Expense->suppRemainingVal = $suppRemainingVal;
            $Expense->taxPer = $tax;
            $Expense->taxVal = $taxVal;
            $Expense->chasis = $chasis;


            $handle = new upload($_FILES['file']);
            $file = updateImagesWithoutresiz($handle, "oldfile", '../upload/expenseFile');
            $Expense->file = $file;

            if (isset($tagids)) {
                if (in_array("0", $tagids)) {
                    $Expense->tagids = '0';
                } else {
                    $Expense->tagids = implode(",", $tagids);
                }
            }

            $ExpenseDAO->update($Expense);
        }



        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }




    return $saveValuebeforeValid;
}

// get savecurrentvalue from save tbl
function getSaveValue($saveid = 0) {
    global $Save;
    global $SaveDAO;
    if ($saveid > 0) {
        $saveData = $SaveDAO->load($saveid);
    } else {
        $saveData = $SaveDAO->load($_SESSION['saveid']);
    }
    $saveValuebefore = $saveData->savecurrentvalue;
    return $saveValuebefore;
}

// get savecurrentvalue and plus from save tbl
function getSaveValueAndPlus($savevaluechanged, $saveid = 0) {
    global $Save;
    global $SaveDAO;
    if ($saveid > 0) {
        $saveData = $SaveDAO->load($saveid);
    } else {
        $saveData = $SaveDAO->load($_SESSION['saveid']);
    }
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// get savecurrentvalue and mins from save tbl
function getSaveValueAndMins($savevaluechanged, $saveid = 0) {
    global $Save;
    global $SaveDAO;
    if ($saveid > 0) {
        $saveData = $SaveDAO->load($saveid);
    } else {
        $saveData = $SaveDAO->load($_SESSION['saveid']);
    }
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// update Save tbl
function updateSave($saveid, $savevalueafter) {
    global $Save;
    global $SaveExt;

    //update savecurrentvalue in Save tbl
    $Save->savecurrentvalue = $savevalueafter;
    $Save->userid = $_SESSION['userid'];
    $Save->saveid = $saveid;

    $SaveExt->updateSaveValue($Save);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {

    //to use the variable out side the funcion
    global $Savedaily;
    global $SavedailyDAO;

    //insert in Savedaily tbl
    $Savedaily->savedailydate = date("Y-m-d H:i:s");
    $Savedaily->userid = $_SESSION['userid'];
    $Savedaily->savedailysavebefore = $savedailysavebefore;
    $Savedaily->savedailychangeamount = $savedailychangeamount;
    $Savedaily->savedailychangetype = $savedailychangetype;
    $Savedaily->saveid = $saveid;
    $Savedaily->processname = $processname;
    $Savedaily->savedailymodelid = $savedailymodelid;
    $Savedaily->savedailysaveafter = $savedailysaveafter;
    $Savedaily->tablename = $tablename;

    $SavedailyDAO->insert($Savedaily);
}

// insertAccountmovement of bank
function insertAccountmovement($accountbefore, $accountamount, $accountmovementtype, $accountafter, $processname, $accountmovementmodelid, $accountid, $bankid, $tablename) {

    //to use the variable out side the funcion
    global $myAccountmovement;
    global $myAccountmovementRecord;


    //insert in Accountmovement tbl
    $myAccountmovement->accountid = $accountid;
    $myAccountmovement->accountmovementafter = $accountafter;
    $myAccountmovement->accountmovementamount = $accountamount;
    $myAccountmovement->accountmovementbefore = $accountbefore;
    $myAccountmovement->accountmovementdate = date("Y-m-d H:i:s");
    $myAccountmovement->accountmovementmodelid = $accountmovementmodelid;
    $myAccountmovement->accountmovementtype = $accountmovementtype;
    $myAccountmovement->bankid = $bankid;
    $myAccountmovement->processname = $processname;
    $myAccountmovement->tablename = $tablename;
    $myAccountmovement->userid = $_SESSION['userid'];

    $myAccountmovementRecord->insert($myAccountmovement);
}

function affectSupplierWithExpense($supplier, $expensevalue, $suppRemainingVal, $expenseId, $expensecomment, $operation) {
    global $today;
    global $supplierDAO;

    if ($expensevalue > 0 && $supplier > 0 && $suppRemainingVal > 0) {
        //update supplierdebt
        $supdata = $supplierDAO->load($supplier);
        $deptBefore = $supdata->suppliercurrentDebt;
        if ($operation == 'add') {
            $changeType = 0;
            $processName = 'اضافه مصروف على مورد ' . $expensecomment;
            $deptAfter = $deptBefore + $suppRemainingVal;
        } elseif ($operation == 'del') {
            $changeType = 1;
            $processName = 'حذف مصروف على مورد';
            $deptAfter = $deptBefore - $suppRemainingVal;
        }

        updateSupplierDebt($supplier, $deptAfter, $today);
        insertSupplierDebtChangeupdate($supplier, $deptBefore, $suppRemainingVal, $changeType, $processName, $expenseId, $deptAfter, "expensesController.php", $expensecomment, $today);
    }
}

function updateSupplierDebt($supplierId, $supplierDebtAfter) {
    global $supplier;
    global $supplierExt;
    global $today;

    //update clientdebt in client tbl
    $supplier->userid = $_SESSION['userid'];
    $supplier->suppliercurrentDebt = $supplierDebtAfter;
    $supplier->supplierid = $supplierId;
    $supplier->supplierdate = $today;

    $supplierExt->updatedept($supplier);
}

function insertSupplierDebtChangeupdate($supplierId, $supplierDebtChangeBefore, $supplierDebtChangeAmount, $supplierDebtChangeType, $processname, $supplierDebtChangeModelId, $supplierDebtChangeAfter, $tablename, $comment, $mydate) {
    global $supplierDebtChange;
    global $supplierDebtChangeDAO;
    global $today;

    $supplierDebtChange->comment = $comment;
    $supplierDebtChange->processname = $processname;
    $supplierDebtChange->supplierdebtchangeafter = $supplierDebtChangeAfter;
    $supplierDebtChange->supplierdebtchangeamount = $supplierDebtChangeAmount;
    $supplierDebtChange->supplierdebtchangebefore = $supplierDebtChangeBefore;
    $supplierDebtChange->supplierdebtchangedate = $mydate; //$today;
    $supplierDebtChange->supplierdebtchangemodelid = $supplierDebtChangeModelId;
    $supplierDebtChange->supplierdebtchangetype = $supplierDebtChangeType;
    $supplierDebtChange->supplierid = $supplierId;
    $supplierDebtChange->tablename = $tablename;
    $supplierDebtChange->userid = $_SESSION['userid'];
    $supplierDebtChange->dailyentryid = 0;
    $supplierDebtChangeDAO->insert($supplierDebtChange);
}

// $parent is the parent of the children we want to see
// $level is increased when we go deeper into the tree,
// used to display a nice indented tree
function display_children($parent, $level) {
    global $ExpensetypeExt;
    //global $outputString;
    global $outputString;
    // retrieve all children of $parent
    $result = $ExpensetypeExt->queryByParentExt($parent);

    if (count($result) > 0) {
        // display each child
        foreach ($result as $type) {
            //check for expenses for this category
            $expensesData = getExpensesByType($type->expensestypeid);

            $outputString .= '<li><a href="#" class="tree-toggle" data-toggle="branch" data-value="' . $type->expensestypeid . '">
                            ' . $type->expensestypename . ' </a>';

            $outputString .= '<ul class="branch in">';

            if (count($expensesData) > 0) {
                foreach ($expensesData as $expenses) {
                    $outputString .= '<li><a href="#" data-role="leaf"  data-value="' . $expenses->expensesid . '" > ' . $expenses->expensesname . '</a></li>';
                }
            }

            // call this function again to display this
            // child's children
            display_children($type->expensestypeid, $level + 1);

            $outputString .= '</li>';
            $outputString .= '</ul>';
        }
    }
    return $outputString;
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
    //    $post = [
    //        'data_arr' => json_encode($data_arr), //encode it as it is array
    //    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}
