<?php

//Transaction
include_once("../models/sql/Transaction.class.php");

//
include_once("affectplugins.php");
//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');

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

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

/* ======================
  Controller Name :- accountstree
  ======================== */

//here goes the instances and general variables
//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();

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

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



/* -----------------------------------------------------------------------------
  ##this function is used to insert Tree Element
  ##function takes
  --$name of element ----"required".
  --$parent of the element that will be drawn below. it can take value = 0 means no parent ----"required".
  --$itemtype 0 masrofat,1khsoom,2eradat,3osool ----"required".
  --$itemfrom 0 from program , 1 from tree only ----"required".
  --$itemtype2 0 "parent" is a node haschilden , 1 "end element" has no childern only 1 is used in daily entry ----"required".
  --$notes ----"optional".
  --$theOrder ordering element in the display of the tree ----"default 0".
  --$theValue the value of element at the begining "it is used only if $itemtype2 = 1" ----"default 0".
  ##function returns
  -1:اسم العنصر مكرر ولم تكتكل العملية
  id:العنصر المضاف
  //default report id is 2 "مناجرة" for مصروفات وايرادات
  --------------------------------------------------------------------------- */

function addTreeElement($name, $parent, $itemtype, $itemfrom, $itemtype2, $notes = '', $theOrder = 0, $theValue = 0, $reportid = 0) {
    global $accountsTreeDAO;
    global $accountsTreeEX;
    global $accountsTree;


    $isunique = isUniqueName($name, $parent);
    if ($isunique == TRUE) {
        $parentData = $accountsTreeDAO->load($parent);
        if (empty($reportid)) {
            $reportid = $parentData->reportid;
        }
        $accountsTree->name = $name;
        $accountsTree->nameEn = $name;
        $accountsTree->customName = $name;
        $accountsTree->customNameEn = $name;
        $accountsTree->parent = $parent;
        $accountsTree->itemtype = $itemtype;
        $accountsTree->itemfrom = $itemfrom;
        $accountsTree->itemtype2 = $itemtype2;
        $accountsTree->accountNature = $parentData->accountNature;
        $accountsTree->listId = $parentData->listId;
        $accountsTree->notes = $notes;
        $accountsTree->theOrder = 0;
        $accountsTree->layingOrder = '';
        $accountsTree->del = 0;
        if ($itemtype2 == 1) {
            $accountsTree->theValue = $theValue;
        } else {
            $accountsTree->theValue = 0;
        }
        $accountsTree->userid = $_SESSION['userid'];
        $accountsTree->sysdate = date("Y-m-d H:i:s");
        $accountsTree->reportid = $reportid;

        $id = $accountsTreeDAO->insert($accountsTree);
        return $id;
    } else {
        $flag = -1;
        $result = $accountsTreeEX->queryByNameAndParent($name, $parent);
        if (count($result) == 1 && $result[0]->del == 1) {
            $row = $result[0];
            $row->del = 0;
            $accountsTreeDAO->update($row);
            $flag = $row->id;
        } else {
            $result = $accountsTreeEX->queryByCustomNameAndParent($name, $parent);
            if (count($result) == 1 && $result[0]->del == 1) {
                $row = $result[0];
                $row->del = 0;
                $accountsTreeDAO->update($row);
                $flag = $row->id;
            }
        }
        return $flag;
    }
}

/* -----------------------------------------------------------------------------
  ##this function is used to insert Tree Element
  ##function takes
  --$name of element ----"required".
  --$parent of the element that will be drawn below. it can take value = 0 means no parent ----"required".
  --$itemtype 0 masrofat,1khsoom,2eradat,3osool ----"required".
  --$itemfrom 0 from program , 1 from tree only ----"required".
  --$itemtype2 0 "parent" is a node haschilden , 1 "end element" has no childern only 1 is used in daily entry ----"required".
  --$notes ----"optional".
  --$theOrder ordering element in the display of the tree ----"default 0".
  --$theValue the value of element at the begining "it is used only if $itemtype2 = 1" ----"default 0".
  ##function returns
  -1:اسم العنصر مكرر ولم تكتكل العملية
  id:العنصر المضاف

  --------------------------------------------------------------------------- */

