<?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");
include_once('dailyentryfun.php');

//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");

//Transfermoney
require_once('../models/dao/TransfermoneyDAO.class.php');
require_once('../models/dto/Transfermoney.class.php');
require_once('../models/mysql/TransfermoneyMySqlDAO.class.php');
require_once('../models/mysql/ext/TransfermoneyMySqlExtDAO.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');
//Currency
require_once('../models/dao/CurrencyDAO.class.php');
require_once('../models/dto/Currency.class.php');
require_once('../models/mysql/CurrencyMySqlDAO.class.php');
require_once('../models/mysql/ext/CurrencyMySqlExtDAO.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');


//Breadcrumb
require_once("../library/breadcrumb.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 :- transfermoneyCTRL التحويل بين الخزن

  OPERTATION in Controller

  1-display add form
  2- add in transfermoney tble
  3-update savefrom value (-)
  4-insert into savedaily tbl
  5-update saveto value (+)
  6-insert into savedaily tbl
  7-display sucess or error
  8-display show and delete
  9-tempdelete from Expenses tbl
  10-returndelete save value (+)

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


//here the global templates
$smarty->display("header.html");


//here goes the instances and general variables
//Transfermoney
$myTransfermoney = new Transfermoney();
$myTransfermoneyRecord = new TransfermoneyMySqlDAO();
$myTransfermoneyEx = new TransfermoneyMySqlExtDAO();

//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();

//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();

//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();


//Breadcrumb
$breadcrumbObject = new Breadcrumb();

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

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

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();


//check and use the condition that suite this action
$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);


//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="transfermoneyController.php?do=show">تحويل بين الخزن</a> > اضافة تحويل', 'transfermoneyController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    //here the smarty templates
    $smarty->display("transfermoneyview/add.html");

    $smarty->assign("customTransfermoney", 1);
} elseif ($do == "add") {

    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    $returnedAdd = add();
    $saveValuebeforeValid = $returnedAdd[0];
    $transferId = $returnedAdd[1];
    if ($saveValuebeforeValid == 1) {
        if ($_POST['printTxt'] == "1") {
            header("location:?do=editprint&id=" . $transferId . "");
        } else
            header("location:?do=sucess");
    } else {
        $url = "transfermoneyController.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");



    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $id = (int) $_REQUEST['id'];


    if ($id > 0) {
        $message = " عرض تحويلات الخزن :" . "برقم:" . $id;
        $smarty->assign('message', $message);
        showById($id);
    } elseif (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
        $message = " عرض تحويلات الخزن :" . $startDate . "الى تاريخ:" . $endDate;
        $smarty->assign('message', $message);
        showByDate($startDate, $endDate);
    } elseif (isset($startDate) && $startDate != "") {
        $condition = '>=';
        $message = " عرض تحويلات الخزن من:" . $startDate . '';
        $smarty->assign('message', $message);
        showByOneDate($condition, $startDate);
    } elseif (isset($endDate) && $endDate != "") {
        $condition = '<=';
        $message = " عرض تحويلات الخزن الى:" . $endDate . '';
        $smarty->assign('message', $message);
        showByOneDate($condition, $endDate);
    } else {
        $today = date("Y-m-d");
        showByDate($today, $today);
    }


    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="transfermoneyController.php?do=show">التحويل بين الخزن</a> > عرض التحويلات', 'transfermoneyController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);

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


    $smarty->display("transfermoneyview/show.html");

    $smarty->assign("customCheck", 1);
}



