<?php

$do = isset($_GET['do']) ? $_GET['do'] : "";
//the global file operation
include("../public/impOpreation.php");
include_once("initiateStaticSessionCommingWithCurl.php");

//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// 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");
//Income
require_once('../models/dao/IncomeDAO.class.php');
require_once('../models/dto/Income.class.php');
require_once('../models/mysql/IncomeMySqlDAO.class.php');
require_once('../models/mysql/ext/IncomeMySqlExtDAO.class.php');
//Incometype
require_once('../models/dao/IncometypeDAO.class.php');
require_once('../models/dto/Incometype.class.php');
require_once('../models/mysql/IncometypeMySqlDAO.class.php');
require_once('../models/mysql/ext/IncometypeMySqlExtDAO.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');


//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');


//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');
//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.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 :- expensesCTRL

  OPERTATION in Controller

  1-display add form
  2- add in Expenses tble
  3-update save value (-)
  4-insert into savedaily tbl
  5-display sucess or error
  6-display show and delete
  7-delete from Expenses tbl
  8-update save value (+)
  9-insert into savedaily tbl
  10-display edit
  ======================== */

//lang

$lang = $_SESSION['erp_lang'];
include_once("../views/languages/$lang/income/income.php");
include_once("../views/languages/$lang/success.php");
include_once("../views/languages/$lang/error.php");
include_once("../views/languages/$lang/note.php");


//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("header.html");
}
//here goes the instances and general variables

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

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

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

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//incomeType
$incomeType = new Incometype();
$IncomeTypeDAO = new IncometypeMySqlDAO();
$IncomeTypeEX = new IncometypeMySqlExtDAO();
//income
$income = new Income();
$incomeDAO = new IncomeMySqlDAO();
$incomeEX = new IncomeMySqlExtDAO();
//save
$Save = new Save();
$SaveDAO = new SaveMySqlDAO();
$SaveExt = new SaveMySqlExtDAO();
//savedaily
$Savedaily = new Savedaily();
$SavedailyDAO = new SavedailyMySqlDAO();
//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupExt = new UsergroupMySqlExtDAO();

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

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


$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);


