<?php

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

//global varable
global $showoutside;
//
include("affectplugins.php");

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
//Transaction
include_once("../models/sql/Transaction.class.php");

//here the db files that include in the file
include("../public/include_dao.php");
/* ------------------------------------------------------------- */
##i put it here as putting it down make update statment not working
//we need to update branch id in daily entry to be like branch id of user
//getting users with branch id = 0"which is all branches" and put it again in daily entry has no meening
//so get user who has certain branch
require_once('../models/dao/DailyentryDAO.class.php');
require_once('../models/dto/Dailyentry.class.php');
require_once('../models/mysql/DailyentryMySqlDAO.class.php');
require_once('../models/mysql/ext/DailyentryMySqlExtDAO.class.php');
$dailyEntryEX = new DailyentryMySqlExtDAO();
$allnothavebranch = $dailyEntryEX->queryAllnothavebranch();
foreach ($allnothavebranch as $myallnothavebranch) {
    $user_branch_id = $myallnothavebranch->value;
    $dailyEntryEX->updatebranchid($user_branch_id, $myallnothavebranch->id);
}
/* -------------------------------------------------------------- */
//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');
//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');

//Dailyentry
require_once('../models/dao/DailyentryDAO.class.php');
require_once('../models/dto/Dailyentry.class.php');
require_once('../models/mysql/DailyentryMySqlDAO.class.php');
require_once('../models/mysql/ext/DailyentryMySqlExtDAO.class.php');
//Dailyentrycreditor
require_once('../models/dao/DailyentrycreditorDAO.class.php');
require_once('../models/dto/Dailyentrycreditor.class.php');
require_once('../models/mysql/DailyentrycreditorMySqlDAO.class.php');
require_once('../models/mysql/ext/DailyentrycreditorMySqlExtDAO.class.php');
//Dailyentrydebtor
require_once('../models/dao/DailyentrydebtorDAO.class.php');
require_once('../models/dto/Dailyentrydebtor.class.php');
require_once('../models/mysql/DailyentrydebtorMySqlDAO.class.php');
require_once('../models/mysql/ext/DailyentrydebtorMySqlExtDAO.class.php');

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


########################affect programs plugins
//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');
//get the do the action
$do = $_GET['do'];

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

/* ======================

  Controller Name :- accountstree

  OPERTATION in Controller

  1- display add form, add
  2- add in tbl
  3- display show and tempdelete
  4- edit
  5- update

  ======================== */
if ($do != "print") {
//here the global templates
    $smarty->display("header.html");
}
//here goes the instances and general variables
//Transaction
$transactions = new Transaction();

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();
//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

//Branch
$Branch = new Branch();
$BranchDAO = new BranchMySqlDAO();
$BranchEX = new BranchMySqlExtDAO();

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

//Costcenter
$costCenter = new Costcenter();
$costCenterDAO = new CostcenterMySqlDAO();
$costCenterEX = new CostcenterMySqlExtDAO();


########################affect programs plugins
//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();

//User
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

########################


$today = date("Y-m-d");
$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);

//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    ##
    //$accountsTree = $accountsTreeDAO->queryAll();
    $user_data = $myUserRecord->load($_SESSION['userid']);
    $smarty->assign("user_data", $user_data);
    $allbranchdata = $BranchDAO->queryAll();
    $smarty->assign("allbranchdata", $allbranchdata);