function delTreeElement($name) {
    global $accountsTreeDAO;
    global $accountsTree;
    $flag;
    try {
        $result = $accountsTreeDAO->queryByName($name);
        $row = $result[0];
        $row->del = 1;
        $accountsTreeDAO->update($row);
        $flag = 1;
    } catch (Exception $e) {
        $flag = -1;
    }
    return $flag;
}

function delTreeElementById($id) {
    global $accountsTreeDAO;
    global $accountsTree;
    $flag;
    try {
        $row = $accountsTreeDAO->load($id);
        $row->del = 1;
        $accountsTreeDAO->update($row);
        $flag = 1;
    } catch (Exception $e) {
        $flag = -1;
    }
    return $flag;
}

/* -----------------------------------------------------------------------------
  ##this function is used to un delete Tree Element
  ##function takes
  --$name of element ----"required".
  ##function returns
  -1:حدث خطأ
  1:تمت العملية

  --------------------------------------------------------------------------- */

function restoreTreeElement($name) {
    global $accountsTreeDAO;
    global $accountsTree;
    $flag;
    try {
        $result = $accountsTreeDAO->queryByName($name);
        $row = $result[0];
        $row->del = 0;
        $accountsTreeDAO->update($row);
        $flag = 1;
    } catch (Exception $e) {
        $flag = -1;
    }
    return $flag;
}

function restoreTreeElementById($id) {
    global $accountsTreeDAO;
    global $accountsTree;
    $flag;
    try {
        $result = $accountsTreeDAO->load($id);
        $row = $result[0];
        $row->del = 0;
        $accountsTreeDAO->update($row);
        $flag = 1;
    } catch (Exception $e) {
        $flag = -1;
    }
    return $flag;
}

/* send the object to update it */

//default report id is 2 "مناجرة" for مصروفات وايرادات
function editTreeElement($accountsTree) {
    global $accountsTreeDAO;

    $accountsTree->userid = $_SESSION['userid'];
    $accountsTree->sysdate = date("Y-m-d H:i:s");

    if ($accountsTree->customName == "") {
        $accountsTree->customName = $accountsTree->name;
    }

    if (empty($accountsTree->reportid)) {
        $accountsTree->reportid = 1;
        if ($accountsTree->itemtype == 0 || $accountsTree->itemtype == 2 || $accountsTree->itemtype == 5) {
            $accountsTree->reportid = 2;
        }
    }
    try {
        $accountsTreeDAO->update($accountsTree);

        $flag = 1;
    } catch (Exception $e) {
        $flag = -1;
    }
    return $flag;
}

function isUniqueName($value, $parent) {
    global $accountsTreeDAO;
    global $accountsTreeEX;
    $data = $accountsTreeEX->queryByNameAndParent($value, $parent);
    $data2 = $accountsTreeEX->queryByCustomNameAndParent($value, $parent);
    $flag = TRUE;
    if (count($data) > 0 || count($data2) > 0) {
        $flag = FALSE;
    }
    return $flag;
}

function isUniqueNameEdit($value, $parent) {
    global $accountsTreeDAO;
    global $accountsTreeDAO;
    global $accountsTreeEX;
    $data = $accountsTreeEX->queryByNameAndParent($value, $parent);
    $data2 = $accountsTreeEX->queryByCustomNameAndParent($value, $parent);
    $flag = TRUE;
    if (count($data) > 0 || count($data2) > 0) {
        $flag = FALSE;
    }
    return $flag;
}