//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    $allParents = $IncomeTypeEX->queryAllEXNotParent(); //$IncomeTypeDAO->queryByConditions(0);
    $smarty->assign("allParents", $allParents);

    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
              $saves = $SaveDAO->queryAll();
        }else{
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $SaveExt->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("saves", $saves);
        $smarty->assign("saveid", $_SESSION['saveid']);
    }else{
        $smarty->assign('saves', $_SESSION['saveid']);
    }

    // $allSave = $SaveDAO->queryAll();
    // $smarty->assign("allSave", $allSave);
    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);

    //here the smarty templates
    $smarty->display("incomeview/add.html");
} elseif ($do == "add") {
    //here the permission check
    // include_once("../public/authentication.php");
    // here the function that do the action
    $saveValuebeforeValid = add();
    if ($saveValuebeforeValid[1] > 0) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            echo (int) $saveValuebeforeValid[1];
        } else {
            header("location:?do=sucess");
        }
    } else {
        $url = "expensesController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى للمصروفات";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");
    $projectid = filter_input(INPUT_GET, "proid");

    $alldata = $IncomeTypeEX->queryAllChildrenExt2();
    //var_dump($alldata);
    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

     $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
              $saves = $SaveDAO->queryAll();
        }else{
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $SaveExt->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("saves", $saves);
        $smarty->assign("saveid",$incomedata->saveid);
    }else{
        $smarty->assign('saves', $incomedata->saveid);
    }

    // $allSave = $SaveDAO->queryAll();
    // $smarty->assign("allSave", $allSave);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->assign("alldata", $alldata);
    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);

    $incomeTypeId = $_REQUEST['incomeTypeId'];
    $from = $_REQUEST['from'];
    $to = $_REQUEST['to'];
    $Costcenterid = $_REQUEST['Costcenterid'];
    $clientid = $_REQUEST['clientid'];

    $saveid = $_REQUEST['saveid'];
    if ($Costcenterid > 0) {
        $projectid = $Costcenterid;
    }
    $smarty->assign("projectid", $projectid);
    $queryString = '';
    $message = '';


    if($incomeTypeId > 0){
        $mytypedata = $IncomeTypeDAO->load($incomeTypeId);
        $queryString .= " AND income.incomeTypeId = $incomeTypeId  ";
        $message .= " عرض ايرادات " . $mytypedata->incomeTypeName;
    }else{
        $message .= " عرض ايرادات   " ;
    }

    if($from){
        $queryString .= ' AND income.incomeDate >= "' . $from . '"  ';
        $message .=  " من تاريخ : " . $from ;
    }

    if($to){
        $queryString .= ' AND income.incomeDate <= "' . $to . '"  ';
        $message .=  "  الى تاريخ  " . $to;
    }

    if ($projectid > 0) {
        $costcenter = $CostcenterDAO->load($projectid);
        $queryString .= ' and income.costcenterid = ' . $projectid;
        $message .= " مع  مركور تكلفه  " . $costcenter->name;
    }

    if ($clientid > 0) {
        $client = $clientDAO->load($clientid);
        $queryString .= ' and income.clientid = ' . $clientid;
        $message .= " مع العميل  " . $client->clientname;
    }

    if ($saveid > 0) {
        $queryString .= ' and income.saveid = ' . $saveid;
    }else if ($_SESSION['searchinonesave'] == 0) {
        if( $_SESSION['saveids'] != 0){
            $queryString .= ' and income.saveid in (' . $_SESSION['saveids'] . ')';
        }
    }else{
        $queryString .= ' and income.saveid = ' . $_SESSION['saveid'] .' ' ;
    }

    $incomeData = $incomeEX->queryAllData($queryString);
    $sum = 0;
    foreach ($incomeData as $data) {
        if ($data->conditions == 0) {
            $sum = $data->incomeValue + $sum;
        }
    }
                
    $smarty->assign('sum', $sum);
    $smarty->assign('incomeData', $incomeData);
    $smarty->assign('message', $message);
    //$smarty->assign("customCheck",1);
    $smarty->display("incomeview/show.html");
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    try {
        $incomeId = $_GET['id'];
        $note = delete($incomeId);
        if ($note == 0) {

            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى";
            } else {
                $note = "There is not enough amount in the main safe";
            }
        }


        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "deletepost") {
    deletepost();
} elseif ($do == "returndelete") {//returndelete
    include_once("../public/authentication.php");
    try {
        $incomeId = $_GET['id'];
        $note = returndelete($incomeId);
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") {//tempdelete
    include_once("../public/authentication.php");
    try {
        $incomeId = $_GET['id'];
        $note = tempdelete($incomeId);
        if ($note == 0) {
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى";
            } else {
                $note = "There is not enough amount in the main safe";
            }
        }

        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") {//edit  Expensetype
    //here the permssion check
    include_once("../public/authentication.php");

    $id = $_GET["id"];

    $alldata = $IncomeTypeEX->queryAllEXNotParent(); //$IncomeTypeDAO->queryByConditions(0);
    $smarty->assign("alldata", $alldata);

    $incomedata = $incomeDAO->load($id);
    $smarty->assign("incomedata", $incomedata);

    $smarty->display("incomeview/editprint.html");
} elseif ($do == "edit") {//edit  Expensetype
    //here the permssion check
    $id = $_GET["id"];
    include_once("../public/authentication.php");
    $alldata = $IncomeTypeEX->queryAllEXNotParent(); //$IncomeTypeDAO->queryByConditions(0);;
    $smarty->assign("alldata", $alldata);

   
    // $allSave = $SaveDAO->queryAll();
    // $smarty->assign("allSave", $allSave);
    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);


    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

    $incomedata = $incomeDAO->load($id);
    $smarty->assign("incomedata", $incomedata);


     $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
              $saves = $SaveDAO->queryAll();
        }else{
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $SaveExt->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("saves", $saves);
        $smarty->assign("saveid",$incomedata->saveid);
    }else{
        $smarty->assign('saves', $incomedata->saveid);
    }


    $smarty->display("incomeview/edit.html");
} elseif ($do == "update") { //edit update
    //here the permssion check
    include_once("../public/authentication.php");
    //
    // here the function that do the action
    $saveValuebeforeValid = update();
    //print_r('dddddddd'.$saveValuebeforeValid);
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        if ($saveValuebeforeValid == "1") {
            header("location:?do=sucess");
        } else {
            $url = "expensesController.php?do=show";
            $smarty->assign('urldirect', $url);
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى";
            } else {
                $note = "There is not enough amount in the main safe";
            }
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        }
    }

    /* if($saveValuebeforeValid == "1" || $saveValuebeforeValid =="2")
      {
      header("location:?do=sucess");
      }
      else
      {
      $url = "expensesController.php?do=show";
      $smarty->assign('urldirect', $url);
      $note ="لا يوجد بالخزنة الرئيسية المبلغ الكافى للمصروفات";

      $smarty->assign('msgnote', $note);
      $smarty->display("notes.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("customIncome", 1);

$smarty->assign("customValidation", 1);
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

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

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

/* function getIncomeTypeParents()
  {
  global	$IncomeTypeEX;

  $allParents = $IncomeTypeEX->getParents();
  return $allParents;}

  //expensesType
  function IncomeType()
  {
  //to use the variable outside the funcion
  global $IncomeTypeEX ;

  //$alldata=$ExpensetypeExt->queryAllExt();
  //كل التصنيفات التي ليست parent لأي تصنيف آخر
  $alldata=$IncomeTypeEX->queryAllChildren();
  return $alldata;
  }

  function getExpensesByType($typeid)
  {
  global $ExpenseDAO;

  $expensesData = $ExpenseDAO->queryByExpensestypeid($typeid);
  return $expensesData;
  } */

