<?php

######affect programs plugins
//Accountstree
require_once('../models/dao/AccountstreeDAO.class.php');
require_once('../models/dto/Accountstree.class.php');
require_once('../models/mysql/AccountstreeMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountstreeMySqlExtDAO.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');

//Bank
require_once('../models/dao/BankDAO.class.php');
require_once('../models/dto/Bank.class.php');
require_once('../models/mysql/BankMySqlDAO.class.php');
require_once('../models/mysql/ext/BankMySqlExtDAO.class.php');
//Bankaccount
require_once('../models/dao/BankaccountDAO.class.php');
require_once('../models/dto/Bankaccount.class.php');
require_once('../models/mysql/BankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/BankaccountMySqlExtDAO.class.php');
//Accountmovement
require_once('../models/dao/AccountmovementDAO.class.php');
require_once('../models/dto/Accountmovement.class.php');
require_once('../models/mysql/AccountmovementMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountmovementMySqlExtDAO.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');
//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');


//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');

//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');

//Onlinestoresetting
require_once('../models/dao/OnlinestoresettingDAO.class.php');
require_once('../models/dto/Onlinestoresetting.class.php');
require_once('../models/mysql/OnlinestoresettingMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinestoresettingMySqlExtDAO.class.php');
//Onlinetempcategory
require_once('../models/dao/OnlinetempcategoryDAO.class.php');
require_once('../models/dto/Onlinetempcategory.class.php');
require_once('../models/mysql/OnlinetempcategoryMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempcategoryMySqlExtDAO.class.php');
//Onlinetemporder
require_once('../models/dao/OnlinetemporderDAO.class.php');
require_once('../models/dto/Onlinetemporder.class.php');
require_once('../models/mysql/OnlinetemporderMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderMySqlExtDAO.class.php');
//Onlinetemporderproduct
require_once('../models/dao/OnlinetemporderproductDAO.class.php');
require_once('../models/dto/Onlinetemporderproduct.class.php');
require_once('../models/mysql/OnlinetemporderproductMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderproductMySqlExtDAO.class.php');
//Onlinetempproduct
require_once('../models/dao/OnlinetempproductDAO.class.php');
require_once('../models/dto/Onlinetempproduct.class.php');
require_once('../models/mysql/OnlinetempproductMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempproductMySqlExtDAO.class.php');
//Onlinetempstoredetail
require_once('../models/dao/OnlinetempstoredetailDAO.class.php');
require_once('../models/dto/Onlinetempstoredetail.class.php');
require_once('../models/mysql/OnlinetempstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempstoredetailMySqlExtDAO.class.php');
//Onlinetempstorereport
require_once('../models/dao/OnlinetempstorereportDAO.class.php');
require_once('../models/dto/Onlinetempstorereport.class.php');
require_once('../models/mysql/OnlinetempstorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempstorereportMySqlExtDAO.class.php');
//Income
require_once('../models/dao/IncomeDAO.class.php');
require_once('../models/dto/Income.class.php');
require_once('../models/mysql/IncomeMySqlDAO.class.php');
require_once('../models/mysql/ext/IncomeMySqlExtDAO.class.php');
//Partner
require_once('../models/dao/PartnerDAO.class.php');
require_once('../models/dto/Partner.class.php');
require_once('../models/mysql/PartnerMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnerMySqlExtDAO.class.php');
//Partnertransferbetween
require_once('../models/dao/PartnertransferbetweenDAO.class.php');
require_once('../models/dto/Partnertransferbetween.class.php');
require_once('../models/mysql/PartnertransferbetweenMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnertransferbetweenMySqlExtDAO.class.php');
//Partnerwithdrawal
require_once('../models/dao/PartnerwithdrawalDAO.class.php');
require_once('../models/dto/Partnerwithdrawal.class.php');
require_once('../models/mysql/PartnerwithdrawalMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnerwithdrawalMySqlExtDAO.class.php');
//Transfermoney
require_once('../models/dao/TransfermoneyDAO.class.php');
require_once('../models/dto/Transfermoney.class.php');
require_once('../models/mysql/TransfermoneyMySqlDAO.class.php');
require_once('../models/mysql/ext/TransfermoneyMySqlExtDAO.class.php');
//Impotencetreatmentsuppliersave
require_once('../models/dao/ImpotencetreatmentsuppliersaveDAO.class.php');
require_once('../models/dto/Impotencetreatmentsuppliersave.class.php');
require_once('../models/mysql/ImpotencetreatmentsuppliersaveMySqlDAO.class.php');
require_once('../models/mysql/ext/ImpotencetreatmentsuppliersaveMySqlExtDAO.class.php');
//Transferbtweenbankaccount
require_once('../models/dao/TransferbtweenbankaccountDAO.class.php');
require_once('../models/dto/Transferbtweenbankaccount.class.php');
require_once('../models/mysql/TransferbtweenbankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/TransferbtweenbankaccountMySqlExtDAO.class.php');
//Cashtransfer
require_once('../models/dao/CashtransferDAO.class.php');
require_once('../models/dto/Cashtransfer.class.php');
require_once('../models/mysql/CashtransferMySqlDAO.class.php');
require_once('../models/mysql/ext/CashtransferMySqlExtDAO.class.php');
/* ======================
  Controller Name :- accountstree
  ======================== */

//here goes the instances and general variables
#######################################################
//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();
//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Savedaily
$saveDaily = new Savedaily();
$saveDailyDAO = new SavedailyMySqlDAO();
$saveDailyExt = new SavedailyMySqlExtDAO();

//bank
$bank = new Bank();
$bankDAO = new BankMySqlDAO();
//Bankaccount
$bankAccount = new Bankaccount();
$bankAccountDAO = new BankaccountMySqlDAO();
$bankAccountEx = new BankaccountMySqlExtDAO();
######################from nora
//Bank
$myBank = new Bank();
$myBankRecord = new BankMySqlDAO();
$myBankEx = new BankMySqlExtDAO();

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

//Accountmovement
$myAccountmovement = new Accountmovement();
$myAccountmovementRecord = new AccountmovementMySqlDAO();
############################################################
//Client
$clientDAO = new ClientMySqlDAO();
$myClientRecord = new ClientMySqlDAO();
$myClient = new Client();
$myClientEx = new ClientMySqlExtDAO();
//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();

//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$Supplierdebtchange = new Supplierdebtchange();
$supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDebtChangeEX = new SupplierdebtchangeMySqlExtDAO();

//Expensetype
$ExpensetypeDAO = new ExpensestypeMySqlDAO();
$Expensetype = new Expensestype();
$ExpensetypeEX = new ExpensestypeMySqlExtDAO();
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
$Expense = new Expense();
$ExpenseEX = new ExpensesMySqlExtDAO();

