<?php

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

//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
//Transaction
include_once("../models/sql/Transaction.class.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');
//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');

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

//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

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

//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();
//Accountstreesetting
$accountsTreeSetting = new Accountstreesetting();
$accountsTreeSettingDAO = new AccountstreesettingMySqlDAO();
$accountsTreeSettingEX = new AccountstreesettingMySqlExtDAO();

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

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


//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    ##
    // here the function that do the action
    $totalDebtor = 0;
    $totalCreditor = 0;
    $balanceArray = array();
    $sum = 0;

    //    $maxNoOfLevels = 1;
    //    getMaxNoOfLevels(0, 1);
    //    $levelSetting = array();
    ##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;
    }

    display_children(0, 0, 0, 0);  //display the tree
    $smarty->assign("totalDebtor", $totalDebtor);
    $smarty->assign("totalCreditor", $totalCreditor);
    $smarty->assign("balanceArray", $balanceArray);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //here the smarty templates
    $smarty->display("trialbalanceview/add.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->display("footer.html");

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

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;

    global $balanceArray;
    global $totalDebtor;
    global $totalCreditor;

    //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) {
                R::exec('update accountstree set layingOrder =' . $nodeNameWithZeros . ' where id= ' . $type->id);
                //                $type->layingOrder = $nodeNameWithZeros;
                //                $accountsTreeDAO->update($type);
            }
            //
            //            exportToExcel($type, $level);
            //
            $preString = '';
            for ($index = 0; $index < $level; $index++) {
                $preString .= '&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;';
            }
            $type->customName = $preString . '<strong>' . $nodeName . '</strong> ' . $type->customName;

            if (($type->accountNature == 0 && $type->theValue > 0) || ($type->accountNature == 1 && $type->theValue < 0)) {
                $totalDebtor += abs($type->theValue);
            }
            if (($type->accountNature == 1 && $type->theValue > 0) || ($type->accountNature == 0 && $type->theValue < 0)) {
                $totalCreditor += abs($type->theValue);
            }



            //check for expenses for this category
            $childDataCount = R::getCell('select count(*) as c from accountstree where parent = ' . $type->id);
            if ($childDataCount > 0) {
                $sum = 0;
                getTheTrueValue($type->id, $sum);
                $type->theValue = $sum;
            }
            //get debt,credit val of sum as they are hidden
            if (($_COOKIE['showClientsAtTree'] == 0 && ($type->id == 58 || $type->id == 60)) || ($_COOKIE['showSuppliersAtTree'] == 0 && ($type->id == 81 || $type->id == 87))) {
                if (($type->accountNature == 0 && $type->theValue > 0) || ($type->accountNature == 1 && $type->theValue < 0)) {
                    $totalDebtor += abs($type->theValue);
                }
                if (($type->accountNature == 1 && $type->theValue > 0) || ($type->accountNature == 0 && $type->theValue < 0)) {
                    $totalCreditor += abs($type->theValue);
                }
            }
            $i++;

            array_push($balanceArray, $type);

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


    return $outputString;
}

function display_childrenOld($parent, $level, $itr, $itr2) { //$itr is itr without zeros  , $itr2 wit zeros
    global $accountsTreeDAO;
    global $accountsTreeEX;
    global $accountsTreeSettingDAO;
    global $balanceArray;
    global $sum;
    global $totalDebtor;
    global $totalCreditor;
    global $levelSetting;
    global $maxNoOfLevels;

    // retrieve all children of $parent

    $result = $accountsTreeEX->queryByParentExt($parent);
    if (count($result) > 0) {
        // display each child
        $myDigits = $accountsTreeSettingDAO->queryByLevelno(($level + 1));
        $myDigits = $myDigits[0];
        $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);
            }
            //
            $preString = '';
            for ($index = 0; $index < $level; $index++) {
                $preString .= '&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;';
            }

            $type->customName = $preString . '<strong>' . $nodeName . '</strong> ' . $type->name;

            if ($type->theValue > 0) {
                $totalDebtor += $type->theValue;
            }
            if ($type->theValue < 0) {
                $totalCreditor += $type->theValue;
            }


            //check for expenses for this category
            $childData = $accountsTreeDAO->queryByParent($type->id);
            if (count($childData) > 0) {
                $sum = 0;
                getTheTrueValue($type->id, $sum);
                $type->theValue = $sum;
            }
            $i++;

            array_push($balanceArray, $type);

            if (count($childData) > 0) {
                display_children($type->id, $level + 1, $nodeName, $nodeNameWithZeros);
            }
        }
    }


    return $outputString;
}

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) {
    } else {
        $result = R::getAll('select id,theValue from accountstree where parent = ' . $parent);
        foreach ($result as $type) {
            $sum += $type['theValue'];
            getTheTrueValue($type['id'], $sum);
        }
    }
}
