<?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");
//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 :- SaveCloseCTRL تقفيل الخزن

  OPERTATION in Controller

  1-display add form
  2- add in SaveClose 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
//SaveClose
$mySaveClose = new Saveclose();
$mySaveCloseRecord = new SavecloseMySqlDAO();
$mySaveCloseEx = new SavecloseMySqlExtDAO();

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

$myUserGroup = new Usergroup();
$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroupEx = new UsergroupMySqlExtDAO();

$myUserRecord = new UserMySqlDAO();

$userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']);
$smarty->assign('userGroupData', $userGroupData);
$userData = $myUserRecord->load($_SESSION['userid']);
$smarty->assign('userData', $userData);
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
            $saves = $mySaveEx->queryAllEX2();
        } else {
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $mySaveEx->queryAllEX2($queryString);
        }
        $smarty->assign("allSave", $saves);
        $smarty->assign("saveid", $_SESSION['saveid']);
    } else {
        $queryString = ' and saveid = ' . $_SESSION['saveid'] . ' ';
        $save = $mySaveEx->queryAllEXOne2($queryString);
        $smarty->assign('save', $save);
        $smarty->assign('saveid', $_SESSION['saveid']);
    }

    // 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="saveCloseController.php?do=show">تقفيل الخزن</a> > اضافة تقفيل', 'saveCloseController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


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

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

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

    // here the function that do the action
    try {
        $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 = "saveCloseController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = "لا يوجد بالخزنة المبلغ الكافى للتقفيل";

            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $id = (int) $_REQUEST['id'];
    if (!isset($startDate) && !isset($endDate)) {
        $startDate = $endDate = date('Y-m-d');
    }
    $queryString = '';
    $message = '';
    if ($id > 0) {
        $queryString .= " AND saveclose.savecloseid = $id  ";
        $message = " عرض تقفيلات الخزن :" . "برقم:" . $id;
    } else {
        $message .= "";
    }

    if ($startDate) {
        $queryString .= ' AND saveclosedate >= "' . $startDate . '"  ';
        $message .= " عرض تقفيلات الخزن من:" . $startDate . '';
    }

    if ($endDate) {
        $queryString .= ' AND saveclosedate <= "' . $endDate . '"  ';
        $message .= " عرض تقفيلات الخزن الى:" . $endDate . '';
    }

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

    $savecloseData = $mySaveCloseEx->queryAllData($queryString);
    $smarty->assign('savecloseData', $savecloseData);
    $smarty->assign('message', $message);


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

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


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

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

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

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



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


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

    $smarty->assign("customPrint", 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("customSaveClose", 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 SaveClose tbl
function add() {
    //to use the variable out side the funcion
    global $mySaveClose;
    global $mySaveCloseRecord;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    $saveidFrom = $_POST['saveidfrom'];
    $saveidTo = (int) $userData->closeSavid;
    $saveidTo = ($saveidTo < 1) ? 1 : $saveidTo;
    $savecloseValue = $_POST['saveclosevalue'];
    $comment = $_POST['comment'];

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

    //add in SaveClose tbl
    $mySaveClose->conditions = 0;
    $mySaveClose->saveidfrom = $saveidFrom;
    $mySaveClose->saveidto = $saveidTo;
    $mySaveClose->saveclosedate = date("Y-m-d");
    $mySaveClose->saveclosevalue = $savecloseValue;
    $mySaveClose->userid = $_SESSION["userid"];
    $mySaveClose->dailyentryid = 0;
    $mySaveClose->comment = $comment;
    $mySaveClose->currencyId = 1; // $currencyId;


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

    $saveFromCurrencyId = 1;
    $savecloseId = $mySaveCloseRecord->insert($mySaveClose);

    if ($savecloseValue > 0) {
        $saveFromData = getSaveValueAndMins($saveidFrom, $savecloseValue);
        $saveFromId = $saveFromData[0];
        $saveFromValuebefore = $saveFromData[1];
        $saveFromValueafter = $saveFromData[2];
        $savecloseValueCurr = $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, $savecloseValueCurr, 1, $saveFromId, "تقفيل الخزنة  [ " . $saveDataFrom->savename . " ] ", $savecloseId, $saveFromValueafter, "saveCloseController.php");


        //get saveToValue before and saveToValue after Plus SaveCloseValue
        $saveToData = getSaveValueAndPlus($saveidTo, $savecloseValue);
        $saveToId = $saveToData[0];
        $saveToValuebefore = $saveToData[1];
        $saveToValueafter = $saveToData[2];
        $savecloseValueCurr = $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, $savecloseValueCurr, 0, $saveToId, "تقفيل الخزنة  [ " . $saveDataFrom->savename . " ] ", $savecloseId, $saveToValueafter, "saveCloseController.php");

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

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

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

        $dailyEntryCreditorArray = array();

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

        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

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


        $dailyEntry->entryComment = 'تقفيل خزنة ' . $saveDataFrom->savename;
        $toTreeId = $toSave->treeId;

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

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

            $did = $returnedData[1];

            $rowData = $mySaveCloseRecord->load($savecloseId);

            $mySaveClose->conditions = $rowData->conditions;
            $mySaveClose->saveidfrom = $rowData->saveidfrom;
            $mySaveClose->saveidto = $rowData->saveidto;
            $mySaveClose->saveclosedate = $rowData->saveclosedate;
            $mySaveClose->saveclosevalue = $rowData->saveclosevalue;
            $mySaveClose->userid = $rowData->userid;
            $mySaveClose->dailyentryid = $did;
            $mySaveClose->conversionFactorFrom = $saveConversionFactorFrom;
            $mySaveClose->conversionFactorTo = $saveConversionFactorTo;

            $mySaveCloseRecord->update($mySaveClose);
            $transactions->commit();
        } catch (Exception $ex) {
            $transactions->rollback();
        }
    }

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

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

    $savecloseData = $mySaveCloseEx->queryWithOrder();

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

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


    $savecloseData = $mySaveCloseEx->queryWithQueryString(" and  saveclose.savecloseid=$id ");
    // assign your db results to the template
    $smarty->assign('savecloseData', $savecloseData);
}

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


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

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


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

function tempdelete($savecloseId) {
    //to use the variable out side the funcion
    global $mySaveClose;
    global $mySaveCloseRecord;
    global $mySaveCloseEx;
    global $mySaveRecord;

    $dailyentryid = $_GET['action'];
    $singleSaveClose = $mySaveCloseEx->loadSaveCloseById($savecloseId);

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

            //get SaveClosevalue by SaveCloseid
            $savecloseData = $mySaveCloseRecord->load($savecloseId);
            $savecloseValue = $savecloseData->saveclosevalue;
            $saveidFrom = $savecloseData->saveidfrom;
            $saveidTo = $savecloseData->saveidto;
            //
            $currencyId = $savecloseData->currencyId;
            $cFactor = $savecloseData->conversionFactor;
            $savecloseValueCurr = $savecloseData->saveclosevalueInCurrency;
            $cFactorFrom = $savecloseData->conversionFactorFrom;
            $cFactorTo = $savecloseData->conversionFactorTo;
            //
            $saveDataFrom = $mySaveRecord->load($saveidFrom);
            $saveDataTo = $mySaveRecord->load($saveidTo);
            $saveValuebeforeValid = 1;
            /////////////////check saveto value before delete transfer//////////////////////

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

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

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

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


            $mySaveClose->conditions = 1;
            $mySaveClose->saveclosedate = date("Y-m-d");
            $mySaveClose->userid = $_SESSION['userid'];
            $mySaveClose->savecloseid = $savecloseId;

            $mySaveCloseEx->updateCondition($mySaveClose);


            if ($savecloseValue > 0) {
                //get saveToValue before and saveToValue after mins SaveCloseValue
                $saveToData = getSaveValueAndMins($saveidTo, $savecloseValue, $cFactorTo);
                $saveToId = $saveToData[0];
                $saveToValuebefore = $saveToData[1];
                $saveToValueafter = $saveToData[2];
                $savecloseValueCurr = $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, $savecloseValueCurr, 1, $saveToId, "تقفيل الخزنة  [ " . $saveDataFrom->savename . " ] ", $savecloseId, $saveToValueafter, "saveCloseController.php");



                //get saveFromValue before and saveFromValue after Plus SaveCloseValue
                $saveFromData = getSaveValueAndPlus($saveidFrom, $savecloseValue, $cFactorFrom);
                $saveFromId = $saveFromData[0];
                $saveFromValuebefore = $saveFromData[1];
                $saveFromValueafter = $saveFromData[2];
                $savecloseValueCurr = $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, $savecloseValueCurr, 0, $saveFromId, "تقفيل الخزنة  [ " . $saveDataTo->savename . " ] ", $savecloseId, $saveFromValueafter, "saveCloseController.php");
            }
        }

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

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

function returndelete($savecloseId) {

    //to use the variable out side the funcion
    global $mySaveClose;
    global $mySaveCloseRecord;
    global $mySaveCloseEx;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    $singleSaveClose = $mySaveCloseEx->loadSaveCloseById($savecloseId);

    try {
        if ($singleSaveClose->conditions == 1) {
            //get SaveClosevalue by SaveCloseid
            $SaveCloseData = $mySaveCloseRecord->load($savecloseId);
            $savecloseValue = $SaveCloseData->saveclosevalue;
            $saveidFrom = $SaveCloseData->saveidfrom;
            $saveidTo = $SaveCloseData->saveidto;
            //
            $currencyId = $SaveCloseData->currencyId;
            $cFactor = $SaveCloseData->conversionFactor;
            $savecloseValueCurr = $SaveCloseData->saveclosevalueInCurrency;
            $cFactorFrom = $SaveCloseData->conversionFactorFrom;
            $cFactorTo = $SaveCloseData->conversionFactorTo;
            //

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

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

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

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


            $mySaveClose->conditions = 0;
            $mySaveClose->saveclosedate = date("Y-m-d");
            $mySaveClose->userid = $_SESSION['userid'];
            $mySaveClose->savecloseid = $savecloseId;

            $mySaveCloseEx->updateCondition($mySaveClose);


            if ($savecloseValue > 0) {
                //get saveFromValue before and saveFromValue after mins SaveCloseValue
                $saveFromData = getSaveValueAndMins($saveidFrom, $savecloseValue, $cFactorFrom);
                $saveFromId = $saveFromData[0];
                $saveFromValuebefore = $saveFromData[1];
                $saveFromValueafter = $saveFromData[2];
                $savecloseValueCurr = $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, $savecloseValueCurr, 1, $saveFromId, "تقفيل الخزنة  [ " . $saveDataFrom->savename . " ] ", $savecloseId, $saveFromValueafter, "saveCloseController.php");



                //get saveToValue before and saveToValue after Plus SaveCloseValue
                $saveToData = getSaveValueAndPlus($saveidTo, $savecloseValue, $cFactorTo);
                $saveToId = $saveToData[0];
                $saveToValuebefore = $saveToData[1];
                $saveToValueafter = $saveToData[2];
                $savecloseValueCurr = $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, $savecloseValueCurr, 0, $saveToId, "تقفيل الخزنة  [ " . $saveDataTo->savename . " ] ", $savecloseId, $saveToValueafter, "saveCloseController.php");


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

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

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

                $dailyEntryCreditorArray = array();

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

                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

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


                $dailyEntry->entryComment = 'اضافة تقفيل خزنة ' . $saveDataFrom->savename;
                $toTreeId = $toSave->treeId;

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

                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

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

                $did = $returnedData[1];

                $rowData = $mySaveCloseRecord->load($savecloseId);

                $mySaveClose->conditions = $rowData->conditions;
                $mySaveClose->saveidfrom = $rowData->saveidfrom;
                $mySaveClose->saveidto = $rowData->saveidto;
                $mySaveClose->saveclosedate = $rowData->saveclosedate;
                $mySaveClose->saveclosevalue = $rowData->saveclosevalue;
                $mySaveClose->userid = $rowData->userid;
                $mySaveClose->dailyentryid = $did;

                $mySaveCloseRecord->update($mySaveClose);
            }
        }
        $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 $mySaveCloseEx;

    $SaveCloseId = $_GET['id'];

    $loadData = $mySaveCloseEx->loadSaveCloseById($SaveCloseId);

    return $loadData;
}

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

    $SaveCloseId = $_GET['savecloseid'];

    $loadData = $mySaveCloseEx->loadSaveCloseById($SaveCloseId);

    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 $SaveCloseId) {

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

    //to use the variable out side the funcion
    global $mySaveClose;
    global $mySaveCloseRecord;

    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 = $mySaveCloseRecord->load($SaveCloseIdold);

    $saveidFrom = $rowDataold->saveidto;
    $saveidTo = $rowDataold->saveidfrom;
    $SaveCloseValue = $rowDataold->saveclosevalue;
    $comment = $rowDataold->comment;
    //
    $currencyId = $rowDataold->currencyId;
    $cFactor = $rowDataold->conversionFactor;
    $SaveCloseValueCurr = $rowDataold->saveclosevalueInCurrency;
    $cFactorTo = $rowDataold->conversionFactorFrom;
    $cFactorFrom = $rowDataold->conversionFactorTo;
    //

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

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

    if ($SaveCloseValue > 0) {
        $saveData = getSaveValueBefore($saveidFrom);


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



    $SaveCloseId = $SaveCloseIdold;

    if ($SaveCloseValue > 0) {
        try {
            $rowDataold->conditions = 2;
            $mySaveCloseRecord->update($rowDataold);

            //get saveFromValue before and saveFromValue after mins SaveCloseValue
            $saveFromData = getSaveValueAndMins($saveidFrom, $SaveCloseValue, $cFactorFrom);
            $saveFromId = $saveFromData[0];
            $saveFromValuebefore = $saveFromData[1];
            $saveFromValueafter = $saveFromData[2];
            $SaveCloseValueCurr = $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, $SaveCloseValueCurr, 1, $saveFromId, "الغاء تقفيل الخزنة  [ " . $saveDataTo->savename . " ] ", $SaveCloseId, $saveFromValueafter, "saveCloseController.php");



            //get saveToValue before and saveToValue after Plus SaveCloseValue
            $saveToData = getSaveValueAndPlus($saveidTo, $SaveCloseValue, $cFactorTo);
            $saveToId = $saveToData[0];
            $saveToValuebefore = $saveToData[1];
            $saveToValueafter = $saveToData[2];
            $SaveCloseValueCurr = $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, $SaveCloseValueCurr, 0, $saveToId, "الغاء تقفيل الخزنة  [ " . $saveDataFrom->savename . " ] ", $SaveCloseId, $saveToValueafter, "saveCloseController.php");

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

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

    // end debtor
    return $saveValuebeforeValid;
}
