<?php

//the global file operation
include("../public/impOpreation.php");
include_once("initiateStaticSessionCommingWithCurl.php");
//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
include_once("dailyentryfun.php");

//here the db files that include in the file
include("../public/include_dao.php");
include("../library/uploadImages.php");
include '../library/Classes/PHPExcel/IOFactory.php';

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

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');
//Supplieropen
require_once('../models/dao/SupplieropenDAO.class.php');
require_once('../models/dto/Supplieropen.class.php');
require_once('../models/mysql/SupplieropenMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplieropenMySqlExtDAO.class.php');
//Supplieropendebtchange
require_once('../models/dao/SupplieropendebtchangeDAO.class.php');
require_once('../models/dto/Supplieropendebtchange.class.php');
require_once('../models/mysql/SupplieropendebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplieropendebtchangeMySqlExtDAO.class.php');
//Supplieropenexchangeorclosing
require_once('../models/dao/SupplieropenexchangeorclosingDAO.class.php');
require_once('../models/dto/Supplieropenexchangeorclosing.class.php');
require_once('../models/mysql/SupplieropenexchangeorclosingMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplieropenexchangeorclosingMySqlExtDAO.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');

//Assetscat
require_once('../models/dao/AssetscatDAO.class.php');
require_once('../models/dto/Assetscat.class.php');
require_once('../models/mysql/AssetscatMySqlDAO.class.php');
require_once('../models/mysql/ext/AssetscatMySqlExtDAO.class.php');
//Assets
require_once('../models/dao/AssetsDAO.class.php');
require_once('../models/dto/Asset.class.php');
require_once('../models/mysql/AssetsMySqlDAO.class.php');
require_once('../models/mysql/ext/AssetsMySqlExtDAO.class.php');
//Expensetype
require_once('../models/dao/ExpensestypeDAO.class.php');
require_once('../models/dto/Expensestype.class.php');
require_once('../models/mysql/ExpensestypeMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensestypeMySqlExtDAO.class.php');
//ExpensesDAO
require_once('../models/dao/ExpensesDAO.class.php');
require_once('../models/dto/Expense.class.php');
require_once('../models/mysql/ExpensesMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensesMySqlExtDAO.class.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 :- productController

  OPERTATION in Controller

  1- display add form, add supplier cat and supplier with ajax
  2- add in supplier tbl
  ======================== */

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

//here goes the instances and general variables
//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

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

//Supplieropen
$supplierOpen = new Supplieropen();
$supplierOpenDAO = new SupplieropenMySqlDAO();
$supplierOpenEX = new SupplieropenMySqlExtDAO();
//SupplieropendebtchangeMySqlDAO
$supplierOpenDebtChange = new Supplieropendebtchange();
$supplierOpenDebtChangeDAO = new SupplieropendebtchangeMySqlDAO();
$supplierOpenDebtChangeEX = new SupplieropendebtchangeMySqlExtDAO();
//Supplieropenexchangeorclosing
$supplierOpenExchangeOrClosing = new Supplieropenexchangeorclosing();
$supplierOpenExchangeOrClosingDAO = new SupplieropenexchangeorclosingMySqlDAO();
$supplierOpenExchangeOrClosingEX = new SupplieropenexchangeorclosingMySqlExtDAO();
//
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//Savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$Assetscat = new Assetscat();
$AssetscatDAO = new AssetscatMySqlDAO();
$AssetscatEX = new AssetscatMySqlExtDAO();
//Assets
$myAssets = new Asset();
$myAssetsRecord = new AssetsMySqlDAO();
$myAssetsEx = new AssetsMySqlExtDAO();
//
$ExpensetypeDAO = new ExpensestypeMySqlDAO();
$Expensetype = new Expensestype();
$ExpensetypeEX = new ExpensestypeMySqlExtDAO();
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
$Expense = new Expense();
$ExpenseEX = new ExpensesMySqlExtDAO();

$today = date("Y-m-d H:i:s");

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

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

    //here the smarty templates
    $smarty->display("supplieropenview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    try {
        $flag = add();

        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

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

    $shownData = $supplierOpenDAO->queryByDel(0);
    $smarty->assign("shownData", $shownData);

    $smarty->assign("customCheck", 1);
    $smarty->display("supplieropenview/show.html");
} elseif ($do == "deleteFinaly") {
    include_once("../public/authentication.php");
    try {
        $note = deleteFinaly();

        if ($note == 'success') {
            header("location:?do=sucess");
        } else {
            $url = "supplierControllerOpen.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 == "exchangeorclosing") {
    //here the permssion check
    include_once("../public/authentication.php");

    $saveData = $mySaveEx->queryAllEX2();
    $smarty->assign("saveData", $saveData);
    $supplierOpenAll = $supplierOpenDAO->queryByDel(0);
    $smarty->assign("supplierOpenAll", $supplierOpenAll);


    //here the smarty templates
    $smarty->display("supplieropenview/exchangeorclosing.html");
} elseif ($do == "saveexchangeorclosing") {
    include_once("../public/authentication.php");
    try {
        saveexchangeorclosing();
        $url = "supplierControllerOpen.php?do=showexchangeorclosing";
        $smarty->assign('urldirect', $url);
        $note = 'تمت العملية بنجاح';
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "showexchangeorclosing") {
    include_once("../public/authentication.php");

    $shownData = $supplierOpenExchangeOrClosingEX->queryAllEX();
    $smarty->assign("shownData", $shownData);

    //here the smarty templates
    $smarty->display("supplieropenview/showexchangeorclosing.html");
} elseif ($do == "deleteexchangeorclosing") {
    include_once("../public/authentication.php");

    try {
        deleteexchangeorclosing();
        $url = "supplierControllerOpen.php?do=showexchangeorclosing";
        $smarty->assign('urldirect', $url);
        $note = 'تمت العملية بنجاح';
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}
#
elseif ($do == "supplieropenchange") {
    include_once("../public/authentication.php");

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];

    $queryString = '';
    $message = '';
    if (isset($startDate) && !empty($startDate)) {
        $message .= " من تاريخ  " . $startDate;
        $queryString .= '  AND date( supplieropendebtchange.supplierdebtchangedate ) >= "' . $startDate . '" ';
    }
    if (isset($endDate) && !empty($endDate)) {
        $message .= "  الى تاريخ" . $endDate;
        $queryString .= '  AND date( supplieropendebtchange.supplierdebtchangedate ) <= "' . $endDate . '"  ';
    }
    $smarty->assign('message', $message);


    if (!empty($queryString)) {
        $shownData = $supplierOpenDebtChangeEX->queryAllEX($queryString);
        $smarty->assign("shownData", $shownData);
    }

    //here the smarty templates
    $smarty->display("supplieropenview/supplieropenchange.html");
}
#
elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->assign("customSupplier", 1);

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


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

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

// add in supplier tbl
function add() {
    global $supplierOpen;
    global $supplierOpenDAO;
    global $supplierOpenDebtChange;
    global $supplierOpenDebtChangeDAO;

    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    $suppliername = $_POST["txtName"];
    $suppliercurrentDebt = $_POST["txtDebt"];

    if (!empty($suppliername)) {
        $supplierdate = date('Y-m-d H:i:s');

//        $checkSupplier = $supplierOpenDAO->queryByName($suppliername);


        $treeId = addTreeElement($suppliername, 410, 3, 1, 1, '', 0, 0, 1);
        if ($suppliercurrentDebt != 0) {
            $dailyEntry->entryComment = 'إضافة مدينون الشجرة (حسابات مفتوحة)  ( ' . $suppliername . ' ) ';

            //
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $suppliercurrentDebt;
            $dailyEntryDebtor->accountstreeid = $treeId;
            // start Ras L Maaal
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $suppliercurrentDebt;
            $dailyEntryCreditor->accountstreeid = 121;

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

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


        $supplier->name = $suppliername;
        $supplier->value = $suppliercurrentDebt;
        $supplier->userid = $_SESSION['userid'];
        $supplier->del = 0;
        $supplier->sysdate = $supplierdate;
        $supplier->dailyentryid = $did;
        $supplier->treeId = $treeId;
        //Insert
        $supplierid = $supplierOpenDAO->insert($supplier);


        if (!empty($supplierid)) {
            $Supplierdebtchange->comment = "";
            $Supplierdebtchange->processname = "إضافة مدينون الشجرة (حسابات مفتوحة)";
            $Supplierdebtchange->supplierdebtchangeafter = $suppliercurrentDebt;
            $Supplierdebtchange->supplierdebtchangeamount = $suppliercurrentDebt;
            $Supplierdebtchange->supplierdebtchangebefore = 0;
            $Supplierdebtchange->supplierdebtchangedate = $supplierdate;
            $Supplierdebtchange->supplierdebtchangemodelid = $supplierid;
            $Supplierdebtchange->opensupplierid = $supplierid;
            $Supplierdebtchange->supplierid = $supplierid;
            $Supplierdebtchange->supplierdebtchangetype = 0;
            $Supplierdebtchange->tablename = "supplierControllerOpen.php";
            $Supplierdebtchange->userid = $_SESSION['userid'];
            $Supplierdebtchange->dailyentryid = 0;
            $Supplierdebtchange->del = 0;
            $Supplierdebtchange->currencyId = 1;

            $supplierOpenDebtChangeDAO->insert($Supplierdebtchange);
        }
    }
}

function deleteFinaly() {
    global $supplierOpenDAO;
    global $supplierOpenDebtChangeDAO;


    $id = (int) $_GET["id"];
    $rowDelData = $supplierOpenDAO->load($id);
    try {
        $rowDelData->del = 1;
        $supplierOpenDAO->update($rowDelData);
        reverseEntryWithItsID($rowDelData->dailyentryid);
        delTreeElementById($rowDelData->treeId);
        $note = "success";
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء الحذف ";
    }


    return $note;
}

function saveexchangeorclosing() {
    global $supplierOpenExchangeOrClosingDAO;
    global $supplierOpenDAO;
    global $mySaveRecord;
    global $myAssetsRecord;
    global $ExpensetypeDAO;
    global $ExpenseDAO;
    global $supplierOpenDebtChangeDAO;


    //Transaction
    $mytransactions = new Transaction();
    try {
        $thetype = (int) $_POST['thetype'];
        if ($thetype == 0) {//expense
            $supplieropenid = (int) $_POST['supplieropenidEx'];
            $saveid = (int) $_POST['saveidEx'];
            $val = (float) $_POST['ExVal'];

            $assetorexpense = 0;
            $assetorexpenseid = 0;
            $comment = $_POST['commentEx'];



            #####daily entry
            $dailyEntry->entryComment = 'صرف لمورد - ' . $comment . '';
            //من المورد
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $val;
            $suppOpen = $supplierOpenDAO->load($supplieropenid);
            $dailyEntryDebtor->accountstreeid = $suppOpen->treeId;
            //الى الخزنة
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $val;
            $saveData = $mySaveRecord->load($saveid);
            $dailyEntryCreditor->accountstreeid = $saveData->treeId;
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            $did = $returnedData[1];


            ######
            $supplierOpenExchangeOrClosing->thetype = $thetype;
            $supplierOpenExchangeOrClosing->supplieropenid = $supplieropenid;
            $supplierOpenExchangeOrClosing->saveid = $saveid;
            $supplierOpenExchangeOrClosing->assetorexpense = $assetorexpense;
            $supplierOpenExchangeOrClosing->assetorexpenseid = $assetorexpenseid;
            $supplierOpenExchangeOrClosing->val = $val;
            $supplierOpenExchangeOrClosing->dailyentryid = $did;
            $supplierOpenExchangeOrClosing->note = $comment;
            $supplierOpenExchangeOrClosing->userid = $_SESSION['userid'];
            $supplierOpenExchangeOrClosing->sysdate = date('Y-m-d H:i:s');
            $supplierOpenExchangeOrClosing->del = 0;
            $supplierOpenExchangeOrClosingid = $supplierOpenExchangeOrClosingDAO->insert($supplierOpenExchangeOrClosing);
            #####
            $saveData = $mySaveRecord->load($saveid);
            $before = $saveData->savecurrentvalue;
            $after = $before - $val;
            $saveData->savecurrentvalue = $after;
            $mySaveRecord->update($saveData, $saveData->savedetails);
            insertSavedaily($before, $val, 1, $saveid, 'صرف لموردالشجرة - ' . $comment . '', $supplierOpenExchangeOrClosingid, $after, 'supplierControllerOpen.php?do=exchangeorclosing', date('Y-m-d H:i:s'));
            #####
            $suppOpen = $supplierOpenDAO->load($supplieropenid);
            $suppliercurrentDebt = $suppOpen->value;
            $suppOpen->value += $val;
            $supplierOpenDAO->update($suppOpen);
            if (!empty($supplieropenid)) {
                $Supplierdebtchange->comment = 'صرف لمورد شجرة - ' . $comment . '';
                $Supplierdebtchange->processname = 'صرف لموردالشجرة';
                $Supplierdebtchange->supplierdebtchangeafter = $suppOpen->value;
                $Supplierdebtchange->supplierdebtchangeamount = $val;
                $Supplierdebtchange->supplierdebtchangebefore = $suppliercurrentDebt;
                $Supplierdebtchange->supplierdebtchangedate = date('Y-m-d H:i:s');
                $Supplierdebtchange->supplierdebtchangemodelid = $supplierOpenExchangeOrClosingid;
                $Supplierdebtchange->opensupplierid = $supplieropenid;
                $Supplierdebtchange->supplierid = $supplieropenid;
                $Supplierdebtchange->supplierdebtchangetype = 0;
                $Supplierdebtchange->tablename = "supplierControllerOpen.php?do=exchangeorclosing";
                $Supplierdebtchange->userid = $_SESSION['userid'];
                $Supplierdebtchange->dailyentryid = $did;
                $Supplierdebtchange->del = 0;
                $Supplierdebtchange->currencyId = 1;

                $supplierOpenDebtChangeDAO->insert($Supplierdebtchange);
            }
        } else if ($thetype == 1) {//closing
            $supplieropenid = (int) $_POST['supplieropenidClosing'];
            $saveid = (int) $_POST['saveidclosing'];
            $val = (float) $_POST['closingVal'];
            $assetorexpense = (int) $_POST['assetorexpense'];
            $assetorexpenseid = (int) $_POST['assetorexpenseid'];
            $comment = $_POST['commentClosing'];




            #####daily entry
            if ($assetorexpense == 0) {//asset
                $asset = $myAssetsRecord->load($assetorexpenseid);
                $treeId = $asset->treeId;
                $name = $asset->assetsName;
            } elseif ($assetorexpense == 1) {//expense
                $expensetype = $ExpensetypeDAO->load($assetorexpenseid);
                $treeId = $expensetype->treeId;
                $name = $expensetype->expensestypename;
            }


            $dailyEntry->entryComment = 'تقفيل حساب مورد مقابل ' . $name . ' - ' . $comment . '';
            //من الاصل او المصروف
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $val;
            $dailyEntryDebtor->accountstreeid = $treeId;
            //الى المورد
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $val;
            $suppOpen = $supplierOpenDAO->load($supplieropenid);
            $dailyEntryCreditor->accountstreeid = $suppOpen->treeId;
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            $did = $returnedData[1];


            ######
            $supplierOpenExchangeOrClosing->thetype = $thetype;
            $supplierOpenExchangeOrClosing->supplieropenid = $supplieropenid;
            $supplierOpenExchangeOrClosing->saveid = $saveid;
            $supplierOpenExchangeOrClosing->assetorexpense = $assetorexpense;
            $supplierOpenExchangeOrClosing->assetorexpenseid = $assetorexpenseid;
            $supplierOpenExchangeOrClosing->val = $val;
            $supplierOpenExchangeOrClosing->dailyentryid = $did;
            $supplierOpenExchangeOrClosing->note = $comment;
            $supplierOpenExchangeOrClosing->userid = $_SESSION['userid'];
            $supplierOpenExchangeOrClosing->sysdate = date('Y-m-d H:i:s');
            $supplierOpenExchangeOrClosing->del = 0;
            $supplierOpenExchangeOrClosingid = $supplierOpenExchangeOrClosingDAO->insert($supplierOpenExchangeOrClosing);


            #####
            $suppOpen = $supplierOpenDAO->load($supplieropenid);
            $suppliercurrentDebt = $suppOpen->value;
            $suppOpen->value -= $val;
            $supplierOpenDAO->update($suppOpen);
            if (!empty($supplieropenid)) {
                $Supplierdebtchange->comment = 'تقفيل حساب مورد مقابل ' . $name . ' - ' . $comment . '';
                $Supplierdebtchange->processname = 'تقفيل حساب مورد';
                $Supplierdebtchange->supplierdebtchangeafter = $suppOpen->value;
                $Supplierdebtchange->supplierdebtchangeamount = $val;
                $Supplierdebtchange->supplierdebtchangebefore = $suppliercurrentDebt;
                $Supplierdebtchange->supplierdebtchangedate = date('Y-m-d H:i:s');
                $Supplierdebtchange->supplierdebtchangemodelid = $supplierOpenExchangeOrClosingid;
                $Supplierdebtchange->opensupplierid = $supplieropenid;
                $Supplierdebtchange->supplierid = $supplieropenid;
                $Supplierdebtchange->supplierdebtchangetype = 1;
                $Supplierdebtchange->tablename = "supplierControllerOpen.php?do=exchangeorclosing";
                $Supplierdebtchange->userid = $_SESSION['userid'];
                $Supplierdebtchange->dailyentryid = $did;
                $Supplierdebtchange->del = 0;
                $Supplierdebtchange->currencyId = 1;

                $supplierOpenDebtChangeDAO->insert($Supplierdebtchange);
            }
            #####
            if ($assetorexpense == 0) {
                $asset->assetsValue += $val;
                $myAssetsRecord->update($asset, $asset->assetsDescription);
            } elseif ($assetorexpense == 1) {//expense
                //add expense
                $Expense->saveid = $saveid;
                $Expense->bankid = 0;
                $Expense->bankaccountid = 0;
                $Expense->checknum = '';
                $Expense->expensesname = ' تقفيل لحساب المورد ' . $suppOpen->name . '';
                $Expense->expensesValue = $val;
                $Expense->conditions = 0;
                $Expense->expensestypeid = $expensetype->expensestypeid;
                $Expense->expensesdate = date('Y-m-d');
                $Expense->userid = $_SESSION["userid"];
                $Expense->expensesdetails = $comment;
                $Expense->costcenterid = -1;
                $Expense->productid = 0;

                $Expense->dailyentryid = $did;
                $Expense->expensenumbrt = 0;
                $Expense->expenseprice = 0;
                $Expense->expensetotaln = 0;
                $Expense->expenseshortfalls = 0;
                $Expense->supplier = 0;
                $Expense->clientid = 0;
                $Expense->sellbillid = 0;
                $Expense->realestateid = 0;
                $Expense->realestateunitid = 0;
                $Expense->suppRemainingVal = 0;
                $Expense->taxPer = 0;
                $Expense->taxVal = 0;
                $expenseId = $ExpenseDAO->insert($Expense);
            }

            #####
            $saveData = $mySaveRecord->load($saveid);
            $before = $saveData->savecurrentvalue;
            $after = $before - $val;
            $saveData->savecurrentvalue = $after;
            $mySaveRecord->update($saveData, $saveData->savedetails);
            insertSavedaily($before, $val, 1, $saveid, 'تقفيل حساب مورد مقابل ' . $name . ' - ' . $comment . '', $supplierOpenExchangeOrClosingid, $after, 'supplierControllerOpen.php?do=exchangeorclosing', date('Y-m-d H:i:s'));
        }

        $mytransactions->commit();
    } catch (Exception $exc) {
        $mytransactions->rollback();
    }
}

function deleteexchangeorclosing() {
    global $supplierOpenExchangeOrClosingDAO;
    global $supplierOpenDAO;
    global $mySaveRecord;
    global $myAssetsRecord;
    global $ExpensetypeDAO;
    global $ExpenseDAO;
    global $ExpenseEX;
    global $supplierOpenDebtChangeDAO;


    //Transaction
    $mytransactions = new Transaction();
    try {

        $id = (int) $_GET['id'];
        $row = $supplierOpenExchangeOrClosingDAO->load($id);
        if (isset($row->id)) {
            reverseEntryWithItsID($row->dailyentryid);
            $row->del = 1;
            $supplierOpenExchangeOrClosingDAO->update($row);


            $saveid = $row->saveid;
            $val = $row->val;
            $supplierOpenExchangeOrClosingid = $id;
            $supplieropenid = $row->supplieropenid;
            $did = $row->dailyentryid;
            $assetorexpense = $row->assetorexpense;
            $assetorexpenseid = $row->assetorexpenseid;



            #####
            $saveData = $mySaveRecord->load($saveid);
            $before = $saveData->savecurrentvalue;
            $after = $before + $val;
            $saveData->savecurrentvalue = $after;
            $mySaveRecord->update($saveData, $saveData->savedetails);
            insertSavedaily($before, $val, 0, $saveid, ($row->thetype == 0) ? 'حذف صرف لموردالشجرة' : 'حذف تقفيل حساب مورد ', $supplierOpenExchangeOrClosingid, $after, 'supplierControllerOpen.php?do=exchangeorclosing', date('Y-m-d H:i:s'));
            if ($row->thetype == 0) {//صرف
                #####
                $suppOpen = $supplierOpenDAO->load($supplieropenid);
                $suppliercurrentDebt = $suppOpen->value;
                $suppOpen->value -= $val;
                $supplierOpenDAO->update($suppOpen);
                if (!empty($supplieropenid)) {
                    $Supplierdebtchange->comment = 'حذف صرف لمورد شجرة';
                    $Supplierdebtchange->processname = 'حذف صرف لموردالشجرة';
                    $Supplierdebtchange->supplierdebtchangeafter = $suppOpen->value;
                    $Supplierdebtchange->supplierdebtchangeamount = $val;
                    $Supplierdebtchange->supplierdebtchangebefore = $suppliercurrentDebt;
                    $Supplierdebtchange->supplierdebtchangedate = date('Y-m-d H:i:s');
                    $Supplierdebtchange->supplierdebtchangemodelid = $supplierOpenExchangeOrClosingid;
                    $Supplierdebtchange->opensupplierid = $supplieropenid;
                    $Supplierdebtchange->supplierid = $supplieropenid;
                    $Supplierdebtchange->supplierdebtchangetype = 1;
                    $Supplierdebtchange->tablename = "supplierControllerOpen.php?do=exchangeorclosing";
                    $Supplierdebtchange->userid = $_SESSION['userid'];
                    $Supplierdebtchange->dailyentryid = $did;
                    $Supplierdebtchange->del = 0;
                    $Supplierdebtchange->currencyId = 1;

                    $supplierOpenDebtChangeDAO->insert($Supplierdebtchange);
                }
            } elseif ($row->thetype == 0) {//تقفيل
                #####
                $suppOpen = $supplierOpenDAO->load($supplieropenid);
                $suppliercurrentDebt = $suppOpen->value;
                $suppOpen->value += $val;
                $supplierOpenDAO->update($suppOpen);
                if (!empty($supplieropenid)) {
                    $Supplierdebtchange->comment = 'حذف تقفيل حساب مورد  ';
                    $Supplierdebtchange->processname = 'حذف تقفيل حساب مورد';
                    $Supplierdebtchange->supplierdebtchangeafter = $suppOpen->value;
                    $Supplierdebtchange->supplierdebtchangeamount = $val;
                    $Supplierdebtchange->supplierdebtchangebefore = $suppliercurrentDebt;
                    $Supplierdebtchange->supplierdebtchangedate = date('Y-m-d H:i:s');
                    $Supplierdebtchange->supplierdebtchangemodelid = $supplierOpenExchangeOrClosingid;
                    $Supplierdebtchange->opensupplierid = $supplieropenid;
                    $Supplierdebtchange->supplierid = $supplieropenid;
                    $Supplierdebtchange->supplierdebtchangetype = 0;
                    $Supplierdebtchange->tablename = "supplierControllerOpen.php?do=exchangeorclosing";
                    $Supplierdebtchange->userid = $_SESSION['userid'];
                    $Supplierdebtchange->dailyentryid = $did;
                    $Supplierdebtchange->del = 0;
                    $Supplierdebtchange->currencyId = 1;

                    $supplierOpenDebtChangeDAO->insert($Supplierdebtchange);
                }


                #####daily entry
                if ($assetorexpense == 0) {//asset
                    $asset = $myAssetsRecord->load($assetorexpenseid);
                    $asset->assetsValue -= $val;
                    $myAssetsRecord->update($asset, $asset->assetsDescription);
                } elseif ($assetorexpense == 1) {//expense
                    $expenseAsArr = $ExpenseEX->queryByQueryString(" and dailyentryid=$did ");
                    $ExpenseDAO->delete($expenseAsArr[0]->expensesid);
                }
            }
        }

        $mytransactions->commit();
    } catch (Exception $exc) {
        $mytransactions->rollback();
    }
}

function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename, $theDate) {

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

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = $theDate;
    $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;
    $mySavedaily->clientid = 0;
    $mySavedailyRecord->insert($mySavedaily);
}

?>