//returndelete
elseif ($do == "returndelete") {
    include_once("../public/authentication.php");

    $transfermoneyId = $_GET['transfermoneyid'];


    // here the function that do the action
    $saveValuebeforeValid = returndelete($transfermoneyId);
    if ($saveValuebeforeValid[1] == 1) {


        header("location:?do=sucess");
    } elseif ($saveValuebeforeValid[1] == 2) {
        $url = "transfermoneyController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {


        $url = "transfermoneyController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالخزنة المبلغ الكافى لتحويل الاموال";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
}



//tempdelete
elseif ($do == "tempdelete") {
    include_once("../public/authentication.php");

    $transfermoneyId = $_GET['transfermoneyid'];


    // here the function that do the action
    $saveValuebeforeValid = tempdelete($transfermoneyId);
    if ($saveValuebeforeValid[1] == 1) {
        header("location:?do=sucess");
    } elseif ($saveValuebeforeValid[1] == 2) {
        $url = "transfermoneyController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {

        $url = "transfermoneyController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالخزنة المبلغ الكافى لتحويل الاموال";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
}





//edit  transfer
elseif ($do == "editprint") {

    //here the permssion check
    include_once("../public/authentication.php");

    $loadData = editprint();
    $smarty->assign("loadData", $loadData);



    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="transfermoneyController.php?do=show">التحويل بين الخزن</a> > عرض تحويل لخزنة', 'transfermoneyController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $smarty->display("transfermoneyview/editprint.html");

    $smarty->assign("customPrint", 1);
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    try {
        $transfermoneyid = $_GET['transfermoneyid'];
        delete($transfermoneyid);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}
//edit  transfer
elseif ($do == "edit") {

    //here the permssion check
    include_once("../public/authentication.php");

    $loadData = edit();
    $smarty->assign("loadData", $loadData);
    $saveidfromval = $mySaveRecord->load($loadData->saveidfrom);
    $smarty->assign("saveidfromval", $saveidfromval);
    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);


    $saveToData = loadsaveExpectId($loadData->saveidfrom);
    $smarty->assign("saveToData", $saveToData);


    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="transfermoneyController.php?do=show">التحويل بين الخزن</a> > تعديل تحويل لخزنة', 'transfermoneyController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $smarty->display("transfermoneyview/edit.html");
} elseif ($do == "update") {

    include_once("../public/authentication.php");
    try {
        $transfermoneyidold = $_POST['transfermoneyidold'];
        delete($transfermoneyidold);
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}



//edit  update
elseif ($do == "executeOperation") {

    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    executeOperation();

    showAll();

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="transfermoneyController.php?do=show">التحويل بين الخزن</a> > عرض التحويلات', 'transfermoneyController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $smarty->display("transfermoneyview/show.html");

    $smarty->assign("customCheck", 1);
} elseif ($do == "sucess") {

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

    //here the smarty templates
    $smarty->display("error.html");
}



$smarty->assign("customTransfermoney", 1);

$smarty->assign("customValidation", 1);

//here the global templates
$smarty->display("footer.html");

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

//select all save data
function loadSave()
{

    //to use the variable out side the funcion
    global $mySaveRecord;
    global $mySaveEx;

    //load all save data
    //    $saveData = $mySaveRecord->queryByConditions(0);
    $saveData = $mySaveEx->queryAllEX2();

    return $saveData;
}

//select all save data
function loadsaveExpectId($saveIdFrom)
{

    //to use the variable out side the funcion
    global $mySaveEx;

    //load all save data
    $saveData = $mySaveEx->queryWithConditionExpectId($saveIdFrom);

    return $saveData;
}

// add in Transfermoney tbl
function add()
{

    //to use the variable out side the funcion
    global $myTransfermoney;
    global $myTransfermoneyRecord;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;
    global $mySaveRecord;
    global $currencyEX;
    //Transaction
    $transactions = new Transaction();

    $saveidFrom = $_POST['saveidfrom'];
    $saveidTo = $_POST['saveidto'];
    $transfermoneyValue = $_POST['transfermoneyvalue'];
    $comment = $_POST['comment'];

    //
    $currencyId = (isset($_POST['currencyId']) && !empty($_POST['currencyId'])) ? (int) $_POST['currencyId'] : 1;
    $cFactor = (isset($_POST['cFactor']) && !empty($_POST['cFactor'])) ? (float) $_POST['cFactor'] : 1;
    $transfermoneyValueCurr = (isset($_POST['transfermoneyvalueCurr']) && !empty($_POST['transfermoneyvalueCurr'])) ? (float) $_POST['transfermoneyvalueCurr'] : $transfermoneyValue;
    //

    $saveDataFrom = $mySaveRecord->load($saveidFrom);
    $saveDataTo = $mySaveRecord->load($saveidTo);

    //add in Transfermoney tbl
    $myTransfermoney->conditions = 0;
    $myTransfermoney->saveidfrom = $saveidFrom;
    $myTransfermoney->saveidto = $saveidTo;
    $myTransfermoney->transfermoneydate = date("Y-m-d");
    $myTransfermoney->transfermoneyvalue = $transfermoneyValue;
    $myTransfermoney->userid = $_SESSION["userid"];
    $myTransfermoney->dailyentryid = 0;
    $myTransfermoney->comment = $comment;
    $myTransfermoney->currencyId = $currencyId;
    $myTransfermoney->conversionFactor = $cFactor;
    $myTransfermoney->transfermoneyvalueInCurrency = $transfermoneyValueCurr;


    $saveValuebeforeValid = 1;
    /////////////////check savefrom value before transfer//////////////////////

    $saveFromCurrencyId = 1;
    if ($transfermoneyValue > 0) {
        //get save value
        $saveData = getSaveValueBefore($saveidFrom);
        $saveFromValueBefore = $saveData[0];
        $saveCFactor = $saveData[1];
        $saveFromCurrencyId = $saveData[2];
        $transfermoneyValueInSaveCurr = $transfermoneyValueCurr; //round(($transfermoneyValue * $saveCFactor), 4); //convert from main curr
        $saveFromValueafterValid = $saveFromValueBefore - $transfermoneyValueInSaveCurr;
        if ($saveFromValueafterValid >= 0) {
            $saveValuebeforeValid = 1;
        } else {
            $saveValuebeforeValid = 0;
            return $saveValuebeforeValid;
        }
    }


    $transfermoneyId = $myTransfermoneyRecord->insert($myTransfermoney);

    if ($transfermoneyValue > 0) {
        if ($currencyId > 1 && $saveFromCurrencyId == $currencyId) {
            $currencyEX->updateConversionFactor($cFactor, $currencyId);
        }
        //get saveFromValue before and saveFromValue after mins transfermoneyValue
        $saveFromData = getSaveValueAndMins($saveidFrom, $transfermoneyValue);
        $saveFromId = $saveFromData[0];
        $saveFromValuebefore = $saveFromData[1];
        $saveFromValueafter = $saveFromData[2];
        $transfermoneyValueCurr = $saveFromData[3]; //needed because of currency
        $saveConversionFactorFrom = $saveFromData[4]; //needed because of currency
        //update saveFrom value after add transfer
        updateSave($saveFromId, $saveFromValueafter);

        //insert into savedaily tbl from savefrom
        insertSavedaily($saveFromValuebefore, $transfermoneyValueCurr, 1, $saveFromId, "تحويل امول الى الخزنة  [ " . $saveDataTo->savename . " ] ", $transfermoneyId, $saveFromValueafter, "transfermoneyController.php");



        //get saveToValue before and saveToValue after Plus transfermoneyValue
        $saveToData = getSaveValueAndPlus($saveidTo, $transfermoneyValue);
        $saveToId = $saveToData[0];
        $saveToValuebefore = $saveToData[1];
        $saveToValueafter = $saveToData[2];
        $transfermoneyValueCurr = $saveToData[3]; //needed because of currency
        $saveConversionFactorTo = $saveToData[4]; //needed because of currency
        //update saveTo value after add transfer
        updateSave($saveToId, $saveToValueafter);

        //insert into savedaily tbl from saveTo
        insertSavedaily($saveToValuebefore, $transfermoneyValueCurr, 0, $saveToId, "تحويل امول من الخزنة  [ " . $saveDataFrom->savename . " ] ", $transfermoneyId, $saveToValueafter, "transfermoneyController.php");

        ///////////////////////////// daily entry
        $saveDataFrom = $mySaveRecord->load($saveidFrom);

        // start creditor
        $fromTreeId = $saveDataFrom->treeId;

        //$oldSave = $myTransfermoneyRecord->load($fromTreeId);

        $dailyEntryCreditorArray = array();

        $dailyEntryCreditor->accountstreeid = $fromTreeId;
        $dailyEntryCreditor->value = $transfermoneyValue;

        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

        // end creditor
        // start debtor
        $toSave = $mySaveRecord->load($saveToId);


        $dailyEntry->entryComment = 'اضافة تحويل من ' . $saveDataFrom->savename . ' الى ' . $toSave->savename;
        $toTreeId = $toSave->treeId;

        $dailyEntryDebtor->accountstreeid = $toTreeId;
        $dailyEntryDebtor->value = $transfermoneyValue;
        $dailyEntryDebtorArray = array();

        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        try {
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $transfermoneyId, "transfermoneyController.php?do=show&id=$transfermoneyId");

            $did = $returnedData[1];

            $rowData = $myTransfermoneyRecord->load($transfermoneyId);

            $myTransfermoney->conditions = $rowData->conditions;
            $myTransfermoney->saveidfrom = $rowData->saveidfrom;
            $myTransfermoney->saveidto = $rowData->saveidto;
            $myTransfermoney->transfermoneydate = $rowData->transfermoneydate;
            $myTransfermoney->transfermoneyvalue = $rowData->transfermoneyvalue;
            $myTransfermoney->userid = $rowData->userid;
            $myTransfermoney->dailyentryid = $did;
            $myTransfermoney->conversionFactorFrom = $saveConversionFactorFrom;
            $myTransfermoney->conversionFactorTo = $saveConversionFactorTo;

            $myTransfermoneyRecord->update($myTransfermoney);
            $transactions->commit();
        } catch (Exception $ex) {
            $transactions->rollback();
        }
    }

    // end debtor
    return  array($saveValuebeforeValid, $transfermoneyId);
}

//show
function showAll()
{
    global $myTransfermoneyEx;
    global $smarty;

    $transfermoneyData = $myTransfermoneyEx->queryWithOrder();

    // assign your db results to the template
    $smarty->assign('transfermoneyData', $transfermoneyData);
}

//show
function showById($id)
{
    global $myTransfermoneyEx;
    global $smarty;


    $transfermoneyData = $myTransfermoneyEx->queryWithQueryString(" and  transfermoney.transfermoneyid=$id ");
    // assign your db results to the template
    $smarty->assign('transfermoneyData', $transfermoneyData);
}

function showByDate($startDate, $endDate)
{
    global $myTransfermoneyEx;
    global $smarty;


    $transfermoneyData = $myTransfermoneyEx->queryWithDate($startDate, $endDate);
    // assign your db results to the template
    $smarty->assign('transfermoneyData', $transfermoneyData);
}

//show By one Date
function showByOneDate($condition, $date)
{
    global $myTransfermoneyEx;
    global $smarty;


    $transfermoneyData = $myTransfermoneyEx->queryWithOneDate($condition, $date);
    // assign your db results to the template
    $smarty->assign('transfermoneyData', $transfermoneyData);
}

function tempdelete($transfermoneyId)
{
    //to use the variable out side the funcion
    global $myTransfermoney;
    global $myTransfermoneyRecord;
    global $myTransfermoneyEx;
    global $mySaveRecord;

    $dailyentryid = $_GET['action'];
    $singleTransfermoney = $myTransfermoneyEx->loadTransfermoneyById($transfermoneyId);

    try {
        if ($singleTransfermoney->conditions == 0) {

            //get transfermoneyvalue by transfermoneyid
            $transfermoneyData = $myTransfermoneyRecord->load($transfermoneyId);
            $transfermoneyValue = $transfermoneyData->transfermoneyvalue;
            $saveidFrom = $transfermoneyData->saveidfrom;
            $saveidTo = $transfermoneyData->saveidto;
            //
            $currencyId = $transfermoneyData->currencyId;
            $cFactor = $transfermoneyData->conversionFactor;
            $transfermoneyValueCurr = $transfermoneyData->transfermoneyvalueInCurrency;
            $cFactorFrom = $transfermoneyData->conversionFactorFrom;
            $cFactorTo = $transfermoneyData->conversionFactorTo;
            //
            $saveDataFrom = $mySaveRecord->load($saveidFrom);
            $saveDataTo = $mySaveRecord->load($saveidTo);
            $saveValuebeforeValid = 1;
            /////////////////check saveto value before delete transfer//////////////////////

            if ($transfermoneyValue > 0) {
                //get save value
                $saveData = getSaveValueBefore($saveidTo);
                $saveToValueBefore = $saveData[0];
                $saveCFactor = $cFactorTo; //$saveData[1]; //use old $cFactorFrom
                $transfermoneyValueInSaveCurr = round(($transfermoneyValue * $saveCFactor), 4); //convert from main curr
                $saveToValueafterValid = $saveToValueBefore - $transfermoneyValueInSaveCurr;

                if ($saveToValueafterValid >= 0) {
                    $saveValuebeforeValid = 1;
                } else {

                    $note = "لا يوجد بالخزنة" . $singleTransfermoney->savetoname . "  المبلغ الكافى لحذف تحويل  " . $singleTransfermoney->transfermoneyvalue . "من" . $singleTransfermoney->savefromname . "إلى" . $singleTransfermoney->savetoname . "";

                    $saveValuebeforeValid = 0;
                    return array($note, $saveValuebeforeValid);
                }
            }


            $myTransfermoney->conditions = 1;
            $myTransfermoney->transfermoneydate = date("Y-m-d");
            $myTransfermoney->userid = $_SESSION['userid'];
            $myTransfermoney->transfermoneyid = $transfermoneyId;

            $myTransfermoneyEx->updateCondition($myTransfermoney);


            if ($transfermoneyValue > 0) {
                //get saveToValue before and saveToValue after mins transfermoneyValue
                $saveToData = getSaveValueAndMins($saveidTo, $transfermoneyValue, $cFactorTo);
                $saveToId = $saveToData[0];
                $saveToValuebefore = $saveToData[1];
                $saveToValueafter = $saveToData[2];
                $transfermoneyValueCurr = $saveToData[3]; //needed because of currency
                $saveConversionFactorTo = $saveToData[4]; //needed because of currency
                //update saveTo value after transfer
                updateSave($saveToId, $saveToValueafter);

                //insert into savedaily tbl from saveto
                insertSavedaily($saveToValuebefore, $transfermoneyValueCurr, 1, $saveToId, "تحويل امول الى الخزنة  [ " . $saveDataFrom->savename . " ] ", $transfermoneyId, $saveToValueafter, "transfermoneyController.php");



                //get saveFromValue before and saveFromValue after Plus transfermoneyValue
                $saveFromData = getSaveValueAndPlus($saveidFrom, $transfermoneyValue, $cFactorFrom);
                $saveFromId = $saveFromData[0];
                $saveFromValuebefore = $saveFromData[1];
                $saveFromValueafter = $saveFromData[2];
                $transfermoneyValueCurr = $saveFromData[3]; //needed because of currency
                $saveConversionFactorFrom = $saveFromData[4]; //needed because of currency
                //update saveFrom value after transfer
                updateSave($saveFromId, $saveFromValueafter);

                //insert into savedaily tbl from saveFrom
                insertSavedaily($saveFromValuebefore, $transfermoneyValueCurr, 0, $saveFromId, "تحويل امول من الخزنة  [ " . $saveDataTo->savename . " ] ", $transfermoneyId, $saveFromValueafter, "transfermoneyController.php");
            }
        }

        $note = "success";
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء حذف التحويل";
        $saveValuebeforeValid = 2;
    }

    reverseEntryWithItsID($dailyentryid);
    return array($note, $saveValuebeforeValid);
}

function returndelete($transfermoneyId)
{

    //to use the variable out side the funcion
    global $myTransfermoney;
    global $myTransfermoneyRecord;
    global $myTransfermoneyEx;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    $singleTransfermoney = $myTransfermoneyEx->loadTransfermoneyById($transfermoneyId);

    try {
        if ($singleTransfermoney->conditions == 1) {
            //get transfermoneyvalue by transfermoneyid
            $transfermoneyData = $myTransfermoneyRecord->load($transfermoneyId);
            $transfermoneyValue = $transfermoneyData->transfermoneyvalue;
            $saveidFrom = $transfermoneyData->saveidfrom;
            $saveidTo = $transfermoneyData->saveidto;
            //
            $currencyId = $transfermoneyData->currencyId;
            $cFactor = $transfermoneyData->conversionFactor;
            $transfermoneyValueCurr = $transfermoneyData->transfermoneyvalueInCurrency;
            $cFactorFrom = $transfermoneyData->conversionFactorFrom;
            $cFactorTo = $transfermoneyData->conversionFactorTo;
            //

            $saveDataFrom = $mySaveRecord->load($saveidFrom);
            $saveDataTo = $mySaveRecord->load($saveidTo);

            $saveValuebeforeValid = 1;
            /////////////////check savefrom value before add transfer//////////////////////

            if ($transfermoneyValue > 0) {
                //get save value
                $saveData = getSaveValueBefore($saveidFrom);
                $saveFromValueBefore = $saveData[0];
                $saveCFactor = $cFactorFrom; //$saveData[1]; //use old $cFactorFrom
                $transfermoneyValueInSaveCurr = round(($transfermoneyValue * $saveCFactor), 4); //convert from main curr
                $saveFromValueafterValid = $saveFromValueBefore - $transfermoneyValueInSaveCurr;
                if ($saveFromValueafterValid >= 0) {
                    $saveValuebeforeValid = 1;
                } else {
                    $note = "لا يوجد بالخزنة" . $singleTransfermoney->savefromname . "  المبلغ الكافى لاعادة حذف تحويل  " . $singleTransfermoney->transfermoneyvalue . "من" . $singleTransfermoney->savefromname . "إلى" . $singleTransfermoney->savetoname . "";

                    $saveValuebeforeValid = 0;
                    return array($note, $saveValuebeforeValid);
                }
            }


            $myTransfermoney->conditions = 0;
            $myTransfermoney->transfermoneydate = date("Y-m-d");
            $myTransfermoney->userid = $_SESSION['userid'];
            $myTransfermoney->transfermoneyid = $transfermoneyId;

            $myTransfermoneyEx->updateCondition($myTransfermoney);


            if ($transfermoneyValue > 0) {
                //get saveFromValue before and saveFromValue after mins transfermoneyValue
                $saveFromData = getSaveValueAndMins($saveidFrom, $transfermoneyValue, $cFactorFrom);
                $saveFromId = $saveFromData[0];
                $saveFromValuebefore = $saveFromData[1];
                $saveFromValueafter = $saveFromData[2];
                $transfermoneyValueCurr = $saveFromData[3]; //needed because of currency
                $saveConversionFactorFrom = $saveFromData[4]; //needed because of currency
                //update saveFrom value after transfer
                updateSave($saveFromId, $saveFromValueafter);

                //insert into savedaily tbl from savefrom
                insertSavedaily($saveFromValuebefore, $transfermoneyValueCurr, 1, $saveFromId, "تحويل امول الى الخزنة  [ " . $saveDataFrom->savename . " ] ", $transfermoneyId, $saveFromValueafter, "transfermoneyController.php");



                //get saveToValue before and saveToValue after Plus transfermoneyValue
                $saveToData = getSaveValueAndPlus($saveidTo, $transfermoneyValue, $cFactorTo);
                $saveToId = $saveToData[0];
                $saveToValuebefore = $saveToData[1];
                $saveToValueafter = $saveToData[2];
                $transfermoneyValueCurr = $saveToData[3]; //needed because of currency
                $saveConversionFactorTo = $saveToData[4]; //needed because of currency
                //update saveTo value after transfer
                updateSave($saveToId, $saveToValueafter);

                //insert into savedaily tbl from saveTo
                insertSavedaily($saveToValuebefore, $transfermoneyValueCurr, 0, $saveToId, "تحويل امول من الخزنة  [ " . $saveDataTo->savename . " ] ", $transfermoneyId, $saveToValueafter, "transfermoneyController.php");


                ///////////////////////////// daily entry
                $saveDataFrom = $mySaveRecord->load($saveidFrom);

                // start creditor
                $fromTreeId = $saveDataFrom->treeId;

                //$oldSave = $myTransfermoneyRecord->load($fromTreeId);

                $dailyEntryCreditorArray = array();

                $dailyEntryCreditor->accountstreeid = $fromTreeId;
                $dailyEntryCreditor->value = $transfermoneyValue;

                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

                // end creditor
                // start debtor
                $toSave = $mySaveRecord->load($saveToId);


                $dailyEntry->entryComment = 'اضافة تحويل من ' . $saveDataFrom->savename . 'الى' . $toSave->savename;
                $toTreeId = $toSave->treeId;

                $dailyEntryDebtor->accountstreeid = $toTreeId;
                $dailyEntryDebtor->value = $transfermoneyValue;
                $dailyEntryDebtorArray = array();

                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

                $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $transfermoneyId, "transfermoneyController.php?do=show&id=$transfermoneyId");

                $did = $returnedData[1];

                $rowData = $myTransfermoneyRecord->load($transfermoneyId);

                $myTransfermoney->conditions = $rowData->conditions;
                $myTransfermoney->saveidfrom = $rowData->saveidfrom;
                $myTransfermoney->saveidto = $rowData->saveidto;
                $myTransfermoney->transfermoneydate = $rowData->transfermoneydate;
                $myTransfermoney->transfermoneyvalue = $rowData->transfermoneyvalue;
                $myTransfermoney->userid = $rowData->userid;
                $myTransfermoney->dailyentryid = $did;

                $myTransfermoneyRecord->update($myTransfermoney);
            }
        }
        $note = "success";
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء اعادة حذف التحويل";
        $saveValuebeforeValid = 2;
    }


    return array($note, $saveValuebeforeValid);
}

//edit from transfer tbl
function editprint()
{
    //to use the variable out side the funcion
    global $myTransfermoneyEx;

    $transfermoneyId = $_GET['id'];

    $loadData = $myTransfermoneyEx->loadTransfermoneyById($transfermoneyId);

    return $loadData;
}

//edit from transfer tbl
function edit()
{
    //to use the variable out side the funcion
    global $myTransfermoneyEx;

    $transfermoneyId = $_GET['transfermoneyid'];

    $loadData = $myTransfermoneyEx->loadTransfermoneyById($transfermoneyId);

    return $loadData;
}

function executeOperation()
{
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $smarty;

    $outputString = "";

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];

    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $transfermoneyId) {

            if ($operationType == '1') {
                //tempdelete
                $note = tempdelete($transfermoneyId);
                if ($note[0] != "success") {
                    $outputString .= $note[0] . "<br/>";
                } else {
                    $outputString .= "تمت العملية بنجاح <br/>";
                }
            } elseif ($operationType == "2") {
                //returndelete
                $note = returndelete($transfermoneyId);
                if ($note[0] != "success") {
                    $outputString .= $note[0] . "<br/>";
                } else {
                    $outputString .= "تمت العملية بنجاح <br/>";
                }
            }
        }

        $smarty->assign("outputString", $outputString);
    }
}

// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;
    global $mySaveEx;

    $saveData = $mySaveEx->loadEx($saveid); //$mySaveRecord->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return array($saveValuebefore, $saveData->conversionFactor, $saveData->currencyId);
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged, $saveConversionFactor = 0)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    $saveData = $mySaveEx->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged, $saveConversionFactor = 0)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    $saveData = $mySaveEx->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

// update in Save tbl
function updateSave($saveid, $savevalueafter)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

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

    $mySaveEx->updateSaveValue($mySave);
}

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

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

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

    $mySavedailyRecord->insert($mySavedaily);
}

function delete($transfermoneyIdold)
{

    //to use the variable out side the funcion
    global $myTransfermoney;
    global $myTransfermoneyRecord;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;
    global $mySaveRecord;
    //Transaction
    $transactions = new Transaction();
    $rowDataold = $myTransfermoneyRecord->load($transfermoneyIdold);

    $saveidFrom = $rowDataold->saveidto;
    $saveidTo = $rowDataold->saveidfrom;
    $transfermoneyValue = $rowDataold->transfermoneyvalue;
    $comment = $rowDataold->comment;
    //
    $currencyId = $rowDataold->currencyId;
    $cFactor = $rowDataold->conversionFactor;
    $transfermoneyValueCurr = $rowDataold->transfermoneyvalueInCurrency;
    $cFactorTo = $rowDataold->conversionFactorFrom;
    $cFactorFrom = $rowDataold->conversionFactorTo;
    //

    $saveDataFrom = $mySaveRecord->load($saveidFrom);
    $saveDataTo = $mySaveRecord->load($saveidTo);

    $saveValuebeforeValid = 1;
    /////////////////check savefrom value before transfer//////////////////////

    if ($transfermoneyValue > 0) {
        $saveData = getSaveValueBefore($saveidFrom);
        $saveFromValueBefore = $saveData[0];
        $saveCFactor = $cFactorFrom; //$saveData[1];//use old $cFactorFrom
        $transfermoneyValueInSaveCurr = round(($transfermoneyValue * $saveCFactor), 4); //convert from main curr
        $saveFromValueafterValid = $saveFromValueBefore - $transfermoneyValueInSaveCurr;
        if ($saveFromValueafterValid >= 0) {
            $saveValuebeforeValid = 1;
        } else {
            $saveValuebeforeValid = 0;
            return $saveValuebeforeValid;
        }
    }


    $transfermoneyId = $transfermoneyIdold;

    if ($transfermoneyValue > 0) {
        try {
            $rowDataold->conditions = 2;
            $myTransfermoneyRecord->update($rowDataold);

            //get saveFromValue before and saveFromValue after mins transfermoneyValue
            $saveFromData = getSaveValueAndMins($saveidFrom, $transfermoneyValue, $cFactorFrom);
            $saveFromId = $saveFromData[0];
            $saveFromValuebefore = $saveFromData[1];
            $saveFromValueafter = $saveFromData[2];
            $transfermoneyValueCurr = $saveFromData[3]; //needed because of currency
            $saveConversionFactorFrom = $saveFromData[4]; //needed because of currency
            //update saveFrom value after add transfer
            updateSave($saveFromId, $saveFromValueafter);

            //insert into savedaily tbl from savefrom
            insertSavedaily($saveFromValuebefore, $transfermoneyValueCurr, 1, $saveFromId, "الغاء تحويل امول من الخزنة  [ " . $saveDataTo->savename . " ] ", $transfermoneyId, $saveFromValueafter, "transfermoneyController.php");



            //get saveToValue before and saveToValue after Plus transfermoneyValue
            $saveToData = getSaveValueAndPlus($saveidTo, $transfermoneyValue, $cFactorTo);
            $saveToId = $saveToData[0];
            $saveToValuebefore = $saveToData[1];
            $saveToValueafter = $saveToData[2];
            $transfermoneyValueCurr = $saveToData[3]; //needed because of currency
            $saveConversionFactorTo = $saveToData[4]; //needed because of currency
            //update saveTo value after add transfer
            updateSave($saveToId, $saveToValueafter);

            //insert into savedaily tbl from saveTo
            insertSavedaily($saveToValuebefore, $transfermoneyValueCurr, 0, $saveToId, "الغاء تحويل امول الى الخزنة  [ " . $saveDataFrom->savename . " ] ", $transfermoneyId, $saveToValueafter, "transfermoneyController.php");

            ///////////////////////////// daily entry

            reverseEntryWithItsID($rowDataold->dailyentryid);
            $transactions->commit();
        } catch (Exception $ex) {
            $transactions->rollback();
            echo $ex;
            die();
        }
    }

    // end debtor
    return $saveValuebeforeValid;
}
