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

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
//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();
//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

$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");
    ##

    $queryString = '';
    $accountsTreeId = filter_input(INPUT_POST, "generalledgerid");
    $datefrom = filter_input(INPUT_POST, "datefrom");
    $dateto = filter_input(INPUT_POST, "dateto");
    $shape = filter_input(INPUT_POST, "shape");
    if (empty($shape) || !isset($shape)) {
        $shape = 0;
    }

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

    if (empty($accountsTreeId)) {
        $accountsTreeId = -1;
    }

    //$accountsTree = $accountsTreeDAO->load($accountsTreeId);
    $childData = $accountsTreeDAO->queryByParent($accountsTreeId);
    if (count($childData) > 0 && $type->itemtype2 == 0) {
        $allDailyEntery;
        $cildrenIds = getChilds($accountsTreeId);
        $cildrenIds = rtrim($cildrenIds, ",");
        DrawTableByAccountNew($cildrenIds, $datefrom, $dateto, $shape, $accountsTreeId);
    }
    $smarty->assign("now", date('Y-m-d H:i:s'));

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //here the smarty templates
    $smarty->display("generalledgerview/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->assign("dailyentry", 1);

$smarty->display("footer.html");

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

function DrawTableByAccountNew($id, $startDate, $endDate, $shape, $accountsTreeId) {
    global $smarty;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;
    global $accountsTreeDAO;

    global $allDailyEntery;

    $queryString_date = '';
    if (isset($startDate) && !empty($startDate)) {
        $queryString_date .= ' and dailyentry.thedate >= "' . $startDate . '" ';
    }
    if (isset($endDate) && !empty($endDate)) {
        $queryString_date .= ' and dailyentry.thedate <= "' . $endDate . '" ';
    }

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



    $allDailyEntery = array();
    $TShapeArrDebtor = array();
    $TShapeArrCerditor = array();
    //prepare ids
    $dailyEntryIds = R::getAll('(   SELECT dailyentry.id
                                    FROM dailyentry
                                    join dailyentrydebtor on dailyentrydebtor.dailyentryid = dailyentry.id
                                   ' . $queryStringDebtor . '
                                )union(
                                    SELECT dailyentry.id
                                    FROM dailyentry
                                    join dailyentrycreditor on dailyentrycreditor.dailyentryid = dailyentry.id
                                    ' . $queryStringCreditor . ')');
    $IDS = '0,';
    foreach ($dailyEntryIds as $value) {
        $IDS .= $value['id'] . ",";
    }
    $IDS = rtrim($IDS, ",");

    $queryString = ' where dailyentry.id in( ' . $IDS . ') ';
//    $queryString2 = ' and accountstree.id in( ' . $id . ') ';
//    $whereClause = ' where 1 ';

    $mainItem = R::getAll('SELECT dailyentry.id ,dailyentrydebtor.value,0 as type
                            FROM dailyentry
                            join dailyentrydebtor on dailyentrydebtor.dailyentryid = dailyentry.id
                            ' . $queryString . '  and accountstreeid in (' . $id . ')
				order by dailyentry.related,dailyentry.id,dailyentrydebtor.id');
    $itemBro = R::getAll('SELECT dailyentryid
				FROM dailyentrydebtor
				where  dailyentrydebtor.accountstreeid not in( ' . $id . ' ) and dailyentryid in(' . $IDS . ')');
    $itemBro = customArrayIndexMany($itemBro, 'dailyentryid');

    $resultDataArr = R::getAll('SELECT dailyentry.* ,
				dailyentrycreditor.id as idChild,dailyentrycreditor.dailyentryid,dailyentrycreditor.accountstreeid,dailyentrycreditor.value,dailyentrycreditor.dComment as dComment,
				0 as type ,concat(dailyentrycreditor.accountstreeid,"-",parent.customName,"/",accountstree.customName) as accountstreeName
				FROM dailyentry
				join dailyentrycreditor on dailyentrycreditor.dailyentryid = dailyentry.id
				join accountstree on accountstree.id = dailyentrycreditor.accountstreeid
                                join accountstree parent on parent.id = accountstree.parent
				and accountstree.id not in( ' . $id . ' ) and dailyentry.id in( ' . $IDS . ' )
				order by dailyentry.related,dailyentry.id,dailyentrycreditor.id');
    $resultDataArr = customArrayIndexMany($resultDataArr, 'id');
    $tempArr = array();
    foreach ($resultDataArr as $key => $value) {
        $rowArr = array();
        foreach ($value as $data) {
            //
            $obj = new stdClass();
            foreach ($data as $key1 => $value1) {
                //$value[$key1] = $value1;
                $obj->$key1 = $value1;
            }
            $rowArr[] = $obj;
            //$tempArr[] = $value;
        }
        $tempArr[$key] = $rowArr;
    }
    $resultDataArr = $tempArr;
    ###########
    //1-get main items
    foreach ($mainItem as $myItem) {
        //2-get count of his brother
        $itemBroCount = count($itemBro[$myItem['id']]) + 1;
        //3-get other type to show
        $result = $resultDataArr[$myItem['id']];
        $resultCount = count($result);
        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]);
            }
        }
    }

    ###########
    $mainItem = R::getAll('SELECT dailyentry.id,dailyentrycreditor.value ,1 as type
                            FROM dailyentry
                            join dailyentrycreditor on dailyentrycreditor.dailyentryid = dailyentry.id
                            ' . $queryString . '  and accountstreeid in (' . $id . ')
				order by dailyentry.related,dailyentry.id,dailyentrycreditor.id');
    $itemBro = R::getAll('SELECT dailyentryid
				FROM dailyentrycreditor
				where  dailyentrycreditor.accountstreeid not in( ' . $id . ' ) and dailyentryid in(' . $IDS . ')');
    $itemBro = customArrayIndexMany($itemBro, 'dailyentryid');
    $resultDataArr = R::getAll('SELECT dailyentry.* ,
				dailyentrydebtor.id as idChild,dailyentrydebtor.dailyentryid,dailyentrydebtor.accountstreeid,dailyentrydebtor.value,dailyentrydebtor.dComment as dComment,
				1 as type ,concat(dailyentrydebtor.accountstreeid,"-",parent.customName,"/",accountstree.customName) as accountstreeName
				FROM dailyentry
				join dailyentrydebtor on dailyentrydebtor.dailyentryid = dailyentry.id
				join accountstree on accountstree.id = dailyentrydebtor.accountstreeid
                                join accountstree parent on parent.id = accountstree.parent
				and accountstree.id not in( ' . $id . ' ) and dailyentry.id in( ' . $IDS . ' )
				order by dailyentry.related,dailyentry.id,dailyentrydebtor.id');

    $resultDataArr = customArrayIndexMany($resultDataArr, 'id');
    $tempArr = array();
    foreach ($resultDataArr as $key => $value) {
        $rowArr = array();
        foreach ($value as $data) {
            //
            $obj = new stdClass();
            foreach ($data as $key1 => $value1) {
                //$value[$key1] = $value1;
                $obj->$key1 = $value1;
            }
            $rowArr[] = $obj;
            //$tempArr[] = $value;
        }
        $tempArr[$key] = $rowArr;
    }
    $resultDataArr = $tempArr;
    //1-get main items
    foreach ($mainItem as $myItem) {
        //2-get count of his brother
        $itemBroCount = count($itemBro[$myItem['id']]) + 1;
        //3-get other type to show
        $result = $resultDataArr[$myItem['id']];
        $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));
}

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

    global $allDailyEntery;

    $queryString_date = '';
    if (isset($startDate) && !empty($startDate)) {
        $queryString_date .= ' and dailyentry.thedate >= "' . $startDate . '" ';
    }
    if (isset($endDate) && !empty($endDate)) {
        $queryString_date .= ' and dailyentry.thedate <= "' . $endDate . '" ';
    }

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


    $allDailyEntery = array();
    $TShapeArrDebtor = array();
    $TShapeArrCerditor = array();
    //prepare ids
    $allDailyEnteryDebtor = $dailyEntryEX->queryAllEXDebtorTreeSimple($queryStringDebtor);
    $allDailyEnteryCreditor = $dailyEntryEX->queryAllEXCreditorTreeSimple($queryStringCreditor);
    $IDS = '';
    foreach ($allDailyEnteryDebtor as $value) {
        $IDS .= $value->id . ",";
    }
    foreach ($allDailyEnteryCreditor 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));
}

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

?>