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

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

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

  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();
//-----------------------------------------------------------
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailEX = new StoredetailMySqlExtDAO();
//Store
$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();

$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");
    ##
    $smarty->assign("now", date('Y-m-d H:i:s'));
    ###لحساب صافى الربح
    ##يتم اضافة المصروفات والايرادات على اجمالى الربح
    //1-اجمالى الربح او الخسارة من تقرير متاجرة
    ############### this part is comon
    $debtorArr2 = array();
    $creditorArr2 = array();
    $totalDebtor2 = 0;
    $totalCreditor2 = 0;
    //بضاعة اول المدة
    $accountsTree = $accountsTreeDAO->load(19);
    $startGoodsValTreeObj = $accountsTree;
    $startGoodsVal = $accountsTree->theValue;
    $smarty->assign("startGoodsVal", $startGoodsVal);


    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //بضاعة اخر المدة
    //نحسب قيمة البضاعة حاليا
    $endGoodsVal = getStartGoodsVal();
    $endGoodsValTreeObj = new Accountstree();
    $endGoodsValTreeObj->name = 'بضاعة اخر المدة';
    $endGoodsValTreeObj->customName = 'بضاعة اخر المدة';
    $endGoodsValTreeObj->theValue = $endGoodsVal;
    $smarty->assign("endGoodsVal", $endGoodsVal);

    //كل المصروفات
    $myArray = array();
    array_push($myArray, $startGoodsValTreeObj);
    display_childrenExcept(3);
    foreach ($myArray as $value) {
        array_push($debtorArr2, $value);
        $totalDebtor2 += $value->theValue;
    }
    //كل الايرادات
    $myArray = array();
    array_push($myArray, $endGoodsValTreeObj);
    display_childrenExcept(4);
    foreach ($myArray as $value) {
        array_push($creditorArr2, $value);
        $totalCreditor2 += $value->theValue;
    }
    $netvalue2 = $totalCreditor2 - $totalDebtor2;
    $netVal2TreeObj = new Accountstree();
    $netVal2TreeObj->theValue = $netvalue2;
    ////2-المصروفات
    //3-الايرادات
    //
    //*------------------------------------------*/
    $debtorArr = array();
    $creditorArr = array();
    $totalDebtor = 0;
    $totalCreditor = 0;
    //كل المصروفات
    $myArray = array();
    if ($netvalue2 < 0) {
        $netVal2TreeObj->name = 'اجمالى الخسارة';
        $netVal2TreeObj->customName = 'اجمالى الخسارة';
        array_push($myArray, $netVal2TreeObj);
    }
    display_childrenExcept(3);
    foreach ($myArray as $value) {
        array_push($debtorArr, $value);
        $totalDebtor += $value->theValue;
    }
    //كل الايرادات
    $myArray = array();
    if ($netvalue2 >= 0) {
        $netVal2TreeObj->name = 'اجمالى الربح';
        $netVal2TreeObj->customName = 'اجمالى الربح';
        array_push($myArray, $netVal2TreeObj);
    }
    display_childrenExcept(4);
    foreach ($myArray as $value) {
        array_push($creditorArr, $value);
        $totalCreditor += $value->theValue;
    }
    $smarty->assign("totalDebtor", $totalDebtor);
    $smarty->assign("totalCreditor", $totalCreditor);


    //prepare final array
    $reportArr = array();
    $creditorCount = count($creditorArr);
    $debtorCount = count($debtorArr);
    $totalCount = $creditorCount + $debtorCount;

    $accountsTree = new Accountstree();
    $debtorItr = 0;
    $creditorItr = 0;
    //ليه  $totalCountFixed * 2
    //لوفيه جمب فيه نتيجتين وجمب فاضى مش هيجيب غير نتيجة واحده من الجمب اللى فيه نتيجتين عشان فيه لفة ضاعت مع الجمب الفاضى فقلت الففه الضعف
    $realCount = 0;
    for ($i = 0; $i < ($totalCount * 2); $i++) {
        if (empty($debtorArr[$debtorItr]) && empty($creditorArr[$creditorItr])) {
            //do no thing
        } else {
            $realCount++;
            if ($i % 2 == 0) {
                if (empty($debtorArr[$debtorItr])) {
                    array_push($reportArr, $accountsTree);
                } else {
                    array_push($reportArr, $debtorArr[$debtorItr]);
                    $debtorItr++;
                }
            } else {
                if (empty($creditorArr[$creditorItr])) {
                    array_push($reportArr, $accountsTree);
                } else {
                    array_push($reportArr, $creditorArr[$creditorItr]);
                    $creditorItr++;
                }
            }
        }
    }
    $smarty->assign("realCount", $realCount);
    $smarty->assign("reportArr", $reportArr);


    $netvalue = $totalCreditor - $totalDebtor;
    $gainLossMsg;
    if ($netvalue >= 0) {
        $gainLossMsg = 'صافى الربح : ' . $netvalue;
    } elseif ($netvalue < 0) {
        $netvalue2 = abs($netvalue2);
        $gainLossMsg = 'صافى الخسارة : ' . $netvalue;
    }
    $smarty->assign("gainLossMsg", $gainLossMsg);


    //here the smarty templates
    $smarty->display("profitandlossreportview/add.html");
} elseif ($do == "incomeList") {

    //الايرادات // دخل النشاط
    $accountsTreeOrdered = array();
    $revenues = $accountsTreeDAO->load(140);
    array_push($accountsTreeOrdered, $revenues);
    $incomeOfActivity = $accountsTreeDAO->load(141);
    array_push($accountsTreeOrdered, $incomeOfActivity);
    orderAsTree(141, 1);
    $smarty->assign("revenues", $accountsTreeOrdered);

    //خصم مسموح به
    $accountsTreeOrdered = array();
    $allowedDiscount = $accountsTreeDAO->load(398);
    array_push($accountsTreeOrdered, $allowedDiscount);
    $smarty->assign("allowedDiscount", $accountsTreeOrdered);

    //تكلفة المخزون السلعى   --  تكلفة التشغيل
    $accountsTreeOrdered = array();
    $workingCost = $accountsTreeDAO->load(160);
    $workingCost->name = 'تكلفة التشغيل';
    array_push($accountsTreeOrdered, $workingCost);
    orderAsTree(160, 1);
    $smarty->assign("WorkingCost", $accountsTreeOrdered);

    //مصرفات التشغيل
    $accountsTreeOrdered = array();
    $workingExpenses = $accountsTreeDAO->load(412);
    array_push($accountsTreeOrdered, $workingExpenses);
    orderAsTree(412, 1);
    $smarty->assign("workingExpenses", $accountsTreeOrdered);

    //مصروفات عمومية و إدارية
    $accountsTreeOrdered = array();
    $generalAndManegeralExpenses = $accountsTreeDAO->load(413);
    array_push($accountsTreeOrdered, $generalAndManegeralExpenses);
    orderAsTree(413, 1);
    $smarty->assign("generalAndManegeralExpenses", $accountsTreeOrdered);


    //ايرادات الاخرى
    $accountsTreeOrdered = array();
    $otherRevenues = $accountsTreeDAO->load(147);
    array_push($accountsTreeOrdered, $otherRevenues);
    orderAsTree(147, 1);
    $smarty->assign("otherRevenues", $accountsTreeOrdered);


    $smarty->display("profitandlossreportview/addnew.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_childrenExcept($parent) {
    global $accountsTreeDAO;
    global $accountsTreeEX;
    global $myArray;
    global $sum;
    $result = $accountsTreeEX->queryByParentExt($parent);
    if (count($result) > 0) {

        foreach ($result as $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;
                array_push($myArray, $type);
            } else {
                array_push($myArray, $type);
            }
##to show the first level of childs only
##if i open it . this show all childs under parent
//            if (count($childData) > 0) {
//                display_childrenExcept($type->id);
//            }
        }
    }
}

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

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

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;
            $type->theValue = (float) $type->theValue;
            array_push($accountsTreeOrdered, $type);
            orderAsTree($type->id, $level + 1);
        }
    }
}

/* * *************************************************************************** */

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

    $result = $accountsTreeEX->queryByParentExtReport2($parent);
    if (count($result) > 0) {
        foreach ($result as $type) {
            $sum += $type->theValue;
//check for expenses for this category
            $childData = $accountsTreeDAO->queryByParentreport2($type->id);
            if (count($childData) > 0) {
                getTheTrueValue2($type->id, $sum);
            }
        }
    }
}

/* * *************************************************************************** */

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

?>