/* -----------------------------------------------------------------------------
  ##this function is used to insert dailyentry with "one or more" creditor and "one or more" debtors
  ##it require has 3 inputs

  ##first one is $dailyEntryObj it is optional it should be like this
  $dailyEntryObj->totalcreditor = 50; //الى دائن
  $dailyEntryObj->totaldebtor = 50; // من مدين
  $dailyEntryObj->dDateTime = date('Y-m-d H:i:s');
  $dailyEntryObj->thedate = date('Y-m-d');
  $dailyEntryObj->userid = 10;//userwho entered thisrow like $_SESSION['userid']
  $dailyEntryObj->condition = 0; //it means not deleted ,1 is deleted
  $dailyEntryObj->reverseofid = 0;// it means it is new dailyentry not a reverse of another one
 * //-9 new but cannot be reversed manually
 * //-10 really reversed
  $dailyEntryObj->costcenterid = 0;
  $dailyEntryObj->entryComment = '';
  //note totalcreditor must equal totaldebtor and shoulnot be zero if you provide this object
  //all fields are optional ==> i mean you can provide one colum or more OR not to give me this object at all
 *

  ##second one is $dailyEntryDebtorArray it is required it should be array of objects like this
  $dailyEntryDebtor->accountstreeid = $parent;//id of account *required
  $dailyEntryDebtor->value = $value;//value to affect it.it is positive *required
  $dailyEntryDebtor->dComment = $comment; // optional

  ##third one is $dailyEntryCreditorArray it is required it should be array of objects like this
  $dailyEntryCreditor->accountstreeid = $parent;//id of account *required
  $dailyEntryCreditor->value = $value;//value to affect it.it is positive  *required
  $dailyEntryCreditor->dComment = $comment; // optional

  #fourth one is $stopEntryTransaction it takes default value = 0 means use transaction, value = 1 means stop useing transations this is used in case that insertEntery() is part of function that uses transations already to stop nested transactions
  as in mysql comit and rollback End any transaction in session even if they are many transactions

  ##function returns
  1 : sucess
  -1:لابد ان يكون مجموع مدين يساوى مجموع دائن وان لا يكون هذا المجموع  يساوى صفر
  -2:'عفوا لقد حدث خطأ'

  +
  --------------------------------------------------------------------------- */