function getClients() {
    global $clientDAO;
    $clientsData = $clientDAO->queryByCondition(0);
    return $clientsData;
}

// add in expenses tbl
function add() {
    global $incomeDAO;
    global $income;
    global $incomeEX;
    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;

    global $incomeType;
    global $IncomeTypeDAO;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    //save
    global $Save;
    global $SaveDAO;

    global $today;

    global $SaveDAO;


    //Transaction
    if ($_GET['do'] != "update")
        $mytransactions = new Transaction();
    try {
        $Costcenterid = $_POST['Costcenterid'];
        $parent = $_POST["parent"];
        $name = $_POST['name'];
        $Value = $_POST['Value'];
        $saveid = $_POST['saveid'];
        $comment = $_POST['comment'];
        $clientid = $_POST['clientid'];





        //add in income tbl
        $income->incomeTypeId = $parent;
        $income->incomeName = $name;
        $income->incomeValue = $Value;
        $income->conditions = 0;
        $income->incomeDate = $today;
        $income->userid = $_SESSION["userid"];
        $income->incomeDetails = $comment;
        $income->costcenterid = $Costcenterid;
        $income->saveid = $saveid;
        $income->clientid = $clientid;
        $income->dailyentryid = 0;



        $incomeId;
        if (isset($_POST["incomeId"])) {
            $incomeId = $_POST["incomeId"];
            $income->incomeId = $_POST["incomeId"];
            $incomeEX->insertWithId($income);


            $Costcenterdetail->processname = 'اضافه ايراد';
            $Costcenterdetail->type = 7;
            $Costcenterdetail->costamount = $Value;
            $Costcenterdetail->costcenterid = $Costcenterid;
            $Costcenterdetail->costdate = date('Y-m-d');
            $Costcenterdetail->del = 0;
            $Costcenterdetail->modelid = $incomeId;
            $Costcenterdetail->tablename = 'incomeController.php';
            $Costcenterdetail->uesrid = $_SESSION['userid'];

            if ($Costcenterid != -1 && $Costcenterid != '-1') {
                $CostcenterdetailDAO->insert($Costcenterdetail);
            }
            //print_r('insertWithId'.$income->incomeId);
        } else {
            $incomeId = $incomeDAO->insert($income);

            $Costcenterdetail->processname = 'اضافه ايراد';
            $Costcenterdetail->type = 7;
            $Costcenterdetail->costamount = $Value;
            $Costcenterdetail->costcenterid = $Costcenterid;
            $Costcenterdetail->costdate = date('Y-m-d');
            $Costcenterdetail->del = 0;
            $Costcenterdetail->modelid = $incomeId;
            $Costcenterdetail->tablename = 'incomeController.php';
            $Costcenterdetail->uesrid = $_SESSION['userid'];

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


        if ($Value > 0) {
            //get saveVsalue before and saveValue after mins expensesValue
            $valueData = getSaveValueAndPlus($Value, $saveid);
            //print_r($valueData);

            if (count($valueData) > 0) {
                $saveId = $valueData[0];
                $saveValuebefore = $valueData[1];
                $saveValueafter = $valueData[2];

                //update save value after expenses
                updateSave($saveId, $saveValueafter);
                //insert into savedaily tbl
                insertSavedaily($saveValuebefore, $Value, 0, $saveId, "إضافة ايرادات", $incomeId, $saveValueafter, "incomeController.php");
            }
        }

        $dailyEntry->entryComment = 'تم اضافة ايراد جديد (  ' . $name . ' )';

//// من حساب الخزينة

        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $Value;
        //save session
//        $saveid = $_SESSION['saveid'];
        $dataSave = $SaveDAO->load($saveid);

        $idTreeSave = $dataSave->treeId;
        $dailyEntryDebtor->accountstreeid = $idTreeSave;

//// الي حساب الايرادات
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $Value;

        $parentData = $IncomeTypeDAO->load($parent);
        $parentTreeId = $parentData->treeId;
        $dailyEntryCreditor->accountstreeid = $parentTreeId;

        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        $did = $returnedData[1];

        $rowData = $incomeDAO->load($incomeId);

        $rowData->dailyentryid = $did;


        $incomeDAO->update($rowData);
        //
        if ($_GET['do'] != "update")
            $mytransactions->commit();
    } catch (Exception $ex) {
        //
        if ($_GET['do'] != "update")
            $mytransactions->rollback();
    }

    return array($saveValuebeforeValid, $incomeId);
}

function showwithsearch() {
    global $IncomeTypeEX;
    global $incomeDAO;
    global $incomeEX;
    global $today;
    global $smarty;

     $queryString = '';
    if ($_SESSION['searchinonesave'] == 0) {
        if( $_SESSION['saveids'] != 0){
            $queryString = ' and income.saveid in (' . $_SESSION['saveids'] . ')';
        }
    }else{
        $queryString = ' and income.saveid = ' . $_SESSION['saveid'] .' ' ;
    }

    $sum;

    $incomeTypeId = $_REQUEST['incomeTypeId'];

    //select all data from Expenses tbl by expensestypeid
    $incomeData = $incomeEX->queryByincometypeidForShow($incomeTypeId,$queryString);

    $sum = 0;
    foreach ($incomeData as $data) {
        if ($data->conditions == 0) {
            $sum = $data->incomeValue + $sum;
        }
    }

    $smarty->assign('sum', $sum);
    $smarty->assign('incomeData', $incomeData);
}

//show
/* function show()
  {
  global $ExpensetypeExt ;
  global $ExpenseDAO ;
  global $ExpenseExt;
  global $today;
  global $smarty;

  $sum;


  $expenseData = $ExpenseExt->queryAllexpense();

  $sum=0;
  foreach ($expenseData as $data)
  {
  if($data->conditions == 0)
  {
  $sum = $data->expensesValue + $sum;
  }
  }

  $smarty->assign('sum', $sum);
  $smarty->assign('expenseData', $expenseData);
  } */

function showWithDate($from, $to, $projectid = '', $clientid = '', $saveid = '') {
    global $IncomeTypeEX;
    global $incomeDAO;
    global $incomeEX;

    global $today;
    global $smarty;

    $sum;
    $queryString = '';
    if ($projectid > 0) {
        $queryString .= ' and income.costcenterid = ' . $projectid;
    }
    if ($clientid > 0) {
        $queryString .= ' and income.clientid = ' . $clientid;
    }


     if ($saveid > 0) {
        $queryString .= ' and income.saveid = ' . $saveid;
    }else if ($_SESSION['searchinonesave'] == 0) {
        if( $_SESSION['saveids'] != 0){
            $queryString .= ' and income.saveid in (' . $_SESSION['saveids'] . ')';
        }
    }else{
        $queryString .= ' and income.saveid = ' . $_SESSION['saveid'] .' ' ;
    }




   
    $incomeData = $incomeEX->queryAllWithDate($from, $to, $queryString);

    $sum = 0;
    foreach ($incomeData as $data) {
        if ($data->conditions == 0) {
            $sum = $data->incomeValue + $sum;
        }
    }

    $smarty->assign('sum', $sum);
    $smarty->assign('incomeData', $incomeData);
}

function showWithOneDate($condition, $date, $incomeTypeId, $clientid = '', $saveid = '') {
    global $IncomeTypeEX;
    global $incomeDAO;
    global $incomeEX;

    global $today;
    global $smarty;

    $sum;
    $queryString = '';
    if ($projectid > 0) {
        $queryString .= ' and income.costcenterid = ' . $projectid;
    }
    if ($clientid > 0) {
        $queryString .= ' and income.clientid = ' . $clientid;
    }
    if ($saveid > 0) {
        $queryString .= ' and income.saveid = ' . $saveid;
    }else if ($_SESSION['searchinonesave'] == 0) {
        if( $_SESSION['saveids'] != 0){
            $queryString .= ' and income.saveid in (' . $_SESSION['saveids'] . ')';
        }
    }else{
        $queryString .= ' and income.saveid = ' . $_SESSION['saveid'] .' ' ;
    }

    $incomeData = $incomeEX->queryAllWithOneDate($condition, $date, $incomeTypeId, $queryString);

    $sum = 0;
    foreach ($incomeData as $data) {
        if ($data->conditions == 0) {
            $sum = $data->incomeValue + $sum;
        }
    }

    $smarty->assign('sum', $sum);
    $smarty->assign('incomeData', $incomeData);
}

function showWithOneDateOnly($condition, $date) {
    global $IncomeTypeEX;
    global $incomeDAO;
    global $incomeEX;

    global $today;
    global $smarty;


    $queryString ='';
    if ($_SESSION['searchinonesave'] == 0) {
        if( $_SESSION['saveids'] != 0){
            $queryString = ' and income.saveid in (' . $_SESSION['saveids'] . ')';
        }
    }else{
        $queryString = ' and income.saveid = ' . $_SESSION['saveid'] .' ' ;
    }



    $sum;

    $incomeData = $incomeEX->queryAllWithOneDateOnly($condition, $date, $queryString);

    $sum = 0;
    foreach ($incomeData as $data) {
        if ($data->conditions == 0) {
            $sum = $data->incomeValue + $sum;
        }
    }

    $smarty->assign('sum', $sum);
    $smarty->assign('incomeData', $incomeData);
}

function showWithDateAndType($from, $to, $incomeTypeId) {
    global $IncomeTypeEX;
    global $incomeDAO;
    global $incomeEX;
    global $today;
    global $smarty;


      $queryString ='';
    if ($_SESSION['searchinonesave'] == 0) {
        if( $_SESSION['saveids'] != 0){
            $queryString = ' and income.saveid in (' . $_SESSION['saveids'] . ')';
        }
    }else{
        $queryString = ' and income.saveid = ' . $_SESSION['saveid'] .' ' ;
    }

    $sum;
    $incomeData = $incomeEX->queryAllWithDateAndType($from, $to, $incomeTypeId, $queryString);


    $sum = 0;
    foreach ($incomeData as $data) {
        if ($data->conditions == 0) {
            $sum = $data->incomeValue + $sum;
        }
    }

    $smarty->assign('sum', $sum);
    $smarty->assign('incomeData', $incomeData);
}

function delete($incomeId) {
    global $incomeDAO;
    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;

    //Transaction
    if ($_GET['do'] != "update")
        $mytransactions = new Transaction();
    try {
        if (empty($incomeId)) {
            $incomeId = $_GET['id'];
        }

        if (!empty($incomeId)) {
            //get expensesvalue by expensesid
            $incomeData = $incomeDAO->load($incomeId);
            $incomevalue = $incomeData->incomeValue;
            $tempdelete = $incomeData->conditions;


            $saveValuebeforeValid = "1";

            //////////////////////////check save value before expenses///////////////////////////
            //check save value
            if ($incomevalue > 0) {
                //get save value
                $saveValueBefore = getSaveValue($incomeData->saveid);
                $saveValuebeforeValid;
                $Value = 0;
                if ($_GET['do'] == "update") {
                    $Value = $_POST['Value'];
                }
                $saveValueafterValid = $saveValueBefore - $incomevalue + $Value;

                if ($saveValueafterValid >= 0) {
                    $saveValuebeforeValid = "1"; //continue
                } else {
                    $saveValuebeforeValid = "0"; //stop and return, show error
                    //return $saveValuebeforeValid;
                }
            }
            //////////////////////////////////////////////////////////////////////////////////////
            //
            //
            //delete from expenses tbl
            $incomeDAO->delete($incomeId);
            $CostcenterdetailEX->updatedellbytypeandmodelid('7', $incomeId, 1);


            //check if this expenses tempdeleted or not
            //يجب أن يكون المصروف غير محذوف حذف مؤقت وإلا الخزنة هتزيد مرتين
            if ($tempdelete == 0) {
                if ($incomevalue > 0) {
                    //get saveValue before and saveValue after plus expensesValue
                    $valueData = getSaveValueAndMins($incomevalue, $incomeData->saveid);
                    if (count($valueData) > 0) {
                        $saveId = $valueData[0];
                        $saveValuebefore = $valueData[1];
                        $saveValueafter = $valueData[2];

                        //update save value after expenses
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl
                        insertSavedaily($saveValuebefore, $incomevalue, 1, $saveId, "حذف ايراد", $incomeId, $saveValueafter, "incomeController.php");
                    }
                }
            }
            $dailyentryid = $_GET['action'];
            reverseEntryWithItsID($dailyentryid, 1);
            delTreeElement($incomeData->incomeName);
            $note = "success";
        } else {
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "حدث خطأ أثناء إتمام العملية";
            } else {
                $note = "An error occurred while completing the operation";
            }
        }
        //
        if ($_GET['do'] != "update")
            $mytransactions->commit();
    } catch (Exception $ex) {
        //
        if ($_GET['do'] != "update")
            $mytransactions->rollback();
    }

    if ($saveValuebeforeValid == 0) {
        $note = 0;
    }
    return $note;
}