//Onlinestoresetting
$onlineStoreSetting = new Onlinestoresetting();
$onlineStoreSettingDAO = new OnlinestoresettingMySqlDAO();
$onlineStoreSettingEX = new OnlinestoresettingMySqlExtDAO();
//Onlinetempcategory
$onlineTempCategory = new Onlinetempcategory();
$onlineTempCategoryDAO = new OnlinetempcategoryMySqlDAO();
$onlineTempCategoryEX = new OnlinetempcategoryMySqlExtDAO();
//Onlinetemporder
$onlineTempOrder = new Onlinetemporder();
$onlineTempOrderDAO = new OnlinetemporderMySqlDAO();
$onlineTempOrderEX = new OnlinetemporderMySqlExtDAO();
//Onlinetemporderproduct
$onlineTempOrderProduct = new Onlinetemporderproduct();
$onlineTempOrderProductDAO = new OnlinetemporderproductMySqlDAO();
$onlineTempOrderProductEX = new OnlinetemporderproductMySqlExtDAO();
//Onlinetempproduct
$onlineTempProduct = new Onlinetempproduct();
$onlineTempProductDAO = new OnlinetempproductMySqlDAO();
$onlineTempProductEX = new OnlinetempproductMySqlExtDAO();
//Onlinetempstoredetail
$onlineTempStoreDetail = new Onlinetempstoredetail();
$onlineTempStoreDetailDAO = new OnlinetempstoredetailMySqlDAO();
$onlineTempStoreDetailEX = new OnlinetempstoredetailMySqlExtDAO();

//Onlinetempstorereport
$onlineTempStoreReport = new Onlinetempstorereport();
$onlineTempStoreReportDAO = new OnlinetempstorereportMySqlDAO();
$onlineTempStoreReportEX = new OnlinetempstorereportMySqlExtDAO();
//
$incomeDAO = new IncomeMySqlDAO();
//Partner
$myPartner = new Partner();
$myPartnerRecord = new PartnerMySqlDAO();
$myPartnerEx = new PartnerMySqlExtDAO();
//Partnerwithdrawal
$myPartnertransferbetween = new Partnertransferbetween();
$myPartnertransferbetweenRecord = new PartnertransferbetweenMySqlDAO();
$myPartnertransferbetweenEx = new PartnertransferbetweenMySqlExtDAO();
//Partnerwithdrawal
$myPartnerwithdrawal = new Partnerwithdrawal();
$myPartnerwithdrawalRecord = new PartnerwithdrawalMySqlDAO();
$myPartnerwithdrawalEx = new PartnerwithdrawalMySqlExtDAO();
//Transfermoney
$myTransfermoney = new Transfermoney();
$myTransfermoneyRecord = new TransfermoneyMySqlDAO();
$myTransfermoneyEx = new TransfermoneyMySqlExtDAO();
//Impotencetreatmentsuppliersave
$myImpotencetreatmentsuppliersave = new Impotencetreatmentsuppliersave();
$myImpotencetreatmentsuppliersaveRecord = new ImpotencetreatmentsuppliersaveMySqlDAO();
$myImpotencetreatmentsuppliersaveEx = new ImpotencetreatmentsuppliersaveMySqlExtDAO();
//Transferbtweenbankaccount
$transferBtweenBankAccounts = new Transferbtweenbankaccount();
$transferBtweenBankAccountsDAO = new TransferbtweenbankaccountMySqlDAO();
$transferBtweenBankAccountsEX = new TransferbtweenbankaccountMySqlExtDAO();
//Cashtransfer
$cashTransfer = new Cashtransfer();
$cashTransferDAO = new CashtransferMySqlDAO();
$cashTransferExt = new CashtransferMySqlExtDAO();


$pluginMapArr = array('save' => 40, 'bank' => 38, '3ohad' => 408, 'client' => 57, 'supplier' => 80, 'expenses' => 411/* 96 */, 'income' => 151, 'asset' => 2, 'capital' => 50, 'solaf' => 387,
    'ogoor mwazfeen' => 415, 'ogoor doctors' => 416
    , 'wagesAndSalaries-m-3' => 417/* اجور ومرتبات-م-ع */,
    'partner' => 128,
    'SaveDeficitAndIncreaseAccount' => 41, 'bankExpensesAccount' => 65, 'bankIncomeAccount' => 393);