function insertEntery($dailyEntryObj = NULL, $dailyEntryDebtorArray, $dailyEntryCreditorArray, $stopEntryTransaction = 0, $operationId = 0, $operationDetailLink = '') {
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $accountsTreeDAO;

    $message = '';
    $flag = 0;
    $totaldebtor = getTotal($dailyEntryDebtorArray);
    $totalcreditor = getTotal($dailyEntryCreditorArray);
    //1- check totals
    if ($totaldebtor == $totalcreditor && $totalcreditor != 0) {
        //2- prepare dailyEntryObj
        if ($dailyEntryObj == NULL) {
            $dailyEntryObj->totalcreditor = $totalcreditor; //الى دائن
            $dailyEntryObj->totaldebtor = $totaldebtor; // من مدين
            $dailyEntryObj->dDateTime = date('Y-m-d H:i:s');
            $dailyEntryObj->thedate = date('Y-m-d');
            $dailyEntryObj->userid = $_SESSION['userid'];
            $dailyEntryObj->condition = 0;
            $dailyEntryObj->reverseofid = 0;
            $dailyEntryObj->entryComment = '';
            $dailyEntryObj->related = 0;
        } else {
            $dailyEntryObj->totalcreditor = $totalcreditor; //الى دائن
            $dailyEntryObj->totaldebtor = $totaldebtor; // من مدين
            if (empty($dailyEntryObj->dDateTime)) {
                $dailyEntryObj->dDateTime = date('Y-m-d H:i:s');
            }
            if (empty($dailyEntryObj->thedate)) {
                $dailyEntryObj->thedate = date('Y-m-d');
            }
            if (empty($dailyEntryObj->userid)) {
                $dailyEntryObj->userid = $_SESSION['userid'];
            }
            if ($dailyEntryObj->condition == '') {
                $dailyEntryObj->condition = 0;
            }
            if ($dailyEntryObj->reverseofid == '') {
                $dailyEntryObj->reverseofid = 0;
            }
            if (empty($dailyEntryObj->entryComment)) {
                $dailyEntryObj->entryComment = '';
            }
            if (empty($dailyEntryObj->related)) {
                $dailyEntryObj->related = 0;
            }
        }
        $dailyEntryObj->operationId = $operationId;
        $dailyEntryObj->operationDetailLink = $operationDetailLink;



        if ($stopEntryTransaction == 0) {//use transaction
            //Transaction
            $transactions = new Transaction();
        }
        try {
            //3-insert
            if (($dailyEntryObj->fromFlag != 0 && $dailyEntryObj->fromFlag != 2) || $dailyEntryObj->fromFlag == "") {
                $dailyEntryObj->fromFlag = 1;
            }
            $dailyEntry->branchid = $_SESSION['branchId'];
            $dailyEntryId = $dailyEntryDAO->insert($dailyEntryObj);
            foreach ($dailyEntryDebtorArray as $dailyEntryDebtor) {
                if (!empty($dailyEntryDebtor->accountstreeid) && !empty($dailyEntryDebtor->value)) {
                    $dailyEntryDebtor->dailyentryid = $dailyEntryId;
                    if (empty($dailyEntryDebtor->dComment)) {
                        $dailyEntryDebtor->dComment = '';
                    }
                    if ($dailyEntryDebtor->costcenterid == '') {
                        $dailyEntryDebtor->costcenterid = 0;
                    } else {
                        insertCostCenterDetail($dailyEntryDebtor->costcenterid, $dailyEntryDebtor->value, $dailyEntryId, $dailyEntryDebtor->pluginComment, $dailyEntryDebtor->pluginControllerName, $dailyEntryDebtor->costcenterType);
                    }

                    $dailyEntryDebtorDAO->insert($dailyEntryDebtor);

                    $operation = affectAccount($dailyEntryDebtor, 0);
                    if ($dailyEntryObj->fromFlag == 2) {
                        $whatIsIt = whatIsIt($dailyEntryDebtor->accountstreeid);
                        $element = $accountsTreeDAO->load($dailyEntryDebtor->accountstreeid);
                        if (!isset($dailyEntryDebtor->pluginid) || empty($dailyEntryDebtor->pluginid)) {
                            $dailyEntryDebtor->pluginid = $dailyEntryId;
                        }
                        affectPlugin($whatIsIt, $dailyEntryDebtor->value, $dailyEntryDebtor->pluginid, $operation, $element->name, $dailyEntryDebtor->pluginComment, $dailyEntryDebtor->pluginControllerName, $dailyEntryDebtor->costcenterid, $dailyEntryDebtor->accountstreeid, 0, $dailyEntryObj, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
                    }
                }
            }
            foreach ($dailyEntryCreditorArray as $dailyEntryCreditor) {
                if (!empty($dailyEntryCreditor->accountstreeid) && !empty($dailyEntryCreditor->value)) {
                    $dailyEntryCreditor->dailyentryid = $dailyEntryId;
                    if (empty($dailyEntryCreditor->dComment)) {
                        $dailyEntryCreditor->dComment = '';
                    }
                    if ($dailyEntryCreditor->costcenterid == '') {
                        $dailyEntryCreditor->costcenterid = 0;
                    } else {
                        insertCostCenterDetail($dailyEntryCreditor->costcenterid, $dailyEntryCreditor->value, $dailyEntryId, $dailyEntryCreditor->pluginComment, $dailyEntryCreditor->pluginControllerName, $dailyEntryCreditor->costcenterType);
                    }
                    $dailyEntryCreditorDAO->insert($dailyEntryCreditor);
                    $operation = affectAccount($dailyEntryCreditor, 1);
                    if ($dailyEntryObj->fromFlag == 2) {
                        $whatIsIt = whatIsIt($dailyEntryCreditor->accountstreeid);
                        $element = $accountsTreeDAO->load($dailyEntryCreditor->accountstreeid);
                        if (!isset($dailyEntryCreditor->pluginid) || empty($dailyEntryCreditor->pluginid)) {
                            $dailyEntryCreditor->pluginid = $dailyEntryId;
                        }
                        affectPlugin($whatIsIt, $dailyEntryCreditor->value, $dailyEntryCreditor->pluginid, $operation, $element->name, $dailyEntryCreditor->pluginComment, $dailyEntryCreditor->pluginControllerName, $dailyEntryCreditor->costcenterid, $dailyEntryCreditor->accountstreeid, 1, $dailyEntryObj, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
                    }
                }
            }

            if ($stopEntryTransaction == 0) {//use transaction
                $transactions->commit();
            }
            $flag = 1;
            $message = 'تمت العملية بنجاح';
        } catch (Exception $e) {
            echo $e;
            if ($stopEntryTransaction == 0) {//use transaction
                $transactions->rollback();
            }
            $flag = -2;
            print_r($e);
            $message = 'عفوا لقد حدث خطأ';
        }
    } else {
        $flag = -1;
        $dailyEntryId = 0;
        $message = 'لابد ان يكون مجموع مدين يساوى مجموع دائن وان لا يكون هذا المجموع  يساوى صفر';
    }
    return array($flag, $dailyEntryId);
}

/* -----------------------------------------------------------------------------
  ##this function is used to reverse the whole daily entry
  ##it require 1 input which is the id of entry

  #second one is $stopEntryTransaction it takes default value = 0 means use transaction, value = 1 means stop useing transations this is used in case that insertEntery() is part of function that uses transations already to stop nested transactions
  as in mysql comit and rollback End any transaction in session even if they are many transactions
 *
  ##function returns
  1 : sucess
  -1:'عفوا لقد حدث خطأ'

  +
  --------------------------------------------------------------------------- */

function reverseEntryWithItsID($id, $stopEntryTransaction = 0) {
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;

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

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

    global $accountsTreeDAO;
    if (isset($id) && $id > 0) {

        if ($stopEntryTransaction == 0) {//use transaction
            //Transaction
            $transactions = new Transaction();
        }


        //get data to reverse
        $olddailyEntry = $dailyEntryDAO->load($id);
        $newentryId = 0;
        $dailyEntryId = 0;
        try {
            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 = -9 : it means that i was reversed manually not with my function but want to appear reversed
                //reverseofid = 0 : it means an entry not a reversed or reverse of another
                $dailyEntryId = $olddailyEntry->id;
                $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->fromFlag = $olddailyEntry->fromFlag;
                $dailyEntry->dDateTime = date('Y-m-d H:i:s');
                $dailyEntry->userid = $_SESSION['userid'];
                $dailyEntry->branchid = $_SESSION['branchId'];

                $dailyEntry->condition = 0;
                $dailyEntry->reverseofid = $olddailyEntry->id;
                $dailyEntry->entryComment = 'تم عكس القيد رقم ' . $olddailyEntry->id . ' ';
                $dailyEntry->related = $olddailyEntry->related;
                $newentryId = $dailyEntryDAO->insert($dailyEntry);

                foreach ($AllDailyEntryDebtor as $debtor) {
                    $dailyEntryCreditor->accountstreeid = $debtor->accountstreeid;
                    $dailyEntryCreditor->dailyentryid = $newentryId;
                    $dailyEntryCreditor->value = $debtor->value;
                    $dailyEntryCreditor->dComment = $debtor->dComment;
                    if ($dailyEntryCreditor->costcenterid == '') {
                        $dailyEntryCreditor->costcenterid = 0;
                    } else {
                        insertCostCenterDetail($dailyEntryCreditor->costcenterid, $dailyEntryCreditor->value, $newentryId, $dailyEntryCreditor->pluginComment, $dailyEntryCreditor->pluginControllerName, $dailyEntryCreditor->costcenterType);
                    }
                    $dailyEntryCreditorDAO->insert($dailyEntryCreditor);
                    $operation = affectAccount($dailyEntryCreditor, 1);
                    if ($dailyEntry->fromFlag == 2) {
                        $whatIsIt = whatIsIt($dailyEntryCreditor->accountstreeid);
                        $element = $accountsTreeDAO->load($dailyEntryCreditor->accountstreeid);
                        if (!isset($dailyEntryCreditor->pluginid) || empty($dailyEntryCreditor->pluginid)) {
                            $dailyEntryCreditor->pluginid = $dailyEntryId;
                        }
                        affectPlugin($whatIsIt, $dailyEntryCreditor->value, $dailyEntryCreditor->pluginid, $operation, $element->name, $dailyEntryCreditor->pluginComment, $dailyEntryCreditor->pluginControllerName, $dailyEntryCreditor->costcenterid, $dailyEntryCreditor->accountstreeid, 1, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
                    }
                }
                foreach ($AllDailyEntryCreditor as $credit) {
                    $dailyEntryDebtor->accountstreeid = $credit->accountstreeid;
                    $dailyEntryDebtor->dailyentryid = $newentryId;
                    $dailyEntryDebtor->value = $credit->value;
                    $dailyEntryDebtor->dComment = $credit->dComment;
                    if ($dailyEntryDebtor->costcenterid == '') {
                        $dailyEntryDebtor->costcenterid = 0;
                    } else {
                        insertCostCenterDetail($dailyEntryDebtor->costcenterid, $dailyEntryDebtor->value, $newentryId, $dailyEntryDebtor->pluginComment, $dailyEntryDebtor->pluginControllerName, $dailyEntryDebtor->costcenterType);
                    }
                    $dailyEntryDebtorDAO->insert($dailyEntryDebtor);

                    $operation = affectAccount($dailyEntryDebtor, 0);
                    if ($dailyEntry->fromFlag == 2) {
                        $whatIsIt = whatIsIt($dailyEntryDebtor->accountstreeid);
                        $element = $accountsTreeDAO->load($dailyEntryDebtor->accountstreeid);
                        if (!isset($dailyEntryDebtor->pluginid) || empty($dailyEntryDebtor->pluginid)) {
                            $dailyEntryDebtor->pluginid = $dailyEntryId;
                        }
                        affectPlugin($whatIsIt, $dailyEntryDebtor->value, $dailyEntryDebtor->pluginid, $operation, $element->name, $dailyEntryDebtor->pluginComment, $dailyEntryDebtor->pluginControllerName, $dailyEntryDebtor->costcenterid, $dailyEntryDebtor->accountstreeid, 0, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
                    }
                }
            }
            if ($stopEntryTransaction == 0) {//use transaction
                $transactions->commit();
            }
            $flag = 1;
        } catch (Exception $e) {
            if ($stopEntryTransaction == 0) {//use transaction
                $transactions->rollback();
            }
            $flag = -1;
        }
        return array($flag, $newentryId);
    }
}

/* -----------------------------------------------------------------------------
  ##this function is used to reverse the whole daily entry
  ##it require 1 input which is the comment of entry
  #second one is $stopEntryTransaction it takes default value = 0 means use transaction, value = 1 means stop useing transations this is used in case that insertEntery() is part of function that uses transations already to stop nested transactions
  as in mysql comit and rollback End any transaction in session even if they are many transactions

  ##function returns
  1 : sucess
  2 : sucess لكن هذا التعليق موجود اكثر من مرة وخدنا اخر نتيجة وعكسناها
  -1:'عفوا لقد حدث خطأ'
  -2:'لا يوجد عناصر تحتوى على هذا التعليق'

  +
  --------------------------------------------------------------------------- */

function reverseEntryWithItsComment($comment, $stopEntryTransaction = 0) {
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;

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

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

    global $accountsTreeDAO;

    if ($stopEntryTransaction == 0) {//use transaction
        //Transaction
        $transactions = new Transaction();
    }

    $newentryId = 0;
    $result = $dailyEntryEX->queryByEntryComment($comment);
    if (count($result) > 0) {
        $id = $result[0]->id;
        //get data to reverse
        $olddailyEntry = $dailyEntryDAO->load($id);
        try {
            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->fromFlag = $olddailyEntry->fromFlag;
                $dailyEntry->thedate = date('Y-m-d');
                $dailyEntry->dDateTime = date('Y-m-d H:i:s');
                $dailyEntry->userid = $_SESSION['userid'];
                $dailyEntry->condition = 0;
                $dailyEntry->reverseofid = $olddailyEntry->id;
                $dailyEntry->entryComment = 'تم عكس القيد رقم ' . $olddailyEntry->id . ' ';
                $dailyEntry->branchid = $_SESSION['branchId'];
                $dailyEntry->related = $olddailyEntry->related;
                $newentryId = $dailyEntryDAO->insert($dailyEntry);

                foreach ($AllDailyEntryDebtor as $debtor) {
                    $dailyEntryCreditor->accountstreeid = $debtor->accountstreeid;
                    $dailyEntryCreditor->dailyentryid = $newentryId;
                    $dailyEntryCreditor->value = $debtor->value;
                    $dailyEntryCreditor->dComment = $debtor->dComment;
                    if ($dailyEntryCreditor->costcenterid == '') {
                        $dailyEntryCreditor->costcenterid = 0;
                    } else {
                        insertCostCenterDetail($dailyEntryCreditor->costcenterid, $dailyEntryCreditor->value, $newentryId, $dailyEntryCreditor->pluginComment, $dailyEntryCreditor->pluginControllerName, $dailyEntryCreditor->costcenterType);
                    }
                    $dailyEntryCreditorDAO->insert($dailyEntryCreditor);

                    $operation = affectAccount($dailyEntryCreditor, 1);
                    if ($dailyEntry->fromFlag == 2) {
                        $whatIsIt = whatIsIt($dailyEntryCreditor->accountstreeid);
                        $element = $accountsTreeDAO->load($dailyEntryCreditor->accountstreeid);
                        if (!isset($dailyEntryCreditor->pluginid) || empty($dailyEntryCreditor->pluginid)) {
                            $dailyEntryCreditor->pluginid = $dailyEntryId;
                        }
                        affectPlugin($whatIsIt, $dailyEntryCreditor->value, $dailyEntryCreditor->pluginid, $operation, $element->name, $dailyEntryCreditor->pluginComment, $dailyEntryCreditor->pluginControllerName, $dailyEntryCreditor->costcenterid, $dailyEntryCreditor->accountstreeid, 1, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
                    }
                }
                foreach ($AllDailyEntryCreditor as $credit) {
                    $dailyEntryDebtor->accountstreeid = $credit->accountstreeid;
                    $dailyEntryDebtor->dailyentryid = $newentryId;
                    $dailyEntryDebtor->value = $credit->value;
                    $dailyEntryDebtor->dComment = $credit->dComment;
                    if ($dailyEntryDebtor->costcenterid == '') {
                        $dailyEntryDebtor->costcenterid = 0;
                    } else {
                        insertCostCenterDetail($dailyEntryDebtor->costcenterid, $dailyEntryDebtor->value, $newentryId, $dailyEntryDebtor->pluginComment, $dailyEntryDebtor->pluginControllerName, $dailyEntryDebtor->costcenterType);
                    }
                    $dailyEntryDebtorDAO->insert($dailyEntryDebtor);

                    $operation = affectAccount($dailyEntryDebtor, 0);
                    if ($dailyEntry->fromFlag == 2) {
                        $whatIsIt = whatIsIt($dailyEntryDebtor->accountstreeid);
                        $element = $accountsTreeDAO->load($dailyEntryDebtor->accountstreeid);
                        if (!isset($dailyEntryDebtor->pluginid) || empty($dailyEntryDebtor->pluginid)) {
                            $dailyEntryDebtor->pluginid = $dailyEntryId;
                        }
                        affectPlugin($whatIsIt, $dailyEntryDebtor->value, $dailyEntryDebtor->pluginid, $operation, $element->name, $dailyEntryDebtor->pluginComment, $dailyEntryDebtor->pluginControllerName, $dailyEntryDebtor->costcenterid, $dailyEntryDebtor->accountstreeid, 0, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
                    }
                }
            }

            if ($stopEntryTransaction == 0) {//use transaction
                $transactions->commit();
            }


            if (count($result) == 1) {
                $flag = 1;
            }
            if (count($result) > 1) {
                $flag = 2;
            }
        } catch (Exception $e) {
            if ($stopEntryTransaction == 0) {//use transaction
                $transactions->rollback();
            }
            return -1;
        }
    } else {
        $flag = -2;
    }

    return array($flag, $newentryId);
}

function getTotal($myArr) {
    $total = 0;
    foreach ($myArr as $obj) {
        if (!empty($obj->accountstreeid) && !empty($obj->value)) {
            $total += $obj->value;
        }
    }

    return round($total, 3);
}

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

    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 insertCostCenterDetail($Costcenterid, $val, $dailyentryid, $comment, $controllerName, $costCenterType = -1) {

    global $Costcenterdetail;
    global $CostcenterdetailDAO;

    $Costcenterdetail->costamount = $val;
    $Costcenterdetail->costcenterid = $Costcenterid;
    $Costcenterdetail->costdate = date('Y-m-d');
    $Costcenterdetail->del = 0;
    $Costcenterdetail->modelid = $dailyentryid;
    $Costcenterdetail->processname = $comment;
    $Costcenterdetail->tablename = $controllerName;
    $Costcenterdetail->type = $costCenterType;
    $Costcenterdetail->uesrid = $_SESSION['userid'];

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

function getCostCenterType($controllerName) {
    $costCenterType = -1;
    //no need to consider sellbill and its type to val 11
    switch ($controllerName) {
        case "expenseexchange.php":
            $costCenterType = 12;
            break;
        case "bindsettlement.php":
            $costCenterType = 13;
            break;

        default:
            break;
    }
}

?>