function deletepost() {
    global $incomeDAO;
    global $CostcenterdetailDAO;
    global $CostcenterdetailEX;

    //Transaction

    if ($_GET['do'] != "update")
        $mytransactions = new Transaction();
    try {
        $incomeId = $_POST['incomeId'];


        if (!empty($incomeId)) {
            //get expensesvalue by expensesid
            $incomeData = $incomeDAO->load($incomeId);
            $incomevalue = $incomeData->incomeValue;
            $tempdelete = $incomeData->conditions;


            $saveValuebeforeValid = "1";

            //////////////////////////check save value before expenses///////////////////////////
            //check save value
            if ($incomevalue > 0) {
                //get save value
                $saveValueBefore = getSaveValue($incomeData->saveid);
                $saveValuebeforeValid;
                $Value = 0;
                if ($_GET['do'] == "update") {
                    $Value = $_POST['Value'];
                }
                $saveValueafterValid = $saveValueBefore - $incomevalue + $Value;

                if ($saveValueafterValid >= 0) {
                    $saveValuebeforeValid = "1"; //continue
                } else {
                    $saveValuebeforeValid = "0"; //stop and return, show error
                    //return $saveValuebeforeValid;
                }
            }
            //////////////////////////////////////////////////////////////////////////////////////
            //
            //
            //delete from expenses tbl
            $incomeDAO->delete($incomeId);
            $CostcenterdetailEX->updatedellbytypeandmodelid('7', $incomeId, 1);


            //check if this expenses tempdeleted or not
            //يجب أن يكون المصروف غير محذوف حذف مؤقت وإلا الخزنة هتزيد مرتين
            if ($tempdelete == 0) {
                if ($incomevalue > 0) {
                    //get saveValue before and saveValue after plus expensesValue
                    $valueData = getSaveValueAndMins($incomevalue, $incomeData->saveid);
                    if (count($valueData) > 0) {
                        $saveId = $valueData[0];
                        $saveValuebefore = $valueData[1];
                        $saveValueafter = $valueData[2];

                        //update save value after expenses
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl
                        insertSavedaily($saveValuebefore, $incomevalue, 1, $saveId, "حذف ايراد", $incomeId, $saveValueafter, "incomeController.php");
                    }
                }
            }
            $dailyentryid = $_GET['action'];
            reverseEntryWithItsID($dailyentryid, 1);
            delTreeElement($incomeData->incomeName);
            $note = "success";
        } else {
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "حدث خطأ أثناء إتمام العملية";
            } else {
                $note = "An error occurred while completing the operation";
            }
        }
        //
        if ($_GET['do'] != "update")
            $mytransactions->commit();
    } catch (Exception $ex) {
        //
        if ($_GET['do'] != "update")
            $mytransactions->rollback();
    }

    if ($saveValuebeforeValid == 0) {
        $note = 0;
    }
    return $note;
}