//    $accountsTree = $accountsTreeDAO->queryByItemtype2(1);
//    $smarty->assign("accountsTree", $accountsTree);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $costCenter = $costCenterDAO->queryAll();
    $smarty->assign("costCenter", $costCenter);

    $queryString = '';
    $dailyentryid = filter_input(INPUT_POST, "dailyentryid");
    if (empty($dailyentryid)) {
        $dailyentryid = filter_input(INPUT_GET, "id");
    }
    $datefrom = filter_input(INPUT_POST, "datefrom");
    $dateto = filter_input(INPUT_POST, "dateto");
    $layingOrder = filter_input(INPUT_POST, "layingOrder");
    $branchid = filter_input(INPUT_POST, "branchid");

    if (empty($dailyentryid) && empty($datefrom) && empty($dateto)) {
        $datefrom = date('Y-m-d');
        $dateto = date('Y-m-d');
    }

    DrawTableNew($dailyentryid, $datefrom, $dateto, $layingOrder, $branchid);

    $smarty->assign("now", date('Y-m-d H:i:s'));
    //here the smarty templates
    $smarty->display("dailyentryview/add.html");
} elseif ($do == "reverse") {
    //$transactions::Transaction();
    try {
        reverse();
        $transactions->commit();
        header("location:dailyentry.php");
    } catch (Exception $e) {
        $transactions->rollback($e);
        header("location:?do=error");
    }
} elseif ($do == "print") {
    $queryString = '';
    $dailyentryid = filter_input(INPUT_POST, "dailyentryid");
    if (empty($dailyentryid)) {
        $dailyentryid = filter_input(INPUT_GET, "id");
    }
    $datefrom = filter_input(INPUT_POST, "datefrom");
    $dateto = filter_input(INPUT_POST, "dateto");
    $layingOrder = filter_input(INPUT_POST, "layingOrder");
    $branchid = filter_input(INPUT_POST, "branchid");


    if (empty($dailyentryid) && empty($datefrom) && empty($dateto)) {
        $datefrom = date('Y-m-d');
        $dateto = date('Y-m-d');
    }

    DrawTableNew($dailyentryid, $datefrom, $dateto, $layingOrder, $branchid, 1);

    $smarty->assign("now", date('Y-m-d H:i:s'));
    //here the smarty templates
    $smarty->display("dailyentryview/print.html");
} elseif ($do == "openingentry") {

    ####
    $hideParentArr = [];
    if ($_COOKIE['showClientsAtTree'] == 0) {
        $hideParentArr[] = 58;
        $hideParentArr[] = 60;
    }
    if ($_COOKIE['showSuppliersAtTree'] == 0) {
        $hideParentArr[] = 81;
        $hideParentArr[] = 87;
    }
    $hideParentArr = !empty($hideParentArr) ? array_unique($hideParentArr) : [0];
    $hideParentStr = implode(',', $hideParentArr);


    $allLastLeafs = $accountsTreeEX->getLastLeafsAll($hideParentStr);
    $smarty->assign("allLastLeafs", $allLastLeafs);
    $smarty->assign("now", date('Y-m-d H:i:s'));
    //here the smarty templates
    $smarty->display("dailyentryview/openingentry.html");
} elseif ($do == "openingbalance") {
    ####
    $hideParentArr = [];
    if ($_COOKIE['showClientsAtTree'] == 0) {
        $hideParentArr[] = 58;
        $hideParentArr[] = 60;
    }
    if ($_COOKIE['showSuppliersAtTree'] == 0) {
        $hideParentArr[] = 81;
        $hideParentArr[] = 87;
    }
    $hideParentArr = !empty($hideParentArr) ? array_unique($hideParentArr) : [0];
    $hideParentStr = implode(',', $hideParentArr);

    $allLastLeafs = $accountsTreeEX->getLastLeafsAll($hideParentStr);
    $smarty->assign("allLastLeafs", $allLastLeafs);
    //here the smarty templates
    $smarty->display("dailyentryview/openingbalance.html");
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->assign("dailyentry", 1);
if ($do != "print") {
    $smarty->display("footer.html");
}
/* ===============================
  function in this CONTROLLER
  ================================ */

function DrawTableNew($dailyentryid, $startDate, $endDate, $layingOrder, $branchid, $print = 0) {
    global $smarty;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;

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

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

    $queryString = '';
    $jon_branch = '';
    if (isset($startDate) && !empty($startDate)) {
        $queryString .= ' and dailyentry.thedate >= "' . $startDate . '" ';
    }
    if (isset($branchid) && $branchid > 0) {
        $queryString .= ' and dailyentry.branchid = "' . $branchid . '" ';
        $jon_branch = ' left join branch on  dailyentry.branchid=branch.branchId ';
    }


    if (isset($endDate) && !empty($endDate)) {
        $queryString .= ' and dailyentry.thedate <= "' . $endDate . '" ';
    }
    if (isset($dailyentryid) && !empty($dailyentryid)) {
        $dailyentryid = explode(",", $dailyentryid);
        $dailyentryidFilterd = '';
        foreach ($dailyentryid as $value) {
            if ($value > 0)
                $dailyentryidFilterd .= "$value,";
        }
        $dailyentryid = trim($dailyentryidFilterd, ',');
        $queryString .= ' and (dailyentry.id in( ' . $dailyentryid . ') or dailyentry.reverseofid in( ' . $dailyentryid . ') ) ';
    }
    /* if (isset($layingOrder) && !empty($layingOrder)) {
      $queryString .= ' and dailyentry.accountstreeid = "' . $layingOrder . '" ';
      } */


    ##########
    $branch_name = '';
    if ($jon_branch != '') {
        $branch_name = ',branch.branchName';
    }

    $dailyEntryData = R::getAll('SELECT dailyentry.* ' . $branch_name . '
                FROM dailyentry
                ' . $jon_branch . '
		where 1 ' . $queryString . ' order by dailyentry.related desc,dailyentry.id desc');

    $dailyEntryData = customArrayIndexOne($dailyEntryData, 'id');
    list($dailyEntryIdsArr) = [[]];
    foreach ($dailyEntryData as $value) {
        $dailyEntryIdsArr[] = $value['id'];
    }
    $dailyEntryIdsArr = !empty($dailyEntryIdsArr) ? array_unique($dailyEntryIdsArr) : [0];

    //
    $allDailyEnteryCreditor = R::getAll('SELECT dailyentrycreditor.id as idChild,dailyentrycreditor.dailyentryid,dailyentrycreditor.accountstreeid,dailyentrycreditor.value,dailyentrycreditor.dComment as dComment,
				1 as type ,concat(dailyentrycreditor.accountstreeid,"-",parent.customName,"/",accountstree.customName) as accountstreeName
				FROM dailyentrycreditor
				join accountstree on accountstree.id = dailyentrycreditor.accountstreeid
				join accountstree parent on parent.id = accountstree.parent
                                where dailyentrycreditor.dailyentryid in(' . implode(',', $dailyEntryIdsArr) . ')');
    $allDailyEnteryCreditor = customArrayIndexMany($allDailyEnteryCreditor, 'dailyentryid');

    $tempArr = array();
    foreach ($dailyEntryData as $value) {
        foreach ($allDailyEnteryCreditor[$value['id']] as $data) {
            foreach ($data as $key1 => $value1) {
                $value[$key1] = $value1;
            }

            //
            $obj = new stdClass();
            foreach ($value as $key1 => $value1) {
                $obj->$key1 = $value1;
            }
            $tempArr[] = $obj;
            //$tempArr[] = $value;
        }
    }
    $allDailyEnteryCreditor = $tempArr;

    //
    $allDailyEnteryDebtor = R::getAll('SELECT dailyentrydebtor.id as idChild,dailyentrydebtor.dailyentryid,dailyentrydebtor.accountstreeid,dailyentrydebtor.value,dailyentrydebtor.dComment as dComment,
				0 as type ,concat(dailyentrydebtor.accountstreeid,"-",parent.customName,"/",accountstree.customName) as accountstreeName
				FROM dailyentrydebtor
				join accountstree on accountstree.id = dailyentrydebtor.accountstreeid
                                join accountstree parent on parent.id = accountstree.parent
				where dailyentrydebtor.dailyentryid in(' . implode(',', $dailyEntryIdsArr) . ')');
    $allDailyEnteryDebtor = customArrayIndexMany($allDailyEnteryDebtor, 'dailyentryid');
    $tempArr = array();
    foreach ($allDailyEnteryDebtor as $key => $value) {
        $rowArr = array();
        foreach ($value as $data) {
            //
            $obj = new stdClass();
            foreach ($dailyEntryData[$data['dailyentryid']] as $key1 => $value1) {
                //$value[$key1] = $value1;
                $obj->$key1 = $value1;
            }
            foreach ($data as $key1 => $value1) {
                //$value[$key1] = $value1;
                $obj->$key1 = $value1;
            }
            $rowArr[] = $obj;
            //$tempArr[] = $value;
        }
        $tempArr[$key] = $rowArr;
    }
    $allDailyEnteryDebtor = $tempArr;






    // print_r($queryString);
    $allDailyEntery = array();
//    $allDailyEnteryCreditor = $dailyEntryEX->queryAllEXCreditor($queryString, $jon_branch);

    $prviosId = -1;
    foreach ($allDailyEnteryCreditor as $dataCreditor) {
        if ($print == 1) {
            $dataCreditor->dDateTime = date("Y-m-d", strtotime($dataCreditor->dDateTime));
        }

        if ($dataCreditor->id == $prviosId) {
            $dataCreditor->id = '';
        } else {
            $prviosId = $dataCreditor->id;
            $dataCreditor->id = '';
            //put debtor data first
//            $allDailyEnteryDebtor = $dailyEntryEX->queryAllEXDebtor($dataCreditor->dailyentryid, $queryString);
            $allDailyEnteryDebtorOfDaily = $allDailyEnteryDebtor[$dataCreditor->dailyentryid];
            $i = 0;
            foreach ($allDailyEnteryDebtorOfDaily as $dataDebtor) {
                if ($print == 1) {
                    $dataDebtor->dDateTime = date("Y-m-d", strtotime($dataDebtor->dDateTime));
                }

                if ($i != 0) {
                    $dataDebtor->id = "";
                }
                array_push($allDailyEntery, $dataDebtor);
                $i++;
            }
        }

        //put creditor data finaly
        array_push($allDailyEntery, $dataCreditor);
    }

    $smarty->assign("allDailyEntery", $allDailyEntery);
    $smarty->assign("allDailyEnteryCount", count($allDailyEntery));
}

function DrawTable($dailyentryid, $startDate, $endDate, $layingOrder, $branchid, $print = 0) {
    global $smarty;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;

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

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

    $queryString = '';
    $jon_branch = '';
    if (isset($startDate) && !empty($startDate)) {
        $queryString .= ' and dailyentry.thedate >= "' . $startDate . '" ';
    }
    if (isset($branchid) && $branchid > 0) {
        $queryString .= ' and dailyentry.branchid = "' . $branchid . '" ';
        $jon_branch = ' left join branch on  dailyentry.branchid=branch.branchId ';
    }


    if (isset($endDate) && !empty($endDate)) {
        $queryString .= ' and dailyentry.thedate <= "' . $endDate . '" ';
    }
    if (isset($dailyentryid) && !empty($dailyentryid)) {
        $queryString .= ' and dailyentry.id = "' . $dailyentryid . '" ';
    }
    /* if (isset($layingOrder) && !empty($layingOrder)) {
      $queryString .= ' and dailyentry.accountstreeid = "' . $layingOrder . '" ';
      } */


    // print_r($queryString);
    $allDailyEntery = array();
    $allDailyEnteryCreditor = $dailyEntryEX->queryAllEXCreditor($queryString, $jon_branch);

    $prviosId = -1;
    foreach ($allDailyEnteryCreditor as $dataCreditor) {
        if ($print == 1) {
            $dataCreditor->dDateTime = date("Y-m-d", strtotime($dataCreditor->dDateTime));
        }

        if ($dataCreditor->id == $prviosId) {
            $dataCreditor->id = '';
        } else {
            $prviosId = $dataCreditor->id;
            $dataCreditor->id = '';
            //put debtor data first
            $allDailyEnteryDebtor = $dailyEntryEX->queryAllEXDebtor($dataCreditor->dailyentryid, $queryString);
            $i = 0;
            foreach ($allDailyEnteryDebtor as $dataDebtor) {
                if ($print == 1) {
                    $dataDebtor->dDateTime = date("Y-m-d", strtotime($dataDebtor->dDateTime));
                }

                if ($i != 0) {
                    $dataDebtor->id = "";
                }

                array_push($allDailyEntery, $dataDebtor);
                $i++;
            }
        }
        //put creditor data finaly
        array_push($allDailyEntery, $dataCreditor);
    }
    /* $allDailyEntery = $dailyEntryDAO->queryAll();
      if(count($allDailyEntery)>0)
      {
      foreach($allDailyEntery as $dailyEntry)
      {
      $dailyEntry->from = $dailyEntryDebtorEX->queryByDailyentryidEX($dailyEntry->id);
      $dailyEntry->to = $dailyEntryCreditorEX->queryByDailyentryidEX($dailyEntry->id);
      }
      } */
    /* print_r('<pre>');
      print_r($allDailyEntery);
      print_r('</pre>'); */
    $smarty->assign("allDailyEntery", $allDailyEntery);
    $smarty->assign("allDailyEnteryCount", count($allDailyEntery));
}

function reverse() {
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;

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

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

    global $accountsTreeDAO;

    $id = filter_input(INPUT_GET, "id");


    //get data to reverse
    $olddailyEntry = $dailyEntryDAO->load($id);
    if ($olddailyEntry->reverseofid != -10) {

        //reverseofid = positive no : it is the no of daily entry which iam a reverse of
        //reverseofid = -10 : it means that i was reversed once
        //reverseofid = 0 : it means an entry not a reversed or reverse of another

        $olddailyEntry->reverseofid = -10;
        $dailyEntryDAO->update($olddailyEntry);

        $AllDailyEntryCreditor = $dailyEntryCreditorDAO->queryByDailyentryid($id);
        $AllDailyEntryDebtor = $dailyEntryDebtorDAO->queryByDailyentryid($id);

        //1-new Dailyentry
        $dailyEntry->totalcreditor = $olddailyEntry->totaldebtor;
        $dailyEntry->totaldebtor = $olddailyEntry->totalcreditor;
        $dailyEntry->thedate = date('Y-m-d');
        $dailyEntry->dDateTime = date('Y-m-d H:i:s');
        $dailyEntry->userid = $_SESSION['userid'];
        $dailyEntry->condition = 0;
        $dailyEntry->fromFlag = $olddailyEntry->fromFlag;
        $dailyEntry->related = $olddailyEntry->related;
        $dailyEntry->reverseofid = $olddailyEntry->id;
        $dailyEntry->entryComment = 'تم عكس القيد رقم ' . $olddailyEntry->id . ' ';
        $newentryId = $dailyEntryDAO->insert($dailyEntry);

        foreach ($AllDailyEntryDebtor as $debtor) {
            $dailyEntryCreditor->accountstreeid = $debtor->accountstreeid;
            $dailyEntryCreditor->dailyentryid = $newentryId;
            $dailyEntryCreditor->value = $debtor->value;
            $dailyEntryCreditor->dComment = $debtor->dComment;
            $dailyEntryCreditor->costcenterid = $debtor->costcenterid;
            $dailyEntryCreditorDAO->insert($dailyEntryCreditor);

            $operation = affectAccount($dailyEntryCreditor, 1);
            $whatIsIt = whatIsIt($debtor->accountstreeid);
            $element = $accountsTreeDAO->load($debtor->accountstreeid);
            affectPlugin($whatIsIt, $debtor->value, $newentryId, $operation, $element->name, "قيد يومية", "dailyentry.php", $debtor->costcenterid, $debtor->accountstreeid, 1, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
        }
        foreach ($AllDailyEntryCreditor as $credit) {
            $dailyEntryDebtor->accountstreeid = $credit->accountstreeid;
            $dailyEntryDebtor->dailyentryid = $newentryId;
            $dailyEntryDebtor->value = $credit->value;
            $dailyEntryDebtor->dComment = $credit->dComment;
            $dailyEntryDebtor->costcenterid = $credit->costcenterid;

            $dailyEntryDebtorDAO->insert($dailyEntryDebtor);

            $operation = affectAccount($dailyEntryDebtor, 0);
            $whatIsIt = whatIsIt($credit->accountstreeid);
            $element = $accountsTreeDAO->load($credit->accountstreeid);

            affectPlugin($whatIsIt, $credit->value, $newentryId, $operation, $element->name, "قيد يومية", "dailyentry.php", $credit->costcenterid, $credit->accountstreeid, 0, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
        }
    }
}

function affectAccount($CreditorOrDebtorObj, $type) {

    global $accountsTree;
    global $accountsTreeDAO;
    global $accountsTreeEX;

    $accountsTree = $accountsTreeDAO->load($CreditorOrDebtorObj->accountstreeid);
    $operation = whatToDo($accountsTree->itemtype, 'positive', $type);
    if ($operation == 'increase') {
        $accountsTree->theValue += $CreditorOrDebtorObj->value;
    }
    if ($operation == 'decrease') {
        $accountsTree->theValue -= $CreditorOrDebtorObj->value;
    }

    $accountsTreeDAO->update($accountsTree);

    //affect parents
    //affectParents($accountsTree->parent, $operation, $CreditorOrDebtorObj->value);
    //parents are the sum of children
    return $operation;
}

function whatToDo($accountType, $numSign, $type) {
    $operation;
    if ($numSign == 'positive') {

        if ($type == 0) {//مدين // من
            switch ($accountType) {
                case 0:
                case 3:
                case 5:
                    $operation = 'increase';
                    break;
                case 1:
                case 2:
                case 4:
                    $operation = 'decrease';
                    break;
                default:
                    break;
            }
        } elseif ($type == 1) {//دائن // الى
            switch ($accountType) {
                case 0:
                case 3:
                case 5:
                    $operation = 'decrease';

                    break;
                case 1:
                case 2:
                case 4:
                    $operation = 'increase';
                    break;
                default:
                    break;
            }
        }
    }
    return $operation;
}

function affectParents($parent, $operation, $value) {
    global $accountsTreeDAO;
    global $accountsTreeEX;

    if (!empty($parent)) {
        // retrieve all children of $parent
        $result = $accountsTreeDAO->load($parent);

        if (count($result) > 0) {
            if ($operation == 'increase') {
                $result->theValue += $value;
            }
            if ($operation == 'decrease') {
                $result->theValue -= $value;
            }
            $accountsTreeDAO->update($result);

            if ($result->parent != 0) {
                affectParents($result->parent, $operation, $value);
            }
        }
    }
}

?>