<?php

// get the config file
include_once("../public/config.php");
include_once("dailyentryfun.php");
//here the db files that include in the file
include("../public/include_dao.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');
//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');
//Accountstreesetting
require_once('../models/dao/AccountstreesettingDAO.class.php');
require_once('../models/dto/Accountstreesetting.class.php');
require_once('../models/mysql/AccountstreesettingMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountstreesettingMySqlExtDAO.class.php');
//----------------------------------------
//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');
//Returnsellbill
require_once('../models/dao/ReturnsellbillDAO.class.php');
require_once('../models/dto/Returnsellbill.class.php');
require_once('../models/mysql/ReturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillMySqlExtDAO.class.php');
//Sellbillandrutern
require_once('../models/dao/SellbillandruternDAO.class.php');
require_once('../models/dto/Sellbillandrutern.class.php');
require_once('../models/mysql/SellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruternMySqlExtDAO.class.php');
//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');
//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//get the do the action
$do = $_GET['do'];

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

  Controller Name :- clientTypeCTRL

  OPERTATION in Controller

  1-
  2-
  3-
  4-

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


//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();
//Accountstreesetting
$accountsTreeSetting = new Accountstreesetting();
$accountsTreeSettingDAO = new AccountstreesettingMySqlDAO();
$accountsTreeSettingEX = new AccountstreesettingMySqlExtDAO();
//---------------------------------------------------------
//Sellbill
$sellBill = new Sellbill();
$sellBillDAO = new SellbillMySqlDAO();
$sellBillEX = new SellbillMySqlExtDAO();
//Returnsellbill
$returnSellBill = new Returnsellbill();
$returnSellBillDAO = new ReturnsellbillMySqlDAO();
$returnSellBillEX = new ReturnsellbillMySqlExtDAO();
//Sellbillandrutern
$sellBillAndRutern = new Sellbillandrutern();
$sellBillAndRuternDAO = new SellbillandruternMySqlDAO();
$sellBillAndRuternEX = new SellbillandruternMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailEX = new StoredetailMySqlExtDAO();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productEX = new ProductMySqlExtDAO();
//Store
$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();

//check and use the condetion that suite this action
if ($do == "getalltree") {
    //$accountsTree = $accountsTreeDAO->queryAll();
    //$accountsTreeOrdered = array();
    //orderAsTree(0, 0);
    //
    //
    //
    ##make no of levels fixed =6 "now we dont count tree levels"
//    $maxNoOfLevels = 6;
//    for ($i = 1; $i <= $maxNoOfLevels; $i++) {
//        $level = $accountsTreeSettingDAO->queryByLevelno($i);
//        if (count($level) < 1) {
//            $accountsTreeSetting->levelno = $i;
//            $accountsTreeSetting->nooffields = 1;
//            $id = $accountsTreeSettingDAO->insert($accountsTreeSetting);
//            $level = $accountsTreeSettingDAO->load($id);
//        } else {
//            $level = $level[0];
//        }
//        //array_push($levelSetting, $level);
//        if ($level->nooffields > 0)
//            $levelSetting[$i] = $level;
//    }
//    $maxNoOfLevels = count($levelSetting);

    $accountsTreeOrdered = $accountsTreeEX->getlayingOrder4('', ''); //getlayingOrder2
    $myhtml = '<option value="0"> لا يوجد</option>';
    foreach ($accountsTreeOrdered as $element) {

//        //getting level using element parcode
//        $noOfFileds = 0;
//        $i = $maxNoOfLevels;
//        do {
//            $layingOrder = $element->layingOrder;
//            $noOfFileds += $levelSetting[$i]->nooffields;
//            $layingOrder = substr($layingOrder, $noOfFileds * -1);
//            if ((int) $layingOrder > 0) {
//                $element->notes = $levelSetting[$i]->levelno;
//            }
//            $i--;
//        } while ($i > 0 && (int) $layingOrder == 0);
        //draw level as dashes
        $preString = '';
        for ($index = 0; $index < $element->notes; $index++) {
            $preString .= '_';
        }
        $myhtml .= '<option value="' . $element->id . '">' . $preString . $element->layingOrder . ' ' . $element->name . '</option>';
    }
    echo $myhtml;
} elseif ($do == "additem") {

    $itemIdModal = filter_input(INPUT_POST, 'itemIdModal');
    $name = filter_input(INPUT_POST, 'itemName');
    $parent = filter_input(INPUT_POST, 'parent');
    $itemtype = filter_input(INPUT_POST, 'itemtype');
    //$itemfrom = filter_input(INPUT_POST, 'itemfrom');
    $notes = filter_input(INPUT_POST, 'notes');
    $itemtype2 = filter_input(INPUT_POST, 'itemtype2');

    $theValue = filter_input(INPUT_POST, 'theValue');
    if (!isset($theValue) || empty($theValue)) {
        $theValue = 0;
    }

    $reportid = (int) filter_input(INPUT_POST, 'reportid');
    $listid = (int) filter_input(INPUT_POST, 'listid');
    $accountNature = (int) filter_input(INPUT_POST, 'accountNature');

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

    $accountsTreeDB;
    if (!empty($itemIdModal)) {
        $accountsTreeDB = $accountsTreeDAO->load($itemIdModal);
    }

    if (count($accountsTreeDB) == 1) {
        if ($accountsTreeDB->itemfrom == 0) {
            //من البرنامج
            //مسموح بتعديل الاسم فقط
            $accountsTree = $accountsTreeDB;
            $accountsTree->customName = $name;
            $accountsTree->reportid = $reportid; //
        } elseif ($accountsTreeDB->itemfrom == 1) {
            //من الشجرة عدل اللى عاوزه//ماعدا ده
            //$accountsTree->itemfrom = $accountsTreeDB->itemfrom;//i will not change it
            $accountsTree = $accountsTreeDB;

            $accountsTree->customName = $name;
            $accountsTree->parent = $parent;
            $accountsTree->itemtype = $itemtype;
            $accountsTree->itemtype2 = $itemtype2;
            $accountsTree->notes = $notes;
            $accountsTree->theValue = $theValue;
            $accountsTree->reportid = $reportid;
            $accountsTree->accountNature = $accountNature;
            $accountsTree->listId = $listid;
            $accountsTree->accountNature = $accountNature;
        }

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

        $id = $itemIdModal;
        //check if name is unique
        $check = isUniqueNameEdit($name, $parent);
        if ($check == TRUE) {
            $accountsTreeDAO->update($accountsTree);
        } else {
            $id = -10;
        }
    } else {
        ##insert//if (!isset($itemIdModal) || empty($itemIdModal))
        $accountsTree->customName = $name;
        $accountsTree->name = $name;
        $accountsTree->parent = $parent;
        $accountsTree->itemtype = $itemtype;
        $accountsTree->itemtype2 = $itemtype2;
        $accountsTree->notes = $notes;
        $accountsTree->theOrder = 0;
        $accountsTree->layingOrder = '';
        $accountsTree->del = 0;
        $accountsTree->theValue = $theValue;
        $accountsTree->userid = $_SESSION['userid'];
        $accountsTree->sysdate = date("Y-m-d H:i:s");
        $accountsTree->itemfrom = 1; //any add here is from tree only
        $accountsTree->reportid = $reportid;
        $accountsTree->listId = $listid;
        $accountsTree->accountNature = $accountNature;
        //check if name is unique
        $check = isUniqueName($name, $parent);
        if ($check == TRUE) {
            $id = $accountsTreeDAO->insert($accountsTree);
        } else {
            $id = -10;
        }
    }

    echo $id;
} elseif ($do == "gettypeandlist") {
    $id = filter_input(INPUT_POST, "id");
    $accountsTree = $accountsTreeDAO->load($id);
    echo $accountsTree->itemtype . ',' . $accountsTree->listId;
} elseif ($do == "redrawtree") {

    // here the function that do the action
    ##make no of levels fixed =6 "now we dont count tree levels"
    $maxNoOfLevels = 6;
    for ($i = 1; $i <= $maxNoOfLevels; $i++) {
        $level = $accountsTreeSettingDAO->queryByLevelno($i);
        if (count($level) < 1) {
            $accountsTreeSetting->levelno = $i;
            $accountsTreeSetting->nooffields = 1;
            $id = $accountsTreeSettingDAO->insert($accountsTreeSetting);
            $level = $accountsTreeSettingDAO->load($id);
        } else {
            $level = $level[0];
        }
        //array_push($levelSetting, $level);
        $levelSetting[$i] = $level;
    }


    $sum = 0;
    $outputString = display_children(0, 0, 0, 0);  //display the tree
    echo $outputString;
} elseif ($do == "getitem") {
    $id = filter_input(INPUT_POST, 'id');
    $accountsTree = $accountsTreeDAO->load($id);
    echo json_encode($accountsTree);
} elseif ($do == "delthis") {
    $id = filter_input(INPUT_POST, 'id');
    $child = $accountsTreeEX->queryByParentExt($id);
    if (count($child) < 1) {
        //del
        //$accountsTreeDAO->delete($id);

        $row = $accountsTreeDAO->load($id);
        $row->del = 1;
        $accountsTreeDAO->update($row);

        echo 0;
    } else {
        echo 1;
    }
} elseif ($do == "getdetail") {
    $id = filter_input(INPUT_POST, "id");
    $shape = filter_input(INPUT_POST, "shape");
    if (empty($shape) || !isset($shape)) {
        $shape = 0;
    }
    $accountsTree = $accountsTreeDAO->load($id);
    $childData = $accountsTreeDAO->queryByParent($id);
    if (count($childData) > 0 && $type->itemtype2 == 0) {
        $cildrenIds = getChilds($id);
        $cildrenIds = rtrim($cildrenIds, ",");
        DrawTableByAccount($cildrenIds, $shape, $id, 0);
    } else {
        DrawTableByAccount($id, $shape, $id, 0);
    }
} elseif ($do == "getdetaillimited") {
    $id = filter_input(INPUT_POST, "id");
    $lastId = filter_input(INPUT_POST, "lastId");
    $shape = filter_input(INPUT_POST, "shape");
    if (empty($shape) || !isset($shape)) {
        $shape = 0;
    }
    $accountsTree = $accountsTreeDAO->load($id);
    $childData = $accountsTreeDAO->queryByParent($id);
    if (count($childData) > 0 && $type->itemtype2 == 0) {
        $cildrenIds = getChilds($id);
        $cildrenIds = rtrim($cildrenIds, ",");
        DrawTableByAccount($cildrenIds, $shape, $id, $lastId);
    } else {
        DrawTableByAccount($id, $shape, $id, $lastId);
    }
} elseif ($do == "reorder") {
    $id = filter_input(INPUT_POST, "id");
    $neworder = filter_input(INPUT_POST, "neworder");

    $accountsTree = $accountsTreeDAO->load($id);
    if (count($accountsTree) > 0) {
        $accountsTree->theOrder = $neworder;
        $accountsTreeDAO->update($accountsTree);
        echo 1;
    }
} elseif ($do == "getstartgoodsval") {
    $flag = checkStartGoods();
    if ($flag == 1) {
        $startGoodsVal = getStartGoodsVal();
        echo $startGoodsVal;
    }
} elseif ($do == "approveasstartgoods") {
    $flag = checkStartGoods();
    if ($flag == 1) {
        $startGoodsVal = getStartGoodsVal();
        $accountsTree = $accountsTreeDAO->load(27);
        $accountsTree->theValue = $startGoodsVal;
        $accountsTreeDAO->update($accountsTree);
    }
} elseif ($do == "resetfromprog") {
    resetfromprog();
}

//******************    Functions    ************************//

function DrawTableByAccount($id, $shape, $accountsTreeId, $lastEntryId) {
    global $smarty;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;
    global $accountsTreeDAO;

    global $allDailyEntery;

    $queryStringCreditor = ' where dailyentrycreditor.accountstreeid in( ' . $id . ') ';
    $queryStringDebtor = ' where dailyentrydebtor.accountstreeid in( ' . $id . ') ';


    $allDailyEntery = array();
    $TShapeArrDebtor = array();
    $TShapeArrCerditor = array();
    //prepare ids
    $allDailyEnteryIDs = $dailyEntryEX->queryAllEXTreeSimpleUnion($queryStringDebtor, $queryStringCreditor, " and id > $lastEntryId");
    /* $allDailyEnteryDebtor = $dailyEntryEX->queryAllEXDebtorTreeSimple($queryStringDebtor);
      $allDailyEnteryCreditor = $dailyEntryEX->queryAllEXCreditorTreeSimple($queryStringCreditor);
      $IDS = '';
      foreach ($allDailyEnteryDebtor as $value) {
      $IDS .= $value->id . ",";
      }

      foreach ($allDailyEnteryCreditor as $value) {
      $IDS .= $value->id . ",";
      } */
    $IDS = '';
    foreach ($allDailyEnteryIDs as $value) {
        $IDS .= $value->id . ",";
    }
    $IDS = rtrim($IDS, ",");
    if ($IDS == "") {
        $IDS = 0;
    }
    $queryString = ' where dailyentry.id in( ' . $IDS . ') ';
    $queryString2 = ' and accountstree.id in( ' . $id . ') ';
    $whereClause = ' where 1 ';
    ###########
    //1-get main items
    $mainItem = $dailyEntryEX->queryAllEXDebtorTreeMain($queryString, $queryString2);
    foreach ($mainItem as $myItem) {
        $queryString3 = ' and accountstree.id not in( ' . $id . ' ) and dailyentry.id in( ' . $myItem->id . ' ) ';
        //2-get count of his brother
        $itemBro = $dailyEntryEX->queryAllEXDebtorTreeMainBroCount($whereClause, $queryString3);
        $itemBroCount = count($itemBro) + 1;
        //3-get other type to show
        $result = $dailyEntryEX->queryAllEXCreditorTreeReverseType($queryString3);
        $resultCount = count($itemBroCount);
        if ($itemBroCount == 1 && $resultCount >= 1) {
            foreach ($result as $value) {
                if ($shape == 1) {
                    array_push($TShapeArrDebtor, $value);
                } else {
                    array_push($allDailyEntery, $value);
                }
            }
        } elseif ($itemBroCount > 1 && $resultCount == 1) {
            $result[0]->value = $myItem->value;

            if ($shape == 1) {
                array_push($TShapeArrDebtor, $result[0]);
            } else {
                array_push($allDailyEntery, $result[0]);
            }
        } elseif ($itemBroCount > 1 && $resultCount > 1) {
            $result[0]->accountstreeName = "مذكورين";
            $result[0]->value = $myItem->value;
            if ($shape == 1) {
                array_push($TShapeArrCerditor, $result[0]);
            } else {
                array_push($allDailyEntery, $result[0]);
            }
        }
    }

    ###########
    //1-get main items
    $mainItem = $dailyEntryEX->queryAllEXCreditorTreeMain($queryString, $queryString2);
    foreach ($mainItem as $myItem) {
        $queryString3 = ' and accountstree.id not in( ' . $id . ' ) and dailyentry.id in ( ' . $myItem->id . ') ';
        //2-get count of his brother
        $itemBro = $dailyEntryEX->queryAllEXCreditorTreeMainBroCount($whereClause, $queryString3);
        $itemBroCount = count($itemBro) + 1;
        //3-get other type to show
        $result = $dailyEntryEX->queryAllEXDebtorTreeReverseType($queryString3);
        $resultCount = count($result);
        if ($itemBroCount == 1 && $resultCount >= 1) {
            foreach ($result as $value) {
                if ($shape == 1) {
                    array_push($TShapeArrCerditor, $value);
                } else {
                    array_push($allDailyEntery, $value);
                }
            }
        } elseif ($itemBroCount > 1 && $resultCount == 1) {
            $result[0]->value = $myItem->value;
            if ($shape == 1) {
                array_push($TShapeArrCerditor, $result[0]);
            } else {
                array_push($allDailyEntery, $result[0]);
            }
        } elseif ($itemBroCount > 1 && $resultCount > 1) {
            $result[0]->accountstreeName = "مذكورين";
            $result[0]->value = $myItem->value;
            if ($shape == 1) {
                array_push($TShapeArrCerditor, $result[0]);
            } else {
                array_push($allDailyEntery, $result[0]);
            }
        }
    }


    $entry = $accountsTreeDAO->load($accountsTreeId);
    $smarty->assign("entry", $entry);
    if ($shape == 0) {
        sortById('asc');
    } elseif ($shape == 1) {

        $dailyEntry = new Dailyentry();
        $debtorItr = 0;
        $creditorItr = 0;
        $realCount = 0;
        $totalCount = count($TShapeArrDebtor) + count($TShapeArrCerditor);

        for ($i = 0; $i < ($totalCount * 2); $i++) {
            if (empty($TShapeArrDebtor[$debtorItr]) && empty($TShapeArrCerditor[$creditorItr])) {
                //do nothing
            } else {
                $realCount++;
                if ($i % 2 == 0) {
                    if (empty($TShapeArrDebtor[$debtorItr])) {
                        array_push($allDailyEntery, $dailyEntry);
                    } else {
                        array_push($allDailyEntery, $TShapeArrDebtor[$debtorItr]);
                        $debtorItr++;
                    }
                } else {
                    if (empty($TShapeArrCerditor[$creditorItr])) {
                        array_push($allDailyEntery, $dailyEntry);
                    } else {
                        array_push($allDailyEntery, $TShapeArrCerditor[$creditorItr]);
                        $creditorItr++;
                    }
                }
            }
        }

        $smarty->assign("realCount", $realCount);
    }
    $smarty->assign("shape", $shape);
    $smarty->assign("allDailyEntery", $allDailyEntery);
    $smarty->assign("allDailyEnteryCount", count($allDailyEntery));
    if ($lastEntryId == 0)
        $smarty->display("dailyentryview/accounttreetable.html");
    else
        $smarty->display("dailyentryview/accounttreetablePart.html");
}

function display_children($parent, $level, $itr, $itr2) {//$itr is itr without zeros  , $itr2 wit zeros
    global $accountsTreeDAO;
    global $accountsTreeEX;
    global $accountsTreeSettingDAO;
    global $outputString;
    global $sum;
    global $levelSetting;
    global $maxNoOfLevels;

    //note: url of tree ##http://jsfiddle.net/jhfrench/GpdgF/
    // retrieve all children of $parent

    $result = $accountsTreeEX->queryByParentExt($parent);
    if (count($result) > 0) {
        // display each child
        $i = 1;
        foreach ($result as $type) {
            //generte laying order  "use a method from the two coming"
            $preDigits = '';
            if (strlen($i) != $levelSetting[($level + 1)]->nooffields) {
                $noDigitsLeft = $levelSetting[($level + 1)]->nooffields - strlen($i);
                for ($j = 0; $j < $noDigitsLeft; $j++) {
                    $preDigits .= '0';
                }
            }

            if ($itr == 0) {
                $nodeName = $preDigits . $i; //. $type->id;
            } else {
                $nodeName = $itr . $preDigits . $i; //. $type->id;
            }
            //fill remaining with zeros to the right // optional
            $nodeNameWithZeros = $nodeName;
//            for ($ii = ($level + 2); $ii <= $maxNoOfLevels; $ii++) {
//                for ($j = 0; $j < $levelSetting[$ii]->nooffields; $j++) {
//                    $nodeNameWithZeros .= '0';
//                }
//            }
            //----------------------------------------------------------------
            //make sure node name is saved in db for searching purpose
            if ($nodeNameWithZeros !== $type->layingOrder) {
                $type->layingOrder = $nodeNameWithZeros;
                $accountsTreeDAO->update($type);
            }
            //check for expenses for this category
            $childData = $accountsTreeDAO->queryByParent($type->id);
            if (count($childData) > 0) {
                $sum = 0;
                getTheTrueValue($type->id, $sum);
                $type->theValue = $sum;
            }

            $outputString .= '<li>
									<span data-value="' . $type->id . '"><strong>' . $nodeNameWithZeros . '</strong> ' . $type->customName . '</span>

                                                                        <a class="btn btn-default" style="display: inline !important;padding: 5px 5px !important;" data-id="' . $type->id . '">' . $type->theValue . '</a>';
            if (($_COOKIE['showClientsAtTree'] == 0 && ($type->id == 58 || $type->id == 60)) || ($_COOKIE['showSuppliersAtTree'] == 0 && ($type->id == 81 || $type->id == 87))) {

            } else if (count($childData) > 0 && $type->itemtype2 == 0) {
                $outputString .= '<a class="btn btn-default bookicon infoLeaf" style="display: inline !important;width:8%;text-align: center !important;padding: 5px 13px !important;" data-id="' . $type->id . '"></a>';
            } else {
                $outputString .= '<a class="btn btn-default infoicon infoLeaf" style="display: inline !important;width:8%;text-align: center !important;padding: 5px 13px !important;" data-id="' . $type->id . '"></a>';
            }

            if ($type->itemfrom == 0) {

            } else {

                $outputString .= '<a class = "btn btn-default deleteicon  delLeaf" data-id = "' . $type->id . '" style = "display: inline !important;margin-right:-3px;width:8%;text-align: center !important;padding: 5px 13px !important;"></a>';
            }
            $outputString .= '<a class = "btn btn-default editicon editLeaf" style = "display: inline !important;width:8%;text-align: center !important;padding: 5px 13px !important;" data-id = "' . $type->id . '"></a>
                    <input type = "text" class = "form-control orderLeaf positiveNo" value = "' . $type->theOrder . '" data-id = "' . $type->id . '" style = "display: inline !important;margin-right:3px;width:16%;text-align: center !important;padding: 5px 13px !important;"/>';





            $i++;
            if (($_COOKIE['showClientsAtTree'] == 0 && ($type->id == 58 || $type->id == 60)) || ($_COOKIE['showSuppliersAtTree'] == 0 && ($type->id == 81 || $type->id == 87))) {
                //do noting.
            } else if (count($childData) > 0) {
                $outputString .= '<ul>';
                display_children($type->id, $level + 1, $nodeName, $nodeNameWithZeros);
                $outputString .= '</ul>';
            }
            $outputString .= '</li>';
        }
    }


    return $outputString;
}

function orderAsTree($parent, $level) {
    global $accountsTreeDAO;
    global $accountsTreeEX;
    global $accountsTreeOrdered;
    //global $outputString;
    // retrieve all children of $parent
    $result = $accountsTreeEX->queryByParentExt($parent);
    if (count($result) > 0) {
        // display each child

        foreach ($result as $type) {
            $type->notes = $level;
            array_push($accountsTreeOrdered, $type);
            orderAsTree($type->id, $level + 1);
        }
    }
}

function sortByDateTime($type) {
    global $allDailyEntery;

    //1-sort by date
    $membresCount = count($allDailyEntery) - 1; //-1 so as not to compare last item with null "reduce one itration"
    foreach ($allDailyEntery as $myalloutRole) {
        $tempMember;
        for ($i = 0; $i < $membresCount; $i++) {
            if ($type == "desc") {
                if ($allDailyEntery[$i]->dDateTime < $allDailyEntery[$i + 1]->dDateTime) {
                    $tempMember = $allDailyEntery[$i];
                    $allDailyEntery[$i] = $allDailyEntery[$i + 1];
                    $allDailyEntery[$i + 1] = $tempMember;
                }
            } elseif ($type == "asc") {
                if ($allDailyEntery[$i]->dDateTime > $allDailyEntery[$i + 1]->dDateTime) {
                    $tempMember = $allDailyEntery[$i + 1];
                    $allDailyEntery[$i + 1] = $allDailyEntery[$i];
                    $allDailyEntery[$i] = $tempMember;
                }
            }
        }
    }
}

function sortById($type) {
    global $allDailyEntery;

    //1-sort by date
    $membresCount = count($allDailyEntery) - 1; //-1 so as not to compare last item with null "reduce one itration"
    foreach ($allDailyEntery as $myalloutRole) {
        $tempMember;
        for ($i = 0; $i < $membresCount; $i++) {
            if ($type == "desc") {
                if ($allDailyEntery[$i]->id < $allDailyEntery[$i + 1]->id) {
                    $tempMember = $allDailyEntery[$i];
                    $allDailyEntery[$i] = $allDailyEntery[$i + 1];
                    $allDailyEntery[$i + 1] = $tempMember;
                }
            } elseif ($type == "asc") {
                if ($allDailyEntery[$i]->id > $allDailyEntery[$i + 1]->id) {
                    $tempMember = $allDailyEntery[$i + 1];
                    $allDailyEntery[$i + 1] = $allDailyEntery[$i];
                    $allDailyEntery[$i] = $tempMember;
                }
            }
        }
    }
}

function getTheTrueValue($parent, $sum) {
    global $accountsTreeDAO;
    global $accountsTreeEX;
    global $sum;

    if (($_COOKIE['showClientsAtTree'] == 0 && ($parent == 58 || $parent == 60)) || ($_COOKIE['showSuppliersAtTree'] == 0 && ($parent == 81 || $parent == 87))) {
        $lastNodeSum = (float) $accountsTreeEX->getLastNodeSumById($parent);
        $sum += $lastNodeSum;
    } else if ($_COOKIE['calTreeNodes'] == 1) {
        $result = $accountsTreeEX->queryByParentExt($parent);
        if (count($result) > 0) {
            foreach ($result as $type) {
                $sum += $type->theValue;
                getTheTrueValue($type->id, $sum);
            }
        }
    }
}

function getChilds($parent) {
    global $accountsTreeEX;
    global $cildrenIds;
    $result = $accountsTreeEX->queryByParentExt($parent);
    if (count($result) > 0) {

        foreach ($result as $type) {
            $cildrenIds .= $type->id . ',';
            getChilds($type->id);
        }
    }
    return $cildrenIds;
}

function resetfromprog($parent, $sum) {
    global $accountsTreeDAO;

    $data = $accountsTreeDAO->queryByItemfrom(0);
    foreach ($data as $value) {
        if ($value->customName != $value->name || $value->customNameEn != $value->nameEn) {
            $value->customName = $value->name;
            $value->customNameEn = $value->nameEn;
            $accountsTreeDAO->update($value);
        }
    }
}

//بضاعة اول المدة
function checkStartGoods() {
    //$sellBill
    global $sellBill;
    global $sellBillDAO;
    global $sellBillEX;
    //Returnsellbill
    global $returnSellBill;
    global $returnSellBillDAO;
    global $returnSellBillEX;
    //Sellbillandrutern
    global $sellBillAndRutern;
    global $sellBillAndRuternDAO;
    global $sellBillAndRuternEX;

    $flag = 0;

    $sellBill = $sellBillEX->checkIfThereIsABill();
    $returnSellBill = $returnSellBillEX->checkIfThereIsABill();
    $sellBillAndRutern = $sellBillAndRuternEX->checkIfThereIsABill();

    if (count($sellBill) == 0 && count($returnSellBill) == 0 && count($sellBillAndRutern) == 0) {
        $flag = 1;
    }
    return $flag;
}

function getStartGoodsVal() {
    //Storedetail
    global $storeDetailEX;

    $productsTotalValue = 0;
    $storeData = loadStore();
    foreach ($storeData as $value) {
        $products = $storeDetailEX->queryWithStoreId($value->storeId);
        foreach ($products as $pro) {
            $productsTotalValue += $pro->productquantity * $pro->productBuyPrice;
        }
    }
    $productsTotalValue = round($productsTotalValue, 2);
    return $productsTotalValue;
}

//select all store data
function loadStore() {
    //to use the variable out side the funcion
    global $storeDAO;

    //load all store data
    $storeData = $storeDAO->queryByConditions(0);
    return $storeData;
}

?>