function tempdelete($incomeId) {
    global $incomeDAO;
    global $incomeEX;
    global $CostcenterdetailEX;

    //Transaction
    $mytransactions = new Transaction();
    try {
        if (empty($incomeId)) {
            $incomeId = $_GET['id'];
        }
        if (!empty($incomeId)) {
            try {
                //get expensesvalue by expensesid
                $incomeData = $incomeDAO->load($incomeId);
                $incomeValue = $incomeData->incomeValue;

                $saveValuebeforeValid = "1";
                //////////////////////////check save value before expenses///////////////////////////
                //check save value
                if ($incomeValue > 0) {
                    //get save value
                    $saveValueBefore = getSaveValue($incomeData->saveid);
                    $saveValuebeforeValid;
                    $saveValueafterValid = $saveValueBefore - $incomeValue;
                    if ($saveValueafterValid >= 0) {
                        $saveValuebeforeValid = "1";
                    } else {
                        $saveValuebeforeValid = "0";
                        if ($_SESSION['erp_lang'] == 'ar') {
                            $note = "لا يوجد بالخزنة الرئيسية المبلغ الكافى";
                        } else {
                            $note = "There is not enough amount in the main safe";
                        }                        //return $note;
                    }
                }
                //////////////////////////////////////////////////////////////////////////////////////
                //temp delete from expenses tbl
                $incomeData->conditions = 1;
                $incomeDAO->update($incomeData);
                $CostcenterdetailEX->updatedellbytypeandmodelid('7', $incomeId, 1);


                if ($incomeValue > 0) {
                    //get saveValue before and saveValue after plus expensesValue
                    $valueData = getSaveValueAndMins($incomeValue, $incomeData->saveid);
                    if (count($valueData) > 0) {
                        $saveId = $valueData[0];
                        $saveValuebefore = $valueData[1];
                        $saveValueafter = $valueData[2];

                        //update save value after expenses
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl
                        insertSavedaily($saveValuebefore, $incomeValue, 1, $saveId, "حذف ايراد", $incomeId, $saveValueafter, "incomeController.php");
                    }
                }
                $note = "success";
            } catch (Exception $e) {

                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = "حدث خطأ أثناء إتمام العملية";
                } else {
                    $note = "An error occurred while completing the operation";
                }
            }
        } else {
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "حدث خطأ أثناء إتمام العملية";
            } else {
                $note = "An error occurred while completing the operation";
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }

    if ($saveValuebeforeValid == 0) {
        $note = 0;
    }
    return $note;
}