//$whichSideisIt  0 debtor , 1 creditor
function affectPlugin($whatIsIt, $val, $id, $operation, $elementName, $comment, $controllerName, $costCenterID, $accountstreeid, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor) {
    global $saveDAO;
    global $bankAccountDAO;
    global $myBankEx;
    global $clientDAO;
    global $supplierDAO;
    global $ExpensetypeDAO;
    //echo $whatIsIt;
    switch ($whatIsIt) {
        case 'save'://save
        case '3ohad'://3ohad
            //affectOtherSaveControllers must be first as i get save value before inside
            affectOtherSaveControllers($val, $comment, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);


            $save = $saveDAO->queryBySavename($elementName);
            $saveid = $save[0]->saveid;
            if ($operation == 'increase') {
                //get saveValue before and saveValue after plus expensesValue
                $valueData = getSaveValueAndPlus_f($saveid, $val); //$_SESSION['saveid']
                $saveId = $valueData[0];
                $saveValuebefore = $valueData[1];
                $saveValueafter = $valueData[2];

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

                //insert into savedaily tbl
                insertSavedaily_f($saveValuebefore, $val, 0, $saveId, $comment, $id, $saveValueafter, $controllerName);
            } elseif ($operation == 'decrease') {
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                //get saveValue before and saveValue after plus totalPayed
                $saveData = getSaveValueAndMins_f($saveid, $val); //$_SESSION['saveid']
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

                //update saveFrom value after add transfer
                updateSave_f($saveId, $saveValueafter);

                //insert into savedaily tbl from savefrom
                insertSavedaily_f($saveValuebefore, $val, 1, $saveId, $comment, $id, $saveValueafter, $controllerName);
            }

            break;
        case 'bank'://bank
            //affectOtherSaveControllers must be first as i get save value before inside
            affectOtherBankControllers($val, $comment, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);


            $elementName = explode('/', $elementName);
            $bankAccountx = $bankAccountDAO->queryByAccountname(rtrim($elementName[0], ' '));

            $accountid = $bankAccountx[0]->accountid;
            $bankid = $bankAccountx[0]->bankid;
            if ($operation == 'increase') {
                $data = getAccountBalanceAndPlus_f($accountid, $val);
                $balanceBefore = $data[0];
                $balanceAfter = $data[1];

                //update saveFrom value after add transfer
                updateBankAccount_f($accountid, $balanceAfter);

                //insert into savedaily tbl from savefrom
                //insert in accountmovement tbl
                insertAccountmovement_f($balanceBefore, $val, 0, $balanceAfter, $comment, $id, $accountid, $bankid, $controllerName, $whichSideisIt, $AllDailyEntryCreditor, $AllDailyEntryDebtor);
            } elseif ($operation == 'decrease') {
                $data = getAccountBalanceAndMins_f($accountid, $val);
                $balanceBefore = $data[0];
                $balanceAfter = $data[1];

                //update saveFrom value after add transfer
                updateBankAccount_f($accountid, $balanceAfter);

                //insert into savedaily tbl from savefrom
                //insert in accountmovement tbl
                insertAccountmovement_f($balanceBefore, $val, 1, $balanceAfter, $comment, $id, $accountid, $bankid, $controllerName, $whichSideisIt, $AllDailyEntryCreditor, $AllDailyEntryDebtor);
            }


            break;
        case 'client'://client
            $client = $clientDAO->queryByClientname($elementName);
            if (count($client) > 0) {
                $clientid = $client[0]->clientid;
                $deptBefor = $client[0]->clientdebt;
                $debtAfter;
                if ($operation == 'increase') {
                    $debtAfter = $deptBefor + $val;
                } elseif ($operation == 'decrease') {
                    $debtAfter = $deptBefor - $val;
                }

                updateClientDebt_f($clientid, $debtAfter);
                if ($operation == 'increase') {
                    insertClientdebtchange_f($clientid, $deptBefor, $val, 0, $comment, $id, $debtAfter, $controllerName, $comment, $val);
                } elseif ($operation == 'decrease') {
                    insertClientdebtchange_f($clientid, $deptBefor, $val, 1, $comment, $id, $debtAfter, $controllerName, $comment, $val);
                }
            }


            break;
        case 'supplier'://spplier
            $supplier = $supplierDAO->queryBySuppliername($elementName);
            if (count($supplier) > 0) {
                $supplierid = $supplier[0]->supplierid;
                $deptBefor = $supplier[0]->suppliercurrentDebt;
                if ($operation == 'increase') {
                    $debtAfter = $deptBefor + $val;
                    insertSupplierDebtChange_f($supplierid, $deptBefor, $val, 0, $comment, $id, $debtAfter, $controllerName, $comment);
                } elseif ($operation == 'decrease') {
                    $debtAfter = $deptBefor - $val;
                    insertSupplierDebtChange_f($supplierid, $deptBefor, $val, 1, $comment, $id, $debtAfter, $controllerName, $comment);
                }
                updateSupplierDebt_f($supplierid, $debtAfter);
            }

            break;
        case 'expenses'://expenses//مصروفات
            //$myexpenseType = $ExpensetypeDAO->queryByExpensestypename($elementName);
            $myexpenseType = R::findOne('expensestype', ' treeId=' . $accountstreeid);
            if (isset($myexpenseType->expensestypeid) && $myexpenseType->expensestypeid > 0) {
                insertEXpenseDaily_f($myexpenseType->expensestypename, $val, $myexpenseType->expensestypeid, $comment, $costCenterID, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
            }


            break;
        case 'income'://income//ايرادات
            $incomeTypeId = R::getCell('select incomeTypeId from incometype where treeId=' . $accountstreeid);
            insertIncomeDaily_f($elementName, $val, $incomeTypeId, $comment, $costCenterID, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
            break;
        case 'asset'://asset    osool//اصول
            $assetId = R::getCell('select assetId from assets where treeId=' . $accountstreeid);
            if (isset($assetId) && $assetId > 0) {
                if ($operation == 'increase') {
                    $myBankEx->queryStringUpdate('UPDATE assets SET assetsValue = assetsValue+' . $val);
                } elseif ($operation == 'decrease') {
                    $myBankEx->queryStringUpdate('UPDATE assets SET assetsValue = assetsValue- ' . $val);
                }
            }

            break;
        case 'capital'://ras elmal    راس المال
            if ($operation == 'increase') {
                $myBankEx->queryStringUpdate('UPDATE capital SET capitalamount = capitalamount+' . $val);
            } elseif ($operation == 'decrease') {
                $myBankEx->queryStringUpdate('UPDATE capital SET capitalamount = capitalamount-' . $val);
            }
            break;
        case 'partner'://partner  الشركاء
            affectPartner($val, $comment, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);

            break;
        default:
            break;
    }
}

function whatIsIt($elementId) {
    global $kind;
    global $pluginMapArr;

    //make sure it is empty every time to check so it doesnot hold history
    $kind = '';
    if (isset($elementId)) {
        #check for element id itself
        $key = array_search($elementId, $pluginMapArr);
        if ($key !== false) {//found
            $kind = $key;
        } else {//not found #check for father
            isChildTo($elementId);
        }

        return $kind;
    }
}

function isChildTo($elementId) {
    global $pluginMapArr;
    global $kind;
    global $accountsTreeEX;


    // $account = R::getrow('SELECT accountstree.id,parent
	// 	FROM accountstree
	// 	WHERE id = ' . $elementId . ' AND accountstree.del=0');
    $account = $accountsTreeEX->getNonDeletedAccData($elementId);
    $key = array_search($account->parent, $pluginMapArr);
    if ($key !== false) {//found
        $kind = $key;
        return;
    } else {//not found
        if (isset($account->parent) && $account->parent > 0) {
            isChildTo($account->parent);
        }
    }
}

function isChildToold($elementId, $parent) {
    global $isChildToFlag;
    global $accountsTreeDAO;
    global $accountsTreeEX;
    $result = $accountsTreeEX->queryByParentExt($parent);
    if (count($result) > 0) {
        foreach ($result as $type) {
            if ($type->id == $elementId) {
                $isChildToFlag = 1;
            } else {
                //check for expenses for this category
                $childData = $accountsTreeDAO->queryByParent($type->id);
                if (count($childData) > 0) {
                    isChildTo($elementId, $type->id);
                }
            }
        }
    }
    return $isChildToFlag;
}

############################################################################
##save functions
// get initialvalue and plus from save tbl

function getSaveValueAndPlus_f($saveid, $savevaluechanged) {
    global $save;
    global $saveDAO;

    $saveData = $saveDAO->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

// get initialvalue and mins from save tbl
function getSaveValueAndMins_f($saveid, $savevaluechanged) {
    global $save;
    global $saveDAO;

    $saveData = $saveDAO->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

// update in Save tbl
function updateSave_f($saveid, $savevalueafter) {
    global $save;
    global $saveExt;

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

    $saveExt->updateSaveValue($save);
}

// insert in Savedaily tbl
function insertSavedaily_f($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {
    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;
    if (isset($_SESSION['client_id']) && !empty($_SESSION['client_id'])) {
        $saveDaily->clientid = $_SESSION['client_id'];
    } else {
        $saveDaily->clientid = 0;
    }
    $saveDailyDAO->insert($saveDaily);
}

#############################################################################
##bank functions
// get accountbeginingbalance from  bankaccount tbl

function getAccountBalanceBefore_f($accountid) {

    //to use the variable out side the funcion
    global $myBankaccountRecord;

    $bankaccountData = $myBankaccountRecord->load($accountid);
    $accountBalance = $bankaccountData->accountbeginingbalance;

    return $accountBalance;
}

// get accountbeginingbalance and plus from Bankaccount tbl
function getAccountBalanceAndPlus_f($accountid, $accountmovementamount) {

    //to use the variable out side the funcion
    global $myBankaccount;
    global $myBankaccountRecord;

    $bankaccountData = $myBankaccountRecord->load($accountid);
    $accountBalanceBefore = $bankaccountData->accountbeginingbalance;

    $accountBalanceAfter = $accountBalanceBefore + $accountmovementamount;

    return array($accountBalanceBefore, $accountBalanceAfter);
}

// get accountbeginingbalance and minus from Bankaccount tbl
function getAccountBalanceAndMins_f($accountid, $accountmovementamount) {

    //to use the variable out side the funcion
    global $myBankaccount;
    global $myBankaccountRecord;

    $bankaccountData = $myBankaccountRecord->load($accountid);
    $accountBalanceBefore = $bankaccountData->accountbeginingbalance;

    $accountBalanceAfter = $accountBalanceBefore - $accountmovementamount;

    return array($accountBalanceBefore, $accountBalanceAfter);
}

// update in BankAccount tbl
function updateBankAccount_f($accountid, $accountBalanceAfter) {

    //to use the variable out side the funcion
    global $myBankaccount;
    global $myBankaccountEx;

    //update accountbeginingbalance in BankAccount tbl
    $myBankaccount->accountbeginingbalance = $accountBalanceAfter;
    $myBankaccount->userid = $_SESSION['userid'];
    $myBankaccount->accountid = $accountid;

    $myBankaccountEx->updateAccountbeginingbalance($myBankaccount);
}

// insert in Savedaily tbl
function insertAccountmovement_f($accountbefore, $accountamount, $accountmovementtype, $accountafter, $processname, $accountmovementmodelid, $accountid, $bankid, $tablename, $whichSideisIt, $AllDailyEntryCreditor, $AllDailyEntryDebtor) {

    if ($whichSideisIt == 0) {//it is debtor ,the side maybe client is at credit side
        $treeId = (int) $AllDailyEntryCreditor[0]->accountstreeid;
    } else if ($whichSideisIt == 1) {//it is creditor ,the side maybe client is at debtor side
        $treeId = (int) $AllDailyEntryDebtor[0]->accountstreeid;
    }
    $clientid = (int) R::getCell('select clientid from client where treeId=' . $treeId);


    //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->clientid = $clientid;
    $myAccountmovement->userid = $_SESSION['userid'];

    $myAccountmovementRecord->insert($myAccountmovement);
}

##############################################################################
##clients

function updateClientDebt_f($clientid, $clientdebtAfter) {

    //to use the variable out side the funcion
    global $myClient;
    global $myClientEx;

    //update clientdebt in client tbl
    $myClient->userid = $_SESSION['userid'];
    $myClient->clientdebt = $clientdebtAfter;
    $myClient->clientid = $clientid;
    $myClientEx->updateClientdebt($myClient);
}

// insert data into Clientdebtchange tbl
function insertClientdebtchange_f($clientid, $clientdebtchangebefore, $clientdebtchangeamount, $clientdebtchangetype, $processname, $clientdebtchangemodelid, $clientdebtchangeafter, $tablename, $comment, $totalOperationCost) {

    //to use the variable out side the funcion
    global $myClientdebtchange;
    global $myClientdebtchangeRecord;

    $myClientdebtchange->clientdebtchangeafter = $clientdebtchangeafter;
    $myClientdebtchange->clientdebtchangeamount = $clientdebtchangeamount;
    $myClientdebtchange->clientdebtchangebefore = $clientdebtchangebefore;
    $myClientdebtchange->clientdebtchangedate = date("Y-m-d h:m:s");
    $myClientdebtchange->clientdebtchangemodelid = $clientdebtchangemodelid;
    $myClientdebtchange->clientdebtchangetype = $clientdebtchangetype;
    $myClientdebtchange->clientid = $clientid;
    $myClientdebtchange->comment = $comment;
    $myClientdebtchange->processname = $processname;
    $myClientdebtchange->tablename = $tablename;
    $myClientdebtchange->userid = $_SESSION['userid'];
    $myClientdebtchange->totalOperationCost = $totalOperationCost;
    $myClientdebtchange->dailyentryid = 0;

    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

##############################################################################
##supplier

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

//update clientdebt in client tbl
    $supplier->userid = $_SESSION['userid'];
    $supplier->suppliercurrentDebt = $supplierDebtAfter;
    $supplier->supplierid = $supplierId;
    $supplier->supplierdate = date("Y-m-d");

    $supplierExt->updatedept($supplier);
}

// insert data into Clientdebtchange tbl

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

    $supplierDebtChange->comment = $comment;
    $supplierDebtChange->processname = $processname;
    $supplierDebtChange->supplierdebtchangeafter = $supplierDebtChangeAfter;
    $supplierDebtChange->supplierdebtchangeamount = $supplierDebtChangeAmount;
    $supplierDebtChange->supplierdebtchangebefore = $supplierDebtChangeBefore;
    $supplierDebtChange->supplierdebtchangedate = date("Y-m-d");
    $supplierDebtChange->supplierdebtchangemodelid = $supplierDebtChangeModelId;
    $supplierDebtChange->supplierdebtchangetype = $supplierDebtChangeType;
    $supplierDebtChange->supplierid = $supplierId;
    $supplierDebtChange->tablename = $tablename;
    $supplierDebtChange->userid = $_SESSION['userid'];
    $supplierDebtChange->dailyentryid = $supplierDebtChangeModelId;

    $supplierDebtChangeDAO->insert($supplierDebtChange);
}

##############################################################################
##expenses

function insertEXpenseDaily_f($expensesname, $expensevalue, $expensetype, $expensecomment, $Costcenterid, $dailyentryid, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor) {
    global $ExpenseDAO;
    global $bankAccountDAO;
    //add in expenses tbl
    $Expense->expensesname = $expensesname . R::getCell('SELECT `AUTO_INCREMENT` FROM  INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = "' . $_SESSION['dbname'] . '"   AND   TABLE_NAME   = "expenses" ');
    $Expense->expensesValue = $expensevalue;
    $Expense->conditions = 0;
    $Expense->expensestypeid = $expensetype;
    $Expense->expensesdate = date("Y-m-d");
    $Expense->userid = $_SESSION["userid"];
    $Expense->expensesdetails = $expensecomment;
    $Expense->costcenterid = $Costcenterid;
    $Expense->dailyentryid = $dailyentryid;
    //get save,bank
    $saveid = 0;
    $bankid = 0;
    $bankaccountid = 0;

    # as transaction isnot finished ,cant load data now
    if ($whichSideisIt == 0) {//it is debtor ,the side of expense.save or bank is at credit side
        $treeId = (int) $AllDailyEntryCreditor[0]->accountstreeid;
    } else if ($whichSideisIt == 1) {//it is creditor ,the side of expense.save or bank is at debtor side
        $treeId = (int) $AllDailyEntryDebtor[0]->accountstreeid;
    }

    $saveid = (int) R::getCell('select saveid from save where treeId=' . $treeId);
    if ($saveid < 1) {
        $elementName = R::getCell('select customName from accountstree where id=' . $treeId);
        $elementName = explode('/', $elementName);
        $bankAccountx = $bankAccountDAO->queryByAccountname(rtrim($elementName[0], ' '));

        $bankaccountid = $bankAccountx[0]->accountid;
        $bankid = $bankAccountx[0]->bankid;
    }
    $Expense->saveid = $saveid;
    $Expense->bankid = $bankid;
    $Expense->bankaccountid = $bankaccountid;

    if ($whichSideisIt == 0) {//it is debtor ,add
        $expenseId = $ExpenseDAO->insert($Expense);
    } else if ($whichSideisIt == 1) {//it is creditor ,del
        if ($dailyEntry->reverseofid > 0) {
            $expensesid = R::getCell('select expensesid from expenses where dailyentryid=' . $dailyEntry->reverseofid);
            $ExpenseDAO->delete($expensesid);
        }
    }

    return $expenseId;
}

function insertIncomeDaily_f($incomename, $incomevalue, $incometype, $incomecomment, $Costcenterid, $dailyentryid, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor) {
    global $incomeDAO;

    //add in income tbl
    $income->incomeTypeId = $incometype;
    $income->incomeName = $incomename . R::getCell('SELECT `AUTO_INCREMENT` FROM  INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = "' . $_SESSION['dbname'] . '"   AND   TABLE_NAME   = "income" ');
    $income->incomeValue = $incomevalue;
    $income->conditions = 0;
    $income->incomeDate = date("Y-m-d");
    $income->userid = $_SESSION["userid"];
    $income->incomeDetails = $incomecomment;
    $income->costcenterid = $Costcenterid;
    $income->clientid = -1;
    $income->dailyentryid = $dailyentryid;

    # as transaction isnot finished ,cant load data now
    if ($whichSideisIt == 0) {//it is debtor ,the side of expense.save or bank is at credit side
        $treeId = (int) $AllDailyEntryCreditor[0]->accountstreeid;
    } else if ($whichSideisIt == 1) {//it is creditor ,the side of expense.save or bank is at debtor side
        $treeId = (int) $AllDailyEntryDebtor[0]->accountstreeid;
    }

    $saveid = (int) R::getCell('select saveid from save where treeId=' . $treeId);
    $income->saveid = $saveid;


    if ($whichSideisIt == 0) {//it is debtor ,del
        if ($dailyEntry->reverseofid > 0) {
            $incomeId = R::getCell('select incomeId from income where dailyentryid=' . $dailyEntry->reverseofid);
            $incomeDAO->delete($incomeId);
        }
    } else if ($whichSideisIt == 1) {//it is creditor ,add
        $incomeId = $incomeDAO->insert($income);
    }
    return $incomeId;
}

################################################################################
##online store functions                                                      ##
################################################################################

function onlineTempStoreDetailFunc($storeid, $productid, $sizeid, $colorid, $quantity, $edited) {
    global $onlineTempStoreDetailEX;
    global $onlineStoreSettingDAO;
    //
    $onlineStoreSetting = getOrHandleOnlineStoreSetting();
    $onlineStores = explode(',', $onlineStoreSetting->availableStores);
    //
    if (in_array($storeid, $onlineStores)) {
        $obj->storeid = $storeid;
        $obj->productid = $productid;
        $obj->sizeid = $sizeid;
        $obj->colorid = $colorid;
        $obj->quantity = $quantity;
        $obj->edited = $edited; //0 not edited "this value is therre online", 1 edited , 2 del
        $obj->sysdate = date("Y-m-d H:i:s");
        $obj->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
        $onlineTempStoreDetailEX->insertOrUpdateOnDuplicate($obj);
    }
}

function onlineTempStoreDetailFunc2($storeid, $productid, $sizeid, $colorid, $quantity, $edited) {
    global $onlineTempStoreDetailEX;
    global $onlineStoreSettingDAO;
    //
    $onlineStoreSetting = getOrHandleOnlineStoreSetting();
    $onlineStores = explode(',', $onlineStoreSetting->availableStores);
    //
    if (in_array($storeid, $onlineStores)) {
        $obj->storeid = $storeid;
        $obj->productid = $productid;
        $obj->sizeid = $sizeid;
        $obj->colorid = $colorid;
        $obj->quantity = $quantity;
        $obj->edited = $edited; //0 not edited "this value is therre online", 1 edited , 2 del
        $obj->sysdate = date("Y-m-d H:i:s");
        $obj->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
        $onlineTempStoreDetailEX->insertOrUpdateOnDuplicate2($obj);
    }
}

//add in Storemovement tbl
function onlineTempStoreReportFunc($obj) {
    global $onlineTempStoreReportEX;
    global $onlineStoreSettingDAO;
    //
    $onlineStoreSetting = getOrHandleOnlineStoreSetting();
    $onlineStores = explode(',', $onlineStoreSetting->availableStores);
    //
    if (in_array($obj->storeid, $onlineStores)) {
        $onlineTempStoreReportEX->insertWithIdEX($obj);
    }
}

//add in onlinetempproduct tbl
function onlineTempCategoryFunc($catid, $edited) {
    global $onlineTempCategoryEX;

    $obj->catid = $catid;
    $obj->edited = $edited; //0 not edited "this value is therre online", 1 edited , 2 del
    $obj->sysdate = date("Y-m-d H:i:s");
    $obj->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $onlineTempCategoryEX->insertOrUpdateOnDuplicate($obj);
}

//add in onlinetempproduct tbl
function onlineTempProductFunc($productid, $edited) {
    global $onlineTempProductEX;

    $obj->productid = $productid;
    $obj->edited = $edited; //0 not edited "this value is therre online", 1 edited , 2 del
    $obj->sysdate = date("Y-m-d H:i:s");
    $obj->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $onlineTempProductEX->insertOrUpdateOnDuplicate($obj);
}

function getOrHandleOnlineStoreSetting() {
    global $onlineStoreSetting;
    global $onlineStoreSettingDAO;
    $onlineStoreSetting = $onlineStoreSettingDAO->load(1);
    if (count($onlineStoreSetting) == 0) {
        $onlineStoreSetting->url = "";
        $onlineStoreSetting->availableStores = "";
        $onlineStoreSetting->onlinestoreid = 2;
        $onlineStoreSetting->onlineclientareaid = 0;
        $onlineStoreSetting->updatetype = 0;
        $onlineStoreSetting->catprohour = 0;
        $onlineStoreSetting->catprominute = 0;
        $onlineStoreSetting->proquantityhour = 0;
        $onlineStoreSetting->proquantityminute = 0;
        $onlineStoreSetting->clientshour = 0;
        $onlineStoreSetting->clientsminute = 0;
        $onlineStoreSetting->ordershour = 0;
        $onlineStoreSetting->ordersminute = 0;
        $onlineStoreSetting->clientdebtchangeStartId = -1;
        $onlineStoreSettingDAO->insert($onlineStoreSetting);
    }
    return $onlineStoreSetting;
}

function affectPartner($val, $comment, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor) {
    global $myPartnerRecord;
    global $myPartnertransferbetweenRecord;
    global $myPartnerwithdrawalRecord;
    global $myPartnerwithdrawalEx;

    $partnervalue = $val;
    #1  check weather it is partnerwithdraw or partnertransferbetween
    $whatIsItFrom = whatIsIt($AllDailyEntryDebtor[0]->accountstreeid);
    $whatIsItTo = whatIsIt($AllDailyEntryCreditor[0]->accountstreeid);
    //this is partnertransferbetween
    if ($whatIsItFrom == $whatIsItTo && $whatIsItTo == "partner") {
        if ($whichSideisIt == 0) {// && $whichSideisIt == 0 is to make it once as both debit , credit side will come here
            // this is delete partnertransferbetween
            $partnerfromdata = R::findOne('partner', 'treeId = ? ', [$AllDailyEntryDebtor[0]->accountstreeid]);
            $partnertodata = R::findOne('partner', 'treeId = ? ', [$AllDailyEntryCreditor[0]->accountstreeid]);

            if ($dailyEntry->reverseofid > 0) {
//            $id = R::getCell('select partnertransferbetweenid from partnertransferbetween where dailyentryid=' . $dailyEntry->reverseofid);
                R::exec("UPDATE partnertransferbetween SET conditions= 1 WHERE dailyentryid =" . $dailyEntry->reverseofid);

                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + '" . $partnervalue . "'  WHERE partnerid = '" . $partnerfromdata->partnerid . "' ");
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - '" . $partnervalue . "'  WHERE partnerid = '" . $partnertodata->partnerid . "' ");

//            $myPartnertransferbetweenRecord->delete($id);
            } else {
                // this is add partnertransferbetween


                $myPartnertransferbetween->conditions = 0;
                $myPartnertransferbetween->partneridfrom = $partnerfromdata->partnerid;
                $myPartnertransferbetween->partneridto = $partnertodata->partnerid;
                $myPartnertransferbetween->partnerdate = date("Y-m-d");
                $myPartnertransferbetween->partnervalue = $partnervalue;
                $myPartnertransferbetween->partnerfrombefore = $partnerfromdata->partnermoney;
                $myPartnertransferbetween->partnerfromafter = $partnerfromdata->partnermoney - $partnervalue;
                $myPartnertransferbetween->partnertobefore = $partnertodata->partnermoney;
                $myPartnertransferbetween->partnertoafter = $partnertodata->partnermoney + $partnervalue;
                $myPartnertransferbetween->userid = $_SESSION["userid"];
                $myPartnertransferbetween->comment = $comment;
                $myPartnertransferbetween->dailyentryid = $id;
                $Partnertransferbetweenid = $myPartnertransferbetweenRecord->insert($myPartnertransferbetween);

                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - " . $partnervalue . "  WHERE partnerid = '" . $partnerfromdata->partnerid . "' ");
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + " . $partnervalue . "  WHERE partnerid = '" . $partnertodata->partnerid . "' ");
            }
        }
    } else {// this is partner withdraw
        if ($dailyEntry->reverseofid > 0) {
            $partnerwithdrawal = R::getRow('select * from partnerwithdrawal where dailyentryid=' . $dailyEntry->reverseofid);
            $partnerwithdrawalId = $partnerwithdrawal['partnerwithdrawalid'];
            $partnerwithdrawalValue = $partnerwithdrawal['partnerwithdrawalvalue'];

            $myPartnerwithdrawal->conditions = 1;
            $myPartnerwithdrawal->userid = $_SESSION['userid'];
            $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
            $myPartnerwithdrawal->partnerwithdrawalid = $partnerwithdrawalId;
            $dataPartner = $myPartnerRecord->load($partnerwithdrawal['partnerid']);
            $myPartnerwithdrawal->partnerbefore = $dataPartner->partnermoney;
            if ($partnerwithdrawalData['partenrwithdrawaltype'] == 1) {
                $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney + $partnerwithdrawalValue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerwithdrawal['partnerid'] . "' ");
            } else {
                $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney - $partnerwithdrawalValue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerwithdrawal['partnerid'] . "' ");
            }

            $myPartnerwithdrawalEx->updateConditions($myPartnerwithdrawal);
        } else {
            $partnerTreeId = $AllDailyEntryDebtor[0]->accountstreeid;
            $saveOrBankAccountTreeId = $AllDailyEntryCreditor[0]->accountstreeid;
            if ($whichSideisIt == 1) {
                $partnerTreeId = $AllDailyEntryCreditor[0]->accountstreeid;
                $saveOrBankAccountTreeId = $AllDailyEntryDebtor[0]->accountstreeid;
            }

            $partnerdata = R::getrow('select * from partner where treeId = ? ', [$partnerTreeId]);
            //add in Partnerwithdrawal tbl
            $myPartnerwithdrawal->conditions = 0;
            $myPartnerwithdrawal->partnerid = $partnerdata['partnerid'];
            $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
            $myPartnerwithdrawal->partenrwithdrawaltype = ($whichSideisIt == 1) ? 0 : 1; //$partenrwithdrawaltype
            $myPartnerwithdrawal->partnerwithdrawalvalue = $val;
            $myPartnerwithdrawal->partnerbefore = $partnerdata['partnermoney'];
            $myPartnerwithdrawal->userid = $_SESSION["userid"];
            $myPartnerwithdrawal->comment = $comment;
            $myPartnerwithdrawal->dailyentryid = $id;
            if ($partenrwithdrawaltype == 1) {
                $myPartnerwithdrawal->partnerafter = $partnerdata['partnermoney'] - $val;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - " . $val . "  WHERE partnerid = '" . $partnerdata['partnerid'] . "' ");
            } else {
                $myPartnerwithdrawal->partnerafter = $partnerdata['partnermoney'] + $val;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + " . $val . "  WHERE partnerid = '" . $partnerdata['partnerid'] . "' ");
            }


            $saveid = 0;
            $bankid = 0;
            $bankaccountid = 0;
            $saveid = (int) R::getCell('select saveid from save where treeId=' . $saveOrBankAccountTreeId);
            if ($saveid < 1) {
                $bankaccountData = R::getRow('select accountid,bankid from bankaccount where treeId=' . $saveOrBankAccountTreeId);
                $bankaccountid = $bankaccountData['accountid'];
                $bankid = R::getCell('select bankid from bank where bankid=' . $bankaccountData['bankid']);
            }

            $myPartnerwithdrawal->saveid = $saveid;
            $myPartnerwithdrawal->bankid = $bankid;
            $myPartnerwithdrawal->bankaccountid = $bankaccountid;
            $myPartnerwithdrawal->checknum = '';
            $partnerwithdrawalId = $myPartnerwithdrawalRecord->insert($myPartnerwithdrawal);
        }
    }
}

//transfermoneyController,settlementsaveController,cashTransferController
function affectOtherSaveControllers($val, $comment, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor) {
    global $myTransfermoneyRecord;
    global $myImpotencetreatmentsuppliersaveRecord;
    global $myImpotencetreatmentsuppliersaveEx;
    global $cashTransferDAO;


    #1  check weather it is transfermoneyController or settlementsaveController
    $whatIsItFrom = whatIsIt($AllDailyEntryDebtor[0]->accountstreeid);
    $whatIsItTo = whatIsIt($AllDailyEntryCreditor[0]->accountstreeid);

    //this is transfermoneyController between saves
    if ($whatIsItFrom == $whatIsItTo && ($whatIsItTo == "save" || $whatIsItTo == "3ohad")) {
        if ($whichSideisIt == 0) {// && $whichSideisIt == 0 is to make it once as both debit , credit side will come here
            // this is delete partnertransferbetween
            $fromdata = R::getRow('select * from save where treeId = ? ', [$AllDailyEntryDebtor[0]->accountstreeid]);
            $todata = R::getRow('select * from save where treeId = ? ', [$AllDailyEntryCreditor[0]->accountstreeid]);
            $cFactorFrom = R::getCell('select conversionFactor from currency where id = ? ', [$fromdata['currencyId']]);
            $cFactorTo = R::getCell('select conversionFactor from currency where id = ? ', [$todata['currencyId']]);
            if ($dailyEntry->reverseofid > 0) {
                R::exec("UPDATE transfermoney SET conditions= 2 WHERE dailyentryid =" . $dailyEntry->reverseofid);
            } else {
                // this is add partnertransferbetween
                //add in Transfermoney tbl
                $myTransfermoney->conditions = 0;
                $myTransfermoney->saveidfrom = $todata['saveid'];
                $myTransfermoney->saveidto = $fromdata['saveid'];
                $myTransfermoney->transfermoneydate = date("Y-m-d");
                $myTransfermoney->transfermoneyvalue = $val / $cFactorTo;
                $myTransfermoney->userid = $_SESSION["userid"];
                $myTransfermoney->dailyentryid = $id;
                $myTransfermoney->comment = $comment;
                $myTransfermoney->currencyId = $todata['currencyId'];
                $myTransfermoney->conversionFactor = $cFactorTo;
                $myTransfermoney->conversionFactorFrom = $cFactorTo;
                $myTransfermoney->conversionFactorTo = $cFactorFrom;
                $myTransfermoney->transfermoneyvalueInCurrency = $val;
                $transfermoneyId = $myTransfermoneyRecord->insert($myTransfermoney);
            }
        }
    }
    //cashTransferController
    elseif ((($whatIsItFrom == "save" || $whatIsItFrom == "3ohad" ) && $whatIsItTo == "bank") ||
            (( $whatIsItTo == "save" || $whatIsItTo == "3ohad") && $whatIsItFrom == "bank")) {
        if ($dailyEntry->reverseofid > 0) {
            R::exec("UPDATE cashtransfer SET conditions= 1 WHERE dailyentryid =" . $dailyEntry->reverseofid);
        } else {
            if ($whatIsItTo == "bank") { //سحب شيك//$transfer == 1
                $type = 1;
                $processname = "تحويل نقدي من البنك إلى الخزنة";
                $savedailychangetype = 0;
                $accountmovementtype = 1;
                $saveData = R::getRow('select * from save where treeId = ? ', [$AllDailyEntryDebtor[0]->accountstreeid]);
                $bankAccountDebtData = R::getRow('select * from bankaccount where treeId = ? ', [$AllDailyEntryCreditor[0]->accountstreeid]);
            } else if ($whatIsItFrom == "bank") {//إيداع شيك//$transfer == 2
                $type = 2;
                $processname = "تحويل نقدي من الخزنة إلى البنك";
                $savedailychangetype = 1;
                $accountmovementtype = 0;
                $saveData = R::getRow('select * from save where treeId = ? ', [$AllDailyEntryCreditor[0]->accountstreeid]);
                $bankAccountDebtData = R::getRow('select * from bankaccount where treeId = ? ', [$AllDailyEntryDebtor[0]->accountstreeid]);
            }

            $cashTransfer->accountbeforevalue = $bankAccountDebtData['accountbeginingbalance'];
            $cashTransfer->bankaccountid = $bankAccountDebtData['accountid'];
            $cashTransfer->cashtransferamount = $val;
            $cashTransfer->cashtransferdate = date('Y-m-d');
            $cashTransfer->cashtransfernote = $comment;
            $cashTransfer->cashtransfernumber = 0;
            $cashTransfer->cashtransferuser = '';
            $cashTransfer->conditions = 0;
            $cashTransfer->saveid = $saveData['saveid'];
            $cashTransfer->type = $type;
            $cashTransfer->userid = $_SESSION['userid'];
            $cashTransfer->dailyentryid = $id;

            $cashTransferId = $cashTransferDAO->insert($cashTransfer);
        }
    }
    // this is settlementsaveController
    else if (($whatIsItFrom == "SaveDeficitAndIncreaseAccount" && ($whatIsItTo == "save" || $whatIsItTo == "3ohad")) ||
            ($whatIsItTo == "SaveDeficitAndIncreaseAccount") && ($whatIsItFrom == "save" || $whatIsItFrom == "3ohad")) {
        if ($dailyEntry->reverseofid > 0) {
            //R::exec("UPDATE transfermoney SET conditions= 2 WHERE dailyentryid =" . $dailyEntry->reverseofid);
            $myImpotencetreatmentsuppliersaveEx->updateConditionsTo1Bydailyentryid($dailyEntry->reverseofid);
        } else {
            if ($whatIsItTo == "SaveDeficitAndIncreaseAccount") {//increase save
                $savedata = R::getRow('select * from save where treeId = ? ', [$AllDailyEntryDebtor[0]->accountstreeid]);
                $savebefore = $savedata['savecurrentvalue'];
                $savebeafter = $savedata['savecurrentvalue'] + $val;
                $savedailychangeType = 0;
            } else {//decrease save
                $savedata = R::getRow('select * from save where treeId = ? ', [$AllDailyEntryCreditor[0]->accountstreeid]);
                $savebefore = $savedata['savecurrentvalue'];
                $savebeafter = $savedata['savecurrentvalue'] - $val;
                $savedailychangeType = 1;
            }

            $myImpotencetreatmentsuppliersave->typesimpotencetreatmentid = -1;
            $myImpotencetreatmentsuppliersave->saveid = $savedata['saveid'];
            $myImpotencetreatmentsuppliersave->supplierid = -1;
            $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavetype = $savedailychangeType;
            $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavebefore = $savebefore;
            $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavetamount = $val;
            $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersaveafter = $savebeafter;
            $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavecomment = $comment;
            $myImpotencetreatmentsuppliersave->conditions = 0;
            $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavedate = date("Y-m-d H:i:s");
            $myImpotencetreatmentsuppliersave->userid = $_SESSION['userid'];
            $myImpotencetreatmentsuppliersave->tablename = "settlementsaveController.php";
            $myImpotencetreatmentsuppliersave->dailyentryid = $id;
            $impotencetreatmentsuppliersaveId = $myImpotencetreatmentsuppliersaveRecord->insert($myImpotencetreatmentsuppliersave);
        }
    }
}

//transferBtweenBankAccounts,bankAccountDeficitController
function affectOtherBankControllers($val, $comment, $id, $whichSideisIt, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor) {
    global $myAccountmovementRecord;
    global $transferBtweenBankAccountsDAO;


    #1  check weather it is transfermoneyController or settlementsaveController
    $whatIsItFrom = whatIsIt($AllDailyEntryDebtor[0]->accountstreeid);
    $whatIsItTo = whatIsIt($AllDailyEntryCreditor[0]->accountstreeid);

    //this is transferBtweenBankAccounts between banks
    if ($whatIsItFrom == $whatIsItTo && $whatIsItTo == "bank") {
        if ($whichSideisIt == 0) {// && $whichSideisIt == 0 is to make it once as both debit , credit side will come here
            // this is delete partnertransferbetween
            $bankAccountDebtData = R::getRow('select * from bankaccount where treeId = ? ', [$AllDailyEntryDebtor[0]->accountstreeid]);
            $bankAccountCreditData = R::getRow('select * from bankaccount where treeId = ? ', [$AllDailyEntryCreditor[0]->accountstreeid]);

            if ($dailyEntry->reverseofid > 0) {
                R::exec("UPDATE transferbtweenbankaccount SET conditions= 1 WHERE dailyentryid =" . $dailyEntry->reverseofid);
            } else {
                // this is add partnertransferbetween
                //add in Transfermoney tbl
                $transferBtweenBankAccounts->bankidfrom = $bankAccountCreditData['bankid'];
                $transferBtweenBankAccounts->bankidto = $bankAccountDebtData['bankid'];
                $transferBtweenBankAccounts->accountidfrom = $bankAccountCreditData['accountid'];
                $transferBtweenBankAccounts->accountidto = $bankAccountDebtData['accountid'];
                $transferBtweenBankAccounts->transfervalue = $val;
                $transferBtweenBankAccounts->transferdate = date("Y-m-d H:i:s");
                $transferBtweenBankAccounts->userid = $_SESSION["userid"];
                $transferBtweenBankAccounts->conditions = 0;
                $transferBtweenBankAccounts->dailyentryid = $id;
                $transferBtweenBankAccounts->comment = $comment;
                $transferId = $transferBtweenBankAccountsDAO->insert($transferBtweenBankAccounts);
            }
        }
    }
    //this is bankAccountDeficitController to decrease bank account
    else if ($whatIsItFrom == 'bankExpensesAccount') {
        // this is delete partnertransferbetween
        $bankAccountdata = R::getRow('select * from bankaccount where treeId = ? ', [$AllDailyEntryCreditor[0]->accountstreeid]);

        if ($dailyEntry->reverseofid > 0) {//reverse means del
            //R::exec("UPDATE transfermoney SET conditions= 2 WHERE dailyentryid =" . $dailyEntry->reverseofid);
            $balanceBefore = $bankAccountdata['accountbeginingbalance'];
            $changeamount = $val;
            $balanceAfter = $balanceBefore + $val;
            $changetype = 0;
            $processName = 'عكس قيد معالجة عجز حساب بالخصم	';
        } else {
            $balanceBefore = $bankAccountdata['accountbeginingbalance'];
            $changeamount = $val;
            $balanceAfter = $balanceBefore - $val;
            $changetype = 1;
            $processName = 'معالجة عجز حساب بالخصم	';
        }
        $myAccountmovement->accountmovementbefore = $balanceBefore;
        $myAccountmovement->accountmovementamount = $changeamount;
        $myAccountmovement->accountmovementafter = $balanceAfter;
        $myAccountmovement->accountmovementtype = $changetype;

        $myAccountmovement->accountmovementdate = date('Y-m-d H:i:s');
        $myAccountmovement->accountmovementmodelid = 0;
        $myAccountmovement->accountid = $bankAccountdata['accountid'];
        $myAccountmovement->tablename = "bankAccountDeficitController.php";
        $myAccountmovement->userid = $_SESSION['userid'];
        $myAccountmovement->bankid = $bankAccountdata['bankid'];
        $myAccountmovement->accountmovementcomment = $comment;
        $myAccountmovement->processname = $processName;
        $myAccountmovement->accountmovementkindid = -1;

        //Insert
        $accountMovementId = $myAccountmovementRecord->insert($myAccountmovement);
    }
    //this is bankAccountDeficitController to increase bank account
    else if ($whatIsItTo == "bankIncomeAccount") {
        // this is delete partnertransferbetween
        $bankAccountdata = R::getRow('select * from bankaccount where treeId = ? ', [$AllDailyEntryDebtor[0]->accountstreeid]);

        if ($dailyEntry->reverseofid > 0) {//reverse means del
            //R::exec("UPDATE transfermoney SET conditions= 2 WHERE dailyentryid =" . $dailyEntry->reverseofid);
            $balanceBefore = $bankAccountdata['accountbeginingbalance'];
            $changeamount = $val;
            $balanceAfter = $balanceBefore - $val;
            $changetype = 1;
            $processName = 'عكس قيد معالجة عجز حساب بالزيادة';
        } else {
            $balanceBefore = $bankAccountdata['accountbeginingbalance'];
            $changeamount = $val;
            $balanceAfter = $balanceBefore + $val;
            $changetype = 0;
            $processName = 'معالجة عجز حساب بالزيادة';
        }
        $myAccountmovement->accountmovementbefore = $balanceBefore;
        $myAccountmovement->accountmovementamount = $changeamount;
        $myAccountmovement->accountmovementafter = $balanceAfter;
        $myAccountmovement->accountmovementtype = $changetype;

        $myAccountmovement->accountmovementdate = date('Y-m-d H:i:s');
        $myAccountmovement->accountmovementmodelid = 0;
        $myAccountmovement->accountid = $bankAccountdata['accountid'];
        $myAccountmovement->tablename = "bankAccountDeficitController.php";
        $myAccountmovement->userid = $_SESSION['userid'];
        $myAccountmovement->bankid = $bankAccountdata['bankid'];
        $myAccountmovement->accountmovementcomment = $comment;
        $myAccountmovement->processname = $processName;
        $myAccountmovement->accountmovementkindid = -1;

        //Insert
        $accountMovementId = $myAccountmovementRecord->insert($myAccountmovement);
    }
}

?>