<?php
include("../public/impOpreation.php");
include_once('dailyentryfun.php');
$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");

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

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

//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();

//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = $supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();

//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
$Expense = new Expense();
$ExpenseExt = new ExpensesMySqlExtDAO();

$expensesType = new Expensestype();
$expensesTypeDAO = new ExpensestypeMySqlDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();


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

if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    $smarty->display("header.html");

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


    $allSupplier = $supplierExt->queryByCondition(0);
    $smarty->assign('allSupplier', $allSupplier);


    $smarty->display("dollarEarningsView/add.html");

    $smarty->assign("customTransfermoney", 1);
    $smarty->display("footer.html");
} 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) && !$id) {
        $startDate = $endDate = date('Y-m-d');
    }

    $queryString = '';
    $message = '';
    if ($id > 0) {
        $queryString .= " AND dollarearnings.id = $id  ";
        $message = " عرض الحصائل الدولارية :" . "برقم:" . $id;
    } else {
        $message .= "";
    }

    if ($startDate) {
        $queryString .= ' AND sysdate >= "' . $startDate . ' 00:00:00"  ';
        $message .= " عرض الحصائل الدولارية الخزن من:" . $startDate . '';
    }

    if ($endDate) {
        $queryString .= ' AND sysdate <= "' . $endDate . '11:59:59"  ';
        $message .= " عرض الحصائل الدولارية الخزن الى:" . $endDate . '';
    }

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

    $dollarEarningsData = R::getAll('SELECT dollarearnings.*, savefrom.savename as savefromname,saveto.savename as savetoname, supplier.suppliername
		    FROM dollarearnings 
            JOIN save savefrom ON dollarearnings.saveidfrom = savefrom.saveid 
            JOIN save saveto ON dollarearnings.saveidto = saveto.saveid
            LEFT JOIN supplier ON dollarearnings.supplierid = supplier.supplierid
		    where savefrom.conditions = 0 and saveto.conditions = 0   ' . $queryString . '
		    order by id desc');
    $smarty->assign('dollarEarningsData', $dollarEarningsData);
    $smarty->assign('message', $message);


    $smarty->display("header.html");
    $smarty->display("dollarEarningsView/show.html");
    $smarty->display("footer.html");

    $smarty->assign("customCheck", 1);
} else if ($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) {
        header("location:?do=sucess");
    } else {
        $url = "dollarEarningsController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالخزنة المبلغ الكافى لتحويل الاموال";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "editprint") {
    //here the permssion check
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if ($id) {
        $loadData = R::getRow('SELECT dollarearnings.*, savefrom.savename as savefromname,saveto.savename as savetoname, supplier.suppliername
		    FROM dollarearnings 
            JOIN save savefrom ON dollarearnings.saveidfrom = savefrom.saveid 
            JOIN save saveto ON dollarearnings.saveidto = saveto.saveid
            LEFT JOIN supplier ON dollarearnings.supplierid = supplier.supplierid
		    where savefrom.conditions = 0 and saveto.conditions = 0 
			and id =' . $id . '');
        $smarty->assign("loadData", $loadData);
    }

    $smarty->display("header.html");
    $smarty->display("dollarEarningsView/editprint.html");
    $smarty->assign("customPrint", 1);
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    try {
        $id = $_GET['id'];
        delete($id);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");
    $smarty->display("header.html");

    $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if ($id) {
        $loadData =  R::getRow('SELECT dollarearnings.*, savefrom.savename as savefromname,saveto.savename as savetoname, supplier.suppliername
                FROM dollarearnings 
                JOIN save savefrom ON dollarearnings.saveidfrom = savefrom.saveid 
                JOIN save saveto ON dollarearnings.saveidto = saveto.saveid
                LEFT JOIN supplier ON dollarearnings.supplierid = supplier.supplierid
                where savefrom.conditions = 0 and saveto.conditions = 0 
                and id =' . $id . '');
        $smarty->assign("loadData", $loadData);
        $saveidfromval = $mySaveRecord->load($loadData['saveidfrom']);
        $smarty->assign("saveidfromval", $saveidfromval);
    }


    $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", $loadData['saveidfrom']);
    } else {
        $queryString = ' and saveid = ' . $loadData['saveidfrom'] . ' ';
        $save = $mySaveEx->queryAllEXOne2($queryString);
        $smarty->assign('save', $save);
        $smarty->assign('saveid', $loadData['saveidfrom']);
    }

    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

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


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

    $allSupplier = $supplierExt->queryByCondition(0);
    $smarty->assign('allSupplier', $allSupplier);

    $smarty->display("dollarEarningsView/edit.html");
    $smarty->assign("customTransfermoney", 1);
    $smarty->display("footer.html");
} elseif ($do == "update") {

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

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

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

function loadSave()
{

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

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

    return $saveData;
}

function add()
{
    //to use the variable out side the funcion
    //Dailyentry
    global $dailyEntry;
    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;

    global $mySaveRecord;
    global $currencyEX;

    global $supplierDAO;
    global $expensesType;
    global $expensesTypeDAO;
    global $Programsettingdata;


    //Transaction
    $transactions = new Transaction();

    $saveidFrom = $_POST['saveidfrom'];
    $saveidTo = $_POST['saveidto'];
    //$transfermoneyValue = $_POST['transfermoneyvalue'];
    $supplierid = $_POST['supplierid'];
    $exvalue = $_POST['exvalue'];
    $comment = $_POST['comment'];
    $cFactorTo = (isset($_POST['cFactorTo']) && !empty($_POST['cFactorTo'])) ? (float) $_POST['cFactorTo'] : 1;
    $cFactorFrom = (isset($_POST['cFactorFrom']) && !empty($_POST['cFactorFrom'])) ? (float) $_POST['cFactorFrom'] : 1;

    //
    // $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);
    $currencyIdSaveFrom = (int) $saveDataFrom->currencyId; // Get currency from save table
    $currencyIdSaveTo = (int) $saveDataTo->currencyId;     // Get currency from save table

    $transfermoneyValueCurr = (float) $_POST['transfermoneyvalueCurr'];
    $transfermoneyvalueInCurrencyto = (float) $_POST['transfermoneyvalueCurrSaveTo'];

    //add in dollarearnings tbl
    $dollarEarning = R::dispense('dollarearnings');
    $dollarEarning->userid = $_SESSION["userid"];
    $dollarEarning->sysdate = date("Y-m-d H:i:s");
    $dollarEarning->saveidfrom = $saveidFrom;
    $dollarEarning->saveidto = $saveidTo;
    $dollarEarning->conditions = 0;
    $dollarEarning->supplierid = $supplierid;
    $dollarEarning->exvalue = $exvalue;
    $dollarEarning->comment = $comment;
    $dollarEarning->dailyentryid = 0;
    $dollarEarning->dailyentryid2 = 0;
    $dollarEarning->currencyidsavefrom = $currencyIdSaveFrom;
    $dollarEarning->currencyidsaveto = $currencyIdSaveTo;
    $dollarEarning->conversionfactorfrom = $cFactorFrom; // Using cFactorTo as the conversion factor
    $dollarEarning->conversionfactorto = $cFactorTo; // Assuming 1 as the base conversion factor for the target currency
    $dollarEarning->transfermoneyvalueincurrencyfrom = $transfermoneyValueCurr;
    $dollarEarning->transfermoneyvalueincurrencyto = $transfermoneyvalueInCurrencyto;

    $dollarEarningId = R::store($dollarEarning);

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

    $saveFromCurrencyId = 1;
    if ($transfermoneyValueCurr > 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;
        }
    }

    if ($transfermoneyValueCurr > 0 && $transfermoneyvalueInCurrencyto > 0) {
        if ($currencyIdSaveTo > 1) {
            $currencyEX->updateConversionFactor($cFactorTo, $currencyIdSaveTo);
        }
        //get saveFromValue before and saveFromValue after mins transfermoneyValue
        $saveFromData = getSaveValueAndMins($saveidFrom, $transfermoneyValueCurr, 1); //1 send cfactor val that dont change val as value is with save curr
        $saveFromId = $saveFromData[0];
        $saveFromValuebefore = $saveFromData[1];
        $saveFromValueafter = $saveFromData[2];
        $transfermoneyValueCurr = $saveFromData[3]; //needed because of currency
        $saveConversionFactorFrom = $saveFromData[4]; //needed because of currency
        //value in main currency
        $saveFromValueBeforeInmainCurr = $saveFromValuebefore;
        $saveFromValueafterInmainCurr = $saveFromValueafter;
        $transfermoneyValueInMainCurrency = $transfermoneyValueCurr;
        if ($cFactorFrom != 1) {
            $saveFromValueBeforeInmainCurr = round(($saveFromValuebefore / $cFactorFrom), 4);
            $saveFromValueafterInmainCurr = round(($saveFromValueafter / $cFactorFrom), 4);
            $transfermoneyValueInMainCurrency = $transfermoneyValueCurr / $cFactorFrom;
        }

        //update saveFrom value after add transfer
        updateSave($saveFromId, $saveFromValueafter);

        //insert into savedaily tbl from savefrom
        insertSavedaily($saveFromValueBeforeInmainCurr, $transfermoneyValueInMainCurrency, 1, $saveFromId, "إضافة حصيلة دولارية من [ " . $saveDataFrom->savename . " ] ", $dollarEarningId, $saveFromValueafterInmainCurr, "dollarEarningsController.php");

        //get saveToValue before and saveToValue after Plus transfermoneyValue
        $saveToData = getSaveValueAndPlus($saveidTo, $transfermoneyvalueInCurrencyto, 1); //1 send cfactor val that dont change val as value is with save curr
        $saveToId = $saveToData[0];
        $saveToValuebefore = $saveToData[1];
        $saveToValueafter = $saveToData[2];
        $transfermoneyValueCurr = $saveToData[3]; //needed because of currency
        $saveConversionFactorTo = $saveToData[4]; //needed because of currency
        //value in main currency
        $saveToValueBeforeInmainCurr = $saveToValuebefore;
        $saveToValueafterInmainCurr = $saveToValueafter;
        if ($cFactorTo != 1) {
            $saveToValueBeforeInmainCurr = round(($saveFromValuebefore / $cFactorTo), 4);
            $saveToValueafterInmainCurr = round(($saveToValueafter / $cFactorTo), 4);
        }
        //update saveTo value after add transfer
        updateSave($saveToId, $saveToValueafter);

        //insert into savedaily tbl from saveTo
        insertSavedaily($saveToValueBeforeInmainCurr, $transfermoneyValueInMainCurrency, 0, $saveToId, "إضافة حصيلة دولارية إلى [ " . $saveDataTo->savename . " ] ", $dollarEarningId, $saveToValueafterInmainCurr, "dollarEarningsController.php");

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

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

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

        $dailyEntryCreditorArray = array();

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

        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

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


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

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

        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        try {
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $dollarEarningId, "dollarEarningsController.php?do=editprint&id=$dollarEarningId");

            $did = $returnedData[1];

            $rowData = R::load('dollarearnings', $dollarEarningId);
            $rowData->dailyentryid = $did;
            R::store($rowData);

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

    if ($exvalue > 0 && $supplierid > 0 && $dollarEarningId > 0) {
        #### affect supplier Debt
        affectSupplierWithExpense($supplierid, $exvalue, $exvalue, $dollarEarningId, $comment, 'add');
        $dataSupplier = $supplierDAO->load($supplierid);
        $idTreeSupplier = $dataSupplier->treeId;

        $dailyEntry->entryComment = 'اضافة حصيلة دولارية على مورد( ' . $dataSupplier->suppliername . ' )';

        //Dailyentrycreditor دائن
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $exvalue;


        $dailyEntryCreditor->accountstreeid = $idTreeSupplier;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

        //get expense type id from programsettings

        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $exvalue;
        $expenseTypeData = $expensesTypeDAO->load($Programsettingdata->dollarExType);

        $treeId = $expenseTypeData->treeId;
        $dailyEntryDebtor->accountstreeid = $treeId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

        try {
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $dollarEarningId, "dollarEarningsController.php?do=editprint&id=$dollarEarningId");

            $did = $returnedData[1];

            $rowData = R::load('dollarearnings', $dollarEarningId);
            $rowData->dailyentryid2 = $did;
            R::store($rowData);

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

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

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

    //to use the variable out side the funcion
    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 $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 $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 affectSupplierWithExpense($supplier, $expensevalue, $suppRemainingVal, $dollarEarningId, $expensecomment, $operation)
{
    global $today;
    global $supplierDAO;

    if ($expensevalue > 0 && $supplier > 0 && $suppRemainingVal > 0) {
        //update supplierdebt
        $supdata = $supplierDAO->load($supplier);
        $deptBefore = $supdata->suppliercurrentDebt;
        if ($operation == 'add') {
            $changeType = 0;
            $processName = 'اضافه حصيلة دولارية على مورد' . $expensecomment;
            $deptAfter = $deptBefore + $suppRemainingVal;
        } elseif ($operation == 'del') {
            $changeType = 1;
            $processName = 'حذف حصيلة دولارية على مورد';
            $deptAfter = $deptBefore - $suppRemainingVal;
        }

        updateSupplierDebt($supplier, $deptAfter, $today);
        insertSupplierDebtChangeupdate($supplier, $deptBefore, $suppRemainingVal, $changeType, $processName, $dollarEarningId, $deptAfter, "dollarEarningsController.php", $expensecomment, $today);
    }
}

function updateSupplierDebt($supplierId, $supplierDebtAfter)
{
    global $supplier;
    global $supplierExt;
    global $today;

    //update clientdebt in client tbl
    $supplier->userid = $_SESSION['userid'];
    $supplier->suppliercurrentDebt = $supplierDebtAfter;
    $supplier->supplierid = $supplierId;
    $supplier->supplierdate = $today;

    $supplierExt->updatedept($supplier);
}

function insertSupplierDebtChangeupdate($supplierId, $supplierDebtChangeBefore, $supplierDebtChangeAmount, $supplierDebtChangeType, $processname, $supplierDebtChangeModelId, $supplierDebtChangeAfter, $tablename, $comment, $mydate)
{
    global $supplierDebtChange;
    global $supplierDebtChangeDAO;

    $supplierDebtChange->comment = $comment;
    $supplierDebtChange->processname = $processname;
    $supplierDebtChange->supplierdebtchangeafter = $supplierDebtChangeAfter;
    $supplierDebtChange->supplierdebtchangeamount = $supplierDebtChangeAmount;
    $supplierDebtChange->supplierdebtchangebefore = $supplierDebtChangeBefore;
    $supplierDebtChange->supplierdebtchangedate = $mydate;
    $supplierDebtChange->supplierdebtchangemodelid = $supplierDebtChangeModelId;
    $supplierDebtChange->supplierdebtchangetype = $supplierDebtChangeType;
    $supplierDebtChange->supplierid = $supplierId;
    $supplierDebtChange->tablename = $tablename;
    $supplierDebtChange->userid = $_SESSION['userid'];
    $supplierDebtChange->dailyentryid = 0;
    $supplierDebtChangeDAO->insert($supplierDebtChange);
}

function delete($oldid)
{
    global $mySaveRecord;
    //Transaction
    $transactions = new Transaction();
    $rowDataold = R::load('dollarearnings', $oldid);

    $saveidFrom = $rowDataold->saveidto;
    $saveidTo = $rowDataold->saveidfrom;
    $comment = $rowDataold->comment;
    //
    $currencyIdSaveFrom = $rowDataold->currencyidsaveto;
    $currencyIdSaveTo = $rowDataold->currencyidsavefrom;
    $cFactorFrom = $rowDataold->conversionfactorto;
    $cFactorTo = $rowDataold->currencyidsavefrom;
    $transfermoneyValueCurr = $rowDataold->transfermoneyvalueincurrencyto;
    $transfermoneyvalueInCurrencyto = $rowDataold->transfermoneyvalueincurrencyfrom;
    //

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

    $saveValuebeforeValid = 1;
    /////////////////check savefrom value before transfer//////////////////////
    //value in main currency
    $transfermoneyValueInMainCurrency = $transfermoneyValueCurr;
    if ($cFactorFrom != 1) {
        $transfermoneyValueInMainCurrency = $transfermoneyValueCurr / $cFactorFrom;
    }
    if ($transfermoneyValueCurr > 0) {
        $saveData = getSaveValueBefore($saveidFrom);

        $saveFromValueBefore = $saveData[0];
        $saveFromValueBeforeInMainCurr = $saveData[0] / $saveData[1];
        $saveFromValueafterValid = $saveFromValueBeforeInMainCurr - $transfermoneyValueInMainCurrency;
        if ($saveFromValueafterValid >= 0) {
            $saveValuebeforeValid = 1;
        } else {
            $saveValuebeforeValid = 0;
        }
    }

    $dollarEarningId = $oldid;

    if ($transfermoneyValueCurr > 0 && $transfermoneyvalueInCurrencyto > 0) {
        try {
            $rowDataold->conditions = 2;
            R::store($rowDataold);

           //get saveFromValue before and saveFromValue after mins transfermoneyValue
            $saveFromData = getSaveValueAndMins($saveidFrom, $transfermoneyValueCurr, 1); // 1 to keep value as is (already in save currency)
            $saveFromId = $saveFromData[0];
            $saveFromValuebefore = $saveFromData[1];
            $saveFromValueafter = $saveFromData[2];
            $transfermoneyValueCurr = $saveFromData[3]; //needed because of currency
            $saveConversionFactorFrom = $saveFromData[4]; //needed because of currency
            //value in main currency
            $saveFromValueBeforeInmainCurr = $saveFromValuebefore;
            $saveFromValueafterInmainCurr = $saveFromValueafter;
            $transfermoneyValueInMainCurrency = $transfermoneyValueCurr;
            if ($cFactorFrom != 1) {
                $saveFromValueBeforeInmainCurr = round(($saveFromValuebefore / $cFactorFrom), 4);
                $saveFromValueafterInmainCurr = round(($saveFromValueafter / $cFactorFrom), 4);
                $transfermoneyValueInMainCurrency = $transfermoneyValueCurr / $cFactorFrom;
            }
            //update saveFrom value after add transfer
            updateSave($saveFromId, $saveFromValueafter);

            //insert into savedaily tbl from savefrom
            insertSavedaily($saveFromValueBeforeInmainCurr, $transfermoneyValueInMainCurrency, 1, $saveFromId, "حذف حصيلة دولارية من الخزنة  [ " . $saveDataFrom->savename . " ] ", $dollarEarningId, $saveFromValueafterInmainCurr, "dollarEarningsController.php");



            //get saveToValue before and saveToValue after Plus transfermoneyValue
            $saveToData = getSaveValueAndPlus($saveidTo, $transfermoneyvalueInCurrencyto, 1); // 1 to keep value as is (already in save currency)
            $saveToId = $saveToData[0];
            $saveToValuebefore = $saveToData[1];
            $saveToValueafter = $saveToData[2];
            $transfermoneyValueCurr = $saveToData[3]; //needed because of currency
            $saveConversionFactorTo = $saveToData[4]; //needed because of currency
            //value in main currency
            $saveToValueBeforeInmainCurr = $saveToValuebefore;
            $saveToValueafterInmainCurr = $saveToValueafter;
            if ($cFactorTo != 1) {
                $saveToValueBeforeInmainCurr = round(($saveFromValuebefore / $cFactorTo), 4);
                $saveToValueafterInmainCurr = round(($saveToValueafter / $cFactorTo), 4);
            }
            //update saveTo value after add transfer
            updateSave($saveToId, $saveToValueafter);

            //insert into savedaily tbl from saveTo
            insertSavedaily($saveToValueBeforeInmainCurr, $transfermoneyValueInMainCurrency, 0, $saveToId, "حذف حصيلة دولارية الى الخزنة  [ " . $saveDataTo->savename . " ] ", $dollarEarningId, $saveToValueafterInmainCurr, "dollarEarningsController.php");

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

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

    if ($rowDataold->exvalue > 0 && $rowDataold->supplierid > 0 && $dollarEarningId > 0) {
        affectSupplierWithExpense($rowDataold->supplierid, $rowDataold->exvalue, $rowDataold->exvalue, $dollarEarningId, $rowDataold->comment, 'del');
    }
    // end debtor
    return $saveValuebeforeValid;
}

function loadsaveExpectId($saveIdFrom)
{

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

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

    return $saveData;
}