function returndelete($incomeId) {
    global $incomeDAO;
    global $incomeEX;
    global $CostcenterdetailEX;

    //Transaction
    $mytransactions = new Transaction();
    try {
        if (empty($incomeId)) {
            $incomeId = $_GET['id'];
        }

        if (!empty($incomeId)) {
            try {
                //get expensesvalue by expensesid
                $incomeData = $incomeDAO->load($incomeId);
                $incomeValue = $incomeData->incomeValue;
                $saveid = $incomeData->saveid;


                //return delete from expensetype tbl
                $incomeData->conditions = 0;
                $incomeDAO->update($incomeData);
                $CostcenterdetailEX->updatedellbytypeandmodelid('7', $incomeId, 0);


                if ($incomeValue > 0) {
                    //get saveVsalue before and saveValue after mins expensesValue
                    $valueData = getSaveValueAndPlus($incomeValue, $saveid);
                    if (count($valueData) > 0) {
                        $saveId = $valueData[0];
                        $saveValuebefore = $valueData[1];
                        $saveValueafter = $valueData[2];

                        //update save value after expenses
                        updateSave($saveId, $saveValueafter);
                        //insert into savedaily tbl
                        insertSavedaily($saveValuebefore, $incomeValue, 0, $saveId, "إضافة ايرادات", $incomeId, $saveValueafter, "incomeController.php");
                    }
                }
                $note = "success";
            } catch (Exception $e) {
                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = "حدث خطأ أثناء إتمام العملية";
                } else {
                    $note = "An error occurred while completing the operation";
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
    return $note;
}

function update() {

    global $incomeDAO;

    //Transaction
    $mytransactions2 = new Transaction();
    try {
        $incomeId = $_POST["incomeId"];
        $dailyentryid = $_POST['dailyentryid'];

        reverseEntryWithItsID($dailyentryid, 1);
        $icomeData = $incomeDAO->load($incomeId);

        delTreeElement($icomeData->incomeName);
        //del
        $saveValuebeforeValid = delete($incomeId);
        //add
        $note = add();
        $mytransactions2->commit();

        if ($saveValuebeforeValid === "success") {
            $saveValuebeforeValid = "1";
        }
    } catch (Exception $ex) {
        $mytransactions2->rollback();
    }
    return $saveValuebeforeValid;
}

function update2() {

    global $incomeDAO;
    global $income;
    global $incomeEX;


    //Transaction
    $mytransactions2 = new Transaction();
    try {
        $parent = $_POST["parent"];
        $name = $_POST['name'];
        $Value = $_POST['Value'];
        $comment = $_POST['comment'];
        $incomeId = $_POST["incomeId"];

        $saveValuebeforeValid = "1";

        //check conditions value in expenses tbl equal tempdele value of post variable
        //or change to change save value
        $incomeData = $incomeDAO->load($incomeId);
        if (count($incomeData) > 0) {
            $tempdele = $ExpenseData->conditions;
            if ($tempdele != $conditions) { //if the user changed conditions (حذف مؤقت أو إلغاء الحذف)
                if ($conditions == 0) {
                    $saveValuebeforeValid = "1";
                    //////////////////////////check save value before expenses///////////////////////////
                    //check save value
                    if ($expensevalue > 0) {
                        //get save value
                        $saveValueBefore = getSaveValue();
                        $saveValuebeforeValid;
                        $saveValueafterValid = $saveValueBefore - $expensevalue;
                        if ($saveValueafterValid >= 0) {
                            $saveValuebeforeValid = "1"; //continue
                        } else {
                            $saveValuebeforeValid = "0"; //stop and return, show error
                            //return $saveValuebeforeValid;
                        }
                    }

                    ////////////////////////////////////////////////////////////////
                    //update save
                    if ($expensevalue > 0) {
                        //get saveValue before and saveValue after subtractig expensesValue
                        $valueData = getSaveValueAndMins($expensevalue);
                        $saveId = $valueData[0];
                        $saveValuebefore = $valueData[1];
                        $saveValueafter = $valueData[2];

                        //update save value after expenses
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl
                        insertSavedaily($saveValuebefore, $expensevalue, 1, $saveId, "إضافة مصروف", $expenseid, $saveValueafter, "expensesController.php");
                    }
                } elseif ($conditions == 1) {
                    $saveValuebeforeValid = "2";
                    if ($expensevalue > 0) {
                        //get saveVsalue before and saveValue after adding expensesValue
                        $valueData = getSaveValueAndPlus($expensevalue);
                        if (count($valueData) > 0) {
                            $saveId = $valueData[0];
                            $saveValuebefore = $valueData[1];
                            $saveValueafter = $valueData[2];

                            //update save value after expenses
                            updateSave($saveId, $saveValueafter);

                            //insert into savedaily tbl
                            insertSavedaily($saveValuebefore, $expensevalue, 0, $saveId, "حذف مصروف", $expenseid, $saveValueafter, "expensesController.php");
                        }
                    }
                }
            }

            //update expenses table
            $Expense->expensesid = $expenseid;
            $Expense->expensesname = $expensesname;
            $Expense->expensesValue = $expensevalue;
            $Expense->conditions = $conditions;
            $Expense->expensestypeid = $expensetype;
            $Expense->expensesdate = $today;
            $Expense->userid = $_SESSION["userid"];
            $Expense->expensesdetails = $expensecomment;

            $ExpenseExt->updateExpense($Expense);
        }
        $mytransactions2->commit();
    } catch (Exception $ex) {
        $mytransactions2->rollback();
    }
    return $saveValuebeforeValid;
}

// get savecurrentvalue from save tbl
function getSaveValue($saveid = 0) {
    global $Save;
    global $SaveDAO;
    if ($saveid) {
        $saveData = $SaveDAO->load($saveid);
    } else {
        $saveData = $SaveDAO->load($_SESSION['saveid']);
    }


    $saveValuebefore = $saveData->savecurrentvalue;
    return $saveValuebefore;
}

// get savecurrentvalue and plus from save tbl
function getSaveValueAndPlus($savevaluechanged, $saveid) {
    global $Save;
    global $SaveDAO;
    if ($saveid) {
        $saveData = $SaveDAO->load($saveid);
    } else {
        $saveData = $SaveDAO->load($_SESSION['saveid']);
    }

    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    //print_r("saveValuebefore = ".$saveValuebefore);

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// get savecurrentvalue and mins from save tbl
function getSaveValueAndMins($savevaluechanged, $saveid = 0) {
    global $Save;
    global $SaveDAO;
    if ($saveid) {
        $saveData = $SaveDAO->load($saveid);
    } else {
        $saveData = $SaveDAO->load($_SESSION['saveid']);
    }

    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// update Save tbl
function updateSave($saveid, $savevalueafter) {
    global $Save;
    global $SaveExt;

    //update savecurrentvalue in Save tbl
    $Save->savecurrentvalue = $savevalueafter;
    $Save->userid = $_SESSION['userid'];
    $Save->saveid = $saveid;

    $SaveExt->updateSaveValue($Save);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {

    //to use the variable out side the funcion
    global $Savedaily;
    global $SavedailyDAO;

    //insert in Savedaily tbl
    $Savedaily->savedailydate = date("Y-m-d H:i:s");
    $Savedaily->userid = $_SESSION['userid'];
    $Savedaily->savedailysavebefore = $savedailysavebefore;
    $Savedaily->savedailychangeamount = $savedailychangeamount;
    $Savedaily->savedailychangetype = $savedailychangetype;
    $Savedaily->saveid = $saveid;
    $Savedaily->processname = $processname;
    $Savedaily->savedailymodelid = $savedailymodelid;
    $Savedaily->savedailysaveafter = $savedailysaveafter;
    $Savedaily->tablename = $tablename;

    $SavedailyDAO->insert($Savedaily);
}

?>