<?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
include("../public/include_dao.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');
//Assetssale
require_once('../models/dao/AssetssaleDAO.class.php');
require_once('../models/dto/Assetssale.class.php');
require_once('../models/mysql/AssetssaleMySqlDAO.class.php');
require_once('../models/mysql/ext/AssetssaleMySqlExtDAO.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');
//Checkcontroller
require_once('../models/dao/CheckcontrollerDAO.class.php');
require_once('../models/dto/Checkcontroller.class.php');
require_once('../models/mysql/CheckcontrollerMySqlDAO.class.php');
require_once('../models/mysql/ext/CheckcontrollerMySqlExtDAO.class.php');

require_once('../models/dao/BankaccountDAO.class.php');
require_once('../models/dto/Bankaccount.class.php');
require_once('../models/mysql/BankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/BankaccountMySqlExtDAO.class.php');

require_once('../models/dao/AccountmovementDAO.class.php');
require_once('../models/dto/Accountmovement.class.php');
require_once('../models/mysql/AccountmovementMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountmovementMySqlExtDAO.class.php');

require_once('../models/dao/BankDAO.class.php');
require_once('../models/dto/Bank.class.php');
require_once('../models/mysql/BankMySqlDAO.class.php');
require_once('../models/mysql/ext/BankMySqlExtDAO.class.php');

require_once('../models/dao/CheckwithdrawalDAO.class.php');
require_once('../models/dto/Checkwithdrawal.class.php');
require_once('../models/mysql/CheckwithdrawalMySqlDAO.class.php');
require_once('../models/mysql/ext/CheckwithdrawalMySqlExtDAO.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');

//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.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 :- assetsCTRL

  OPERTATION in Controller

  1-display add form
  2- add in Assets tble
  3-display sucess or error
  4-display show form
  5-delete from Assets tbl
  6-edit in Assets data

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

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

//here goes the instances and general variables
$myAssets = new Asset();
$myAssetsRecord = new AssetsMySqlDAO();
$myAssetsEx = new AssetsMySqlExtDAO();

$myAssetssale = new Assetssale();
$myAssetssaleDAO = new AssetssaleMySqlDAO();
$myAssetssaleEx = new AssetssaleMySqlExtDAO();

$Assetscat = new Assetscat();
$AssetscatDAO = new AssetscatMySqlDAO();
$AssetscatEX = new AssetscatMySqlExtDAO();

//creating objects
$checkWithdrawalDAO = new CheckwithdrawalMySqlDAO;
$checkWithdrawalExtDAO = new CheckwithdrawalMySqlExtDAO;
$checkWithdrawal = new Checkwithdrawal;

$account = new Bankaccount();
$accountDAO = new BankaccountMySqlDAO;
$accountExtDAO = new BankaccountMySqlExtDAO;

$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;

$bankDAO = new BankMySqlDAO;
$bank = new Bank;
$bankExtDAO = new BankMySqlExtDAO;
//mySave
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//Savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Checkcontroller
$Checkcontroller = new Checkcontroller();
$CheckcontrollerDAO = new CheckcontrollerMySqlDAO();
$CheckcontrollerEX = new CheckcontrollerMySqlExtDAO();
//Accountmovement
$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;
//Breadcrumb
$breadcrumbObject = new Breadcrumb();

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

$Asset = new Asset();
$AssetDAO = new AssetsMySqlDAO();
$AssetEX = new AssetsMySqlExtDAO();

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

//Bankaccount
$myBankaccount = new Bankaccount();
$myBankaccountRecord = new BankaccountMySqlDAO();
$myBankaccountEx = new BankaccountMySqlExtDAO();



//Dailyentry
$dailyEntry2 = new Dailyentry();
$dailyEntryDAO2 = new DailyentryMySqlDAO();
$dailyEntryEX2 = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor2 = new Dailyentrycreditor();
$dailyEntryCreditorDAO2 = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX2 = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor2 = new Dailyentrydebtor();
$dailyEntryDebtorDAO2 = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX2 = new DailyentrydebtorMySqlExtDAO();

//Client
$clientDAO = new ClientMySqlDAO();
$client = new Client();
$clientEX = new ClientMySqlExtDAO();

//Store
$myStoreRecord = new StoreMySqlDAO();

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

//supplier
$supplier = new Supplier();
$supplierDao = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();



//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");
    $bank = $bankExtDAO->queryAllExt();
    //print_r($bank);
    $smarty->assign("bank", $bank);

    $savedata = $mySaveRecord->queryAll();
    $smarty->assign("savedata", $savedata);

    $allSuppliers = $supplierDao->queryAll();
    $smarty->assign("allSuppliers", $allSuppliers);

    $savebefor = getSaveValueBefore();

    $smarty->assign("savebefor", $savebefor);

    $allctadata = showallcat();
    $smarty->assign("allctadata", $allctadata);

    $type = $_GET["type"];
    $smarty->assign("type", $type);



    if ($type != 0) {  //add new asset
        $smarty->display("assetsview/add.html");
    } else {
        // add old asset
        $smarty->display("assetsview/addold.html");
    }
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    // here the function that do the action
    $assetsearchData = loadAsset();
    $smarty->assign('assetsearchData', $assetsearchData);

    $clientdata = $clientDAO->queryAll();
    $smarty->assign("clientdata", $clientdata);

    $savedata = $mySaveRecord->queryAll();
    $smarty->assign("savedata", $savedata);

    $assetId = $_REQUEST['assetId'];
    if (isset($assetId) && $assetId != "-1") {
        $messageData = $myAssetsRecord->load($assetId);
        $message = "إسم الأصل: " . $messageData->assetsName;
        $smarty->assign("message", $message);

        showByassetName();
    } else {
        showAll();
    }

    //here the smarty templates
    $smarty->display("assetsview/show.html");
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    $type = $_REQUEST['type'];
    $assetId = $_REQUEST['assetId'];
    try {
        $note = delete($type, $assetId);
        //  print_r($note);
        if ($note !== "sucess") {
            $url = "assetTypeController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = $note;
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    include_once("../public/authentication.php");


    $assetId = $_GET['assetId'];
    $loadData = edit($assetId);
    $smarty->assign("loadData", $loadData);

    $savedata = $mySaveRecord->queryAll();
    $smarty->assign("savedata", $savedata);

    $allSuppliers = $supplierDao->queryAll();
    $smarty->assign("allSuppliers", $allSuppliers);

    $allctadata = showallcat();
    $smarty->assign("allctadata", $allctadata);
    $type = $_GET["type"];

    if ($type == 2) {
        $checkdata = getcheckdata($assetId);
        $smarty->assign("showData", $checkdata);
    }

    //bank
    $bank = $bankExtDAO->queryAllExt();
    $smarty->assign("bank", $bank);

    $smarty->assign("type", $type);

    $smarty->display("assetsview/edit.html");
} elseif ($do == "assetsaleadd") {
    assetsaleadd();
} elseif ($do == "assetsalecheck") {
    assetsalecheck();
} elseif ($_GET['do'] == "executeOperation") {
    try {
        execute();
        showAll();
        $smarty->display("assetsview/show.html");
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");


    $id = $_GET["id"];
    $loadData = edit($id);
    $smarty->assign("loadData", $loadData);

    $allctadata = showallcat();
    $smarty->assign("allctadata", $allctadata);
    $type = $loadData->type;

    if ($type == 2) {
        $checkdata = getcheckdata($id);
        $smarty->assign("showData", $checkdata);
    }

    //bank
    $bank = $bankExtDAO->queryAllExt();
    $smarty->assign("bank", $bank);

    $smarty->assign("type", $type);

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

    $smarty->display("assetsview/editprint.html");
} elseif ($do == "update") {
    include_once("../public/authentication.php");
    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} 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("customValidation", 1);
$smarty->assign("customAssets", 1);
$smarty->display("footer.html");

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

// load Assets data
function loadAsset()
{
    //to use the variable out side the funcion
    global $myAssetsRecord;

    //select all data data in Assets tbl
    $assetsearchData = $myAssetsRecord->queryAll();

    return $assetsearchData;
}

function assetsaleadd()
{

    //to use the variable out side the funcion
    global $myAssetssale;
    global $myAssetssaleDAO;
    global $myAssetssaleEx;

    //save
    global $mySave;
    global $mySaveRecord;

    $assetssaleclient = $_POST['assetssaleclient'];
    $assetssalesave = $_POST['assetssalesave'];
    $assetssaleval = $_POST['assetssaleval'];
    $assetssalecomment = $_POST['assetssalecomment'];
    $assetssaledate = $_POST['assetssaledate'];
    $assetsid = $_POST['assetsidm'];

    //insert data in Assets tbl
    $myAssetssale->assetssaleclient = $assetssaleclient;
    $myAssetssale->assetssalesave = $assetssalesave;
    $myAssetssale->assetssalecomment = $assetssalecomment;
    $myAssetssale->assetssaleval = $assetssaleval;
    $myAssetssale->assetssaledate = $assetssaledate;
    $myAssetssale->assetsid = $assetsid;
    $myAssetssale->assetssaledateadd = date("Y-m-d");
    $myAssetssaleres = $myAssetssaleDAO->insert($myAssetssale);




    R::exec("UPDATE `save` SET `savecurrentvalue`= savecurrentvalue + $assetssaleval WHERE saveid = $assetssalesave");
    R::exec("UPDATE `assets` SET `assetsValue`= 0 WHERE assetId = $assetsid");

    $savebefor = getSaveValueBefore($saveid);
    insertSavedaily(
        $savebefor,
        $assetssaleval,
        0,
        $assetssalesave,
        'بيع اصل',
        $assetsid,
        ($savebefor - $assetssaleval),
        'assetController.php'
    );
}

// add in Assets tbl
function add()
{

    //to use the variable out side the funcion
    global $myAssets;
    global $myAssetsRecord;

    global $accountsTreeDAO;
    global $accountsTree;

    global $AssetscatEX;
    global $AssetscatDAO;
    global $Assetscat;

    //bankaccount
    global $myBankaccount;
    global $myBankaccountRecord;

    //save
    global $mySave;
    global $mySaveRecord;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    //Dailyentry
    global $dailyEntry2;
    global $dailyEntryDAO2;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor2;
    global $dailyEntryCreditorDAO2;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor2;
    global $dailyEntryDebtorDAO2;
    //supplier
    global $supplier;
    global $supplierDao;
    global $supplierExt;
    //supplier debt change
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $supplierDeptChangeExt;

    $assetName = $_POST['assetname'];
    $assetPrice = $_POST['assetprice'];
    $assetsDepreciation = $_POST['assetsDepreciation'];
    $assetDescription = $_POST['assetdescription'];
    $type = $_POST["type"];
    if (!isset($type) || empty($type)) {
        $type = 0;
    }
    $depreciation = $_POST["depreciation"];
    $Hourlyrate = $_POST["Hourlyrate"];
    $assetscatid = $_POST["assetscatid"];
    $manufacture = $_POST["manufacture"];
    $paytype = $_POST["paytype"];
    $accountid = $_POST["accountid"];
    $checkAddPage = $_POST["Add"];
    $saveid = $_POST["saveid"];

    $paytype = $_POST["paytype"];
    if ($paytype == "0") {
        //pay from save
        $paytype = 1;
    } elseif ($paytype == "1") {
        //pay with check
        $paytype = 2;
    } elseif ($paytype == "2") {
        //pay with supplier
        $paytype = 3;
    }
    if ($saveid < 1) {
        $saveid = $_SESSION['saveid'];
    }

    if ($paytype == "3") {
        //pay with supplier
        $saveid = $_POST['supplierid'];
    }

    //insert data in Assets tbl
    $myAssets->assetsDepreciation = $assetsDepreciation;
    $myAssets->manufacture = $manufacture;
    $myAssets->assetsName = $assetName;
    $myAssets->assetsValue = $assetPrice;
    $myAssets->assetsDate = date("Y-m-d");
    $myAssets->conditions = 0;
    $myAssets->userid = $_SESSION['userid'];
    $myAssets->type = $paytype; //$type;se
    $myAssets->depreciation = $depreciation;
    $myAssets->Hourlyrate = $Hourlyrate;
    $myAssets->assetscatid = $assetscatid;
    $myAssets->dailyentryid = 0;
    $myAssets->saveid = $saveid;
    //print_r('Hourlyrate=='.$_POST['Hourlyrate'].'</br>');

    $modelid = $myAssetsRecord->insert($myAssets, $assetDescription);

    if ($saveid < 1) {
        $saveid = $_SESSION['saveid'];
    }

    if ($type != 0) {

        $paytype = $_POST["paytype"];

        //pay asset from  save
        if ($paytype == "0") {
            $savebefor = getSaveValueBefore($saveid);
            if ($savebefor >= $assetPrice) {

                //  print_r("in save");

                getSaveValueAndMins($assetPrice, $saveid);
                updateSave($saveid, ($savebefor - $assetPrice));
                insertSavedaily(
                    $savebefor,
                    $assetPrice,
                    1,
                    $saveid,
                    'وصل شراء اصل',
                    $modelid,
                    ($savebefor - $assetPrice),
                    'assetController.php'
                );
            }
        }

        //pay asset by check
        elseif ($paytype == "1") {

            //print_r("inbank");

            addbanck($modelid);
        }
        //pay asset by supplier
        elseif ($paytype == "2") {
            $supplierId = $_POST['supplierid'];
            $supplier = $supplierDao->load($supplierId);
            $debtbefore = $supplier->suppliercurrentDebt;
            if ($debtbefore >= $assetPrice) {
                createSupplierInUseSP(2);
                //Transaction
                // $mytransactions = new Transaction();
                try {
                    $supplierdata = getSupplierDataFromSupplierInUseSP($supplierId);
                    $debtBefore = $supplierdata->suppliercurrentDebt;
                    $debtAfter = $debtBefore + $assetPrice;
                    $supplierdebtchangemodelid = $modelid;

                    //insert into supplierdeptchange tbl
                    $supplierDeptChange->comment = $assetsDepreciation;
                    $supplierDeptChange->processname = "شراء أصل جدبد ";
                    $supplierDeptChange->supplierdebtchangeafter = $debtAfter;
                    $supplierDeptChange->supplierdebtchangeamount = $assetPrice;
                    $supplierDeptChange->supplierdebtchangebefore = $debtBefore;
                    $supplierDeptChange->supplierdebtchangedate = date("Y-m-d H:i:s");
                    $supplierDeptChange->supplierdebtchangemodelid = $supplierdebtchangemodelid;
                    $supplierDeptChange->supplierdebtchangetype = 0;
                    $supplierDeptChange->tablename = "assetController.php?type=1";
                    $supplierDeptChange->userid = $_SESSION['userid'];
                    $supplierDeptChange->supplierid = $supplierId;
                    $supplierDeptChange->dailyentryid = 0;

                    //Insert
                    $supplierDeptChangeId = $supplierDeptChangeDAO->insert($supplierDeptChange);

                    if (isset($supplierDeptChangeId)) {
                        $suppData = $supplierDao->load($supplierId);
                        //update current dept in supplier tbl
                        $supplier->suppliercurrentDebt = $debtAfter;
                        $supplier->suppliercurrentDebtInCurrency = $debtAfter;
                        $supplier->userid = $_SESSION['userid'];
                        $supplier->supplierdate = date("Y-m-d H:i:s");
                        $supplier->supplierid = $supplierId;

                        $supplierExt->updatedept($supplier);
                        markSupplierAsNOTInUse($supplierId);
                    }
                } catch (Exception $ex) {
                    // $mytransactions->rollback();
                    markSupplierAsNOTInUse($_POST["supplierid"]);
                }
            }
        }
    }

    $loadAsset = $AssetscatDAO->load($assetscatid);

    $treeId = $loadAsset->treeId;
    if ($treeId < 1) {
        $assetscatTreedata = $accountsTreeDAO->queryByCustomName($loadAsset->cattitel);
        $treeId = $assetscatTreedata[0]->id;
    }



    //////////////// End Al-Asl
    /// start load asset id
    //
    /// end load asset id
    if ($checkAddPage == 1) {
        if ($paytype == 0) {

            $dailyEntry->entryComment = 'اضافة اصل جديد (' . $assetName . ')';

            //////////////// start Al-Asl

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $assetPrice;

            $aslId = addTreeElement($assetName, $treeId, 3, 0, 1, '', 0, 0);
            $dailyEntryDebtor->accountstreeid = $aslId;

            //////////////// End Al-Asl
            //
            //////////////// start save data

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $assetPrice;
            //save session
            $saveid = $saveid;
            $dataSave = $mySaveRecord->load($saveid);

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

            //end  save data
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $modelid, "assetController.php?do=editprint&id=$modelid");
            $did = $returnedData[1];

            $myAssets = $myAssetsRecord->load($modelid);
            $myAssets->dailyentryid = $did;
            $myAssets->treeId = $aslId;

            $myAssetsRecord->update($myAssets, $assetDescription);
        } elseif ($paytype == 1) {

            $dailyEntry->entryComment = 'اضافة اصل جديد (' . $assetName . ')';

            //////////////// start Al-Asl

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $assetPrice;

            $aslId = addTreeElement($assetName, $treeId, 3, 0, 1, '', 0, 0);
            $dailyEntryDebtor->accountstreeid = $aslId;

            //////////////// End Al-Asl
            //////////////// start bankAccount data

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $assetPrice;
            //save session

            $dataBankAccount = $myBankaccountRecord->load($accountid);

            $idTreeBankAccount = $dataBankAccount->treeId;
            $dailyEntryCreditor->accountstreeid = $idTreeBankAccount;

            //end  save data
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $modelid, "assetController.php?do=editprint&id=$modelid");
            $did = $returnedData[1];

            $myAssets = $myAssetsRecord->load($modelid);


            $myAssets->dailyentryid = $did;
            $myAssets->treeId = $aslId;

            $myAssetsRecord->update($myAssets, $assetDescription);
        } elseif ($paytype == 2) {

            $dailyEntry->entryComment = 'اضافة اصل جديد (' . $assetName . ')';

            //////////////// start Al-Asl

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $assetPrice;

            $aslId = addTreeElement($assetName, $treeId, 3, 0, 1, '', 0, 0);
            $dailyEntryDebtor->accountstreeid = $aslId;

            //////////////// End Al-Asl
            //////////////// start bankAccount data

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $assetPrice;

            //supplier data
            $supplier = $supplierDao->load($supplierId);
            $dailyEntryCreditor->accountstreeid = $supplier->treeId;
            //end  supplierdata

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

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $modelid, "assetController.php?do=editprint&id=$modelid");
            $did = $returnedData[1];

            $myAssets = $myAssetsRecord->load($modelid);


            $myAssets->dailyentryid = $did;
            $myAssets->treeId = $aslId;

            $myAssetsRecord->update($myAssets, $assetDescription);
        }
    } else {

        $dailyEntry->entryComment = 'اضافة اصل قديم (' . $assetName . ')';

        //////////////// start Al-Asl

        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $assetPrice;

        $aslId = addTreeElement($assetName, $treeId, 3, 0, 1, '', 0, 0);
        $dailyEntryDebtor->accountstreeid = $aslId;

        //////////////// End Al-Asl
        ///////////// start Ras L maaal

        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $assetPrice;
        $dailyEntryCreditor->accountstreeid = 121; //راس المال
        ///////////// end Ras L maaaal
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

        $returnedData_1 = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $modelid, "assetController.php?do=editprint&id=$modelid");

        $did_1 = $returnedData_1[1];

        ///////من حساب راس المال الي حساب مخصص اهلاك

        $dailyEntry2->entryComment = 'اهلاك اصل قديم ' . $assetName;

        //////////////// start Rasl L maal

        $dailyEntryDebtorArray2 = array();
        $dailyEntryDebtor2->value = $depreciation;
        $dailyEntryDebtor2->accountstreeid = 121; //راس المال
        //////////////// end Rasl L maal
        //////////////// start Mogam3 L Hlak

        $dailyEntryCreditorArray2 = array();
        $dailyEntryCreditor2->value = $depreciation;
        $dailyEntryCreditor2->accountstreeid = 8; //مخصصات الاهلاك
        //////////////// end  Mogam3 L Hlak

        array_push($dailyEntryDebtorArray2, $dailyEntryDebtor2);
        array_push($dailyEntryCreditorArray2, $dailyEntryCreditor2);

        $returnedData = insertEntery($dailyEntry2, $dailyEntryDebtorArray2, $dailyEntryCreditorArray2, 0, $modelid, "assetController.php?do=editprint&id=$modelid");

        $did_2 = $returnedData[1];

        $myAssets = $myAssetsRecord->load($modelid);


        $myAssets->dailyentryid = $did_1 . ',' . $did_2;
        $myAssets->treeId = $aslId;
        //print_r($myAssets->dailyentryid);

        $myAssetsRecord->update($myAssets, $assetDescription);
    }
}

function addbanck($modelid)
{



    global $checkWithdrawal;
    global $checkWithdrawalDAO;
    global $Checkcontroller;
    global $CheckcontrollerDAO;
    global $accountMove;
    global $accountMoveDAO;
    global $accountDAO;
    global $accountExtDAO;
    global $account;

    $accountid = $_POST["accountid"];
    $accountnumber = $_POST["accountnumberDis"];
    $accountbeginingbalance = $_POST["accountbeginingbalance"];
    $checkwithdrawalamount = $_POST["txtAmount"];
    $checkwithdrawalnote = $_POST["textNote"];
    $checkwithdrawalnumber = $_POST["txtcheckNum"];
    $checkwithdrawaluser = $_POST["txtUser"];
    $checkwithdrawaldate = date("Y-m-d");

    $ddlBank = $_POST["ddlBank"];

    $checkWithdrawal->bankaccountid = $accountid;
    $checkWithdrawal->supplierid = 0;
    $checkWithdrawal->accountnumber = $accountnumber;
    $checkWithdrawal->accountbeforevalue = $accountbeginingbalance;
    $checkWithdrawal->checkwithdrawalamount = $checkwithdrawalamount;
    $checkWithdrawal->checkwithdrawaldate = $checkwithdrawaldate;
    $checkWithdrawal->conditions = 0;

    //$checkWithdrawal->checkwithdrawalnote=$checkwithdrawalnote;
    $checkWithdrawal->checkwithdrawalnumber = $checkwithdrawalnumber;
    $checkWithdrawal->checkwithdrawaluser = $checkwithdrawaluser;
    $checkWithdrawal->userid = $_SESSION['userid'];
    $checkWithdrawal->dailyentryid = 0;


    $checkWithdrawalId = $checkWithdrawalDAO->insert($checkWithdrawal, $checkwithdrawalnote);


    $Checkcontroller->checkid = $checkWithdrawalId;
    $Checkcontroller->controllerid = $modelid;
    $Checkcontroller->type = "شيك شراء اصل";
    $CheckcontrollerDAO->insert($Checkcontroller);


    if ($checkWithdrawalId != null) {


        $accoundatat = $accountDAO->load($accountid);
        $accountBefore = $accoundatat->accountbeginingbalance;

        if ($accountBefore >= $checkwithdrawalamount) {
            $account->accountbeginingbalance = $accountBefore - $checkwithdrawalamount;
        }


        $account->accountdate = $checkwithdrawaldate;

        $account->accountid = $accountid;

        //update
        $accountExtDAO->updateacount($account);


        //-------------------
        //Insert in accountmovement table
        $accountMove->accountmovementbefore = $accountBefore;
        $accountMove->accountid = $accountid;
        $accountMove->bankid = $ddlBank;
        $accountMove->accountmovementamount = $checkwithdrawalamount;
        $accountMove->accountmovementafter = $accountBefore - $checkwithdrawalamount;
        $accountMove->accountmovementtype = 1;
        $accountMove->processname = "شراء اصل";
        $accountMove->tablename = "assetController.php";
        $accountMove->accountmovementmodelid = $modelid;
        $accountMove->accountmovementdate = $checkwithdrawaldate;
        $accountMove->userid = $_SESSION['userid'];;

        //Insert
        $accountMoveDAO->insert($accountMove);
    }
}

// show the form
function showByassetName()
{
    //to use the variable out side the funcion
    global $myAssetsEx;
    global $myAssetsRecord;

    global $smarty;



    //select all data from Assets tbl by assetid


    $allctadata = showallcat();
    $smarty->assign("allctadata", $allctadata);

    $allassetdata = $myAssetsRecord->queryAll();
    $smarty->assign("allassetdata", $allassetdata);
    // required connect
    SmartyPaginate::connect();
    // set items per page
    SmartyPaginate::setLimit(25000);

    $assetId = $_REQUEST['assetId'];

    // get the all colums number
    $allColums = $myAssetsRecord->load($assetId);
    SmartyPaginate::setTotal(count($allColums));

    if (SmartyPaginate::getCurrentIndex() != -1) {
        //get the selected data with limitation
        $assetData = $myAssetsEx->loadimted(SmartyPaginate::getCurrentIndex(), SmartyPaginate::getLimit(), $assetId);
    }
    if (empty($_GET['page'])) {
        //get the selected data with limitation
        $assetData = $myAssetsEx->loadimted(0, SmartyPaginate::getLimit(), $assetId);
        SmartyPaginate::setCurrentItem($_SESSION['SmartyPaginate'][$page]['current_item']);
    }



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



    //$smarty->assign('sumValue',$sumValue);
    // assign {$paginate} var
    SmartyPaginate::assign($smarty);
    SmartyPaginate::setUrlVar("page");

    //text that show in navgation
    SmartyPaginate::setNextText('التالى');
    SmartyPaginate::setPrevText('السابق');
    //add any varaible in url
    SmartyPaginate::setUrl('assetController.php?do=show&assetid=' . $assetId . '&');
}

// show the form
function showAll()
{
    //to use the variable out side the funcion
    global $myAssetsEx;
    global $myAssetsRecord;

    global $smarty;

    //select all data from Assets tbl


    $allctadata = showallcat();
    $smarty->assign("allctadata", $allctadata);
    // required connect
    SmartyPaginate::connect();
    // set items per page
    SmartyPaginate::setLimit(25000);

    // get the all colums number
    $allColums = $myAssetsRecord->queryAll();
    SmartyPaginate::setTotal(count($allColums));
    $smarty->assign("allassetdata", $allColums);

    if (SmartyPaginate::getCurrentIndex() != -1) {
        //get the selected data with limitation
        $assetData = $myAssetsEx->queryAllWithLimit(SmartyPaginate::getCurrentIndex(), SmartyPaginate::getLimit());
    }
    if (empty($_GET['page'])) {
        //get the selected data with limitation
        $assetData = $myAssetsEx->queryAllWithLimit(0, SmartyPaginate::getLimit());
        SmartyPaginate::setCurrentItem($_SESSION['SmartyPaginate'][$page]['current_item']);
    }


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

    // assign {$paginate} var
    SmartyPaginate::assign($smarty);
    SmartyPaginate::setUrlVar("page");

    //text that show in navgation
    SmartyPaginate::setNextText('التالى');
    SmartyPaginate::setPrevText('السابق');
    //add any varaible in url
    SmartyPaginate::setUrl('assetController.php?do=show&');
}

//update tempdelete in Assets tbl

function delete($type, $assetId)
{
    //to use the variable out side the funcion
    global $myAssets;
    global $myAssetsEx;
    global $myAssetsRecord;

    //get variable
    $type = $type; //$_GET['type'];
    $assetId = $assetId; //$_GET['assetId'];
    $dailyEntryId = $_GET['action'];
    $assetdata = $myAssetsRecord->load($assetId);
    $myAssets->assetId = $assetId;
    $myAssets->assetsDate = date("Y-m-d");
    $myAssets->conditions = 1;
    $myAssets->userid = $_SESSION['userid'];
    $saveId = $assetdata->saveid;

    //print_r($myAssets);
    $myAssetsEx->updateDele($myAssets);

    //pay from save
    if ($type == 1) {
        $savebefor = getSaveValueBefore($saveId);
        getSaveValueAndPlus($assetdata->assetsValue, $saveId);
        updateSave($saveId, ($savebefor + ($assetdata->assetsValue)));
        $Savedailyid = insertSavedaily(
            $savebefor,
            $assetdata->assetsValue,
            0,
            $saveId,
            'الغاء وصل شراء اصل',
            $assetId,
            ($savebefor + ($assetdata->assetsValue)),
            'assetController.php'
        );
        //print_r($Savedailyid);
        if ($Savedailyid > 0) {
            reverseEntryWithItsID($dailyEntryId);

            $note = "sucess";
        } else {
            $note = "لم تتم العمليه بنجاح ";
        }


        return $note;
    }

    //by with check
    else if ($type == 2) { //?????
        $note = updateckeck($assetId);

        return $note;
    } else if ($type == 0) { //old asset
        $dailyEntryIdSplit = split(',', $dailyEntryId);
        $dily_1 = $dailyEntryIdSplit[0];

        reverseEntryWithItsID($dily_1);
        $dily_2 = $dailyEntryIdSplit[1];
        reverseEntryWithItsID($dily_2);
        $note = "sucess";
        return $note;
    } else if ($type == 1) { //new asset
        reverseEntryWithItsID($dailyEntryId);
        $note = "sucess";
        return $note;
    }
}

// edit in table
function edit($id)
{
    //to use the variable out side the funcion
    global $myAssetsRecord;

    global $checkWithdrawal;
    global $checkWithdrawalDAO;
    //get variable
    $assetId = $id; //$_GET['assetId'];
    $type = $_GET["type"];
    //load data
    $loadData = $myAssetsRecord->load($assetId);





    return $loadData;
}

function getcheckdata($assetId)
{
    //to use the variable out side the funcion

    global $checkWithdrawal;
    global $checkWithdrawalDAO;
    global $checkWithdrawalExtDAO;

    global $Checkcontroller;
    global $CheckcontrollerDAO;

    //get variable
    //$assetId=$_GET['assetId'];
    $type = $_GET["type"];
    //load check id

    $loadData = $CheckcontrollerDAO->queryByControllerid($assetId);

    //print_r($loadData);
    $checkid = $loadData->checkid;

    $checkdata = $checkWithdrawalExtDAO->queryByIdExt($checkid);



    return $checkdata;
}

// update table
function update()
{
    //to use the variable out side the funcion
    global $myAssets;
    global $myAssetsRecord;

    global $checkWithdrawal;
    global $checkWithdrawalDAO;
    global $checkWithdrawalExtDAO;

    global $accountsTreeDAO;
    global $accountsTree;

    global $AssetscatEX;
    global $AssetscatDAO;
    global $Assetscat;
    //Dailyentry
    global $dailyEntry2;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor2;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor2;

    $assetName = $_POST['assetname'];
    $assetPrice = $_POST['assetprice'];
    $assetsDepreciation = $_POST['assetsDepreciation'];
    $assetsDescription = $_POST['assetsDescription'];
    $depreciation = $_POST["depreciation"];
    $assetscatid = $_POST["assetscatid"];
    $today = $_POST['today'];
    $assetId = $_POST['assetId'];
    $type = $_POST['type'];
    $manufacture = $_POST["manufacture"];
    $Hourlyrate = $_POST["Hourlyrate"];
    $dailyentryid = $_POST["dailyentryid"];


    //  print_r($assetscatid . 'aaaaaaaaaaaaaaaaaaaaaaa');
    //update data in Assets tbl
    $myAssets->assetsDepreciation = $assetsDepreciation;
    $myAssets->manufacture = $manufacture;
    $myAssets->assetsName = $assetName;
    $myAssets->assetsValue = $assetPrice;
    $myAssets->assetsDate = date("Y-m-d");
    $myAssets->conditions = 0;
    $myAssets->userid = $_SESSION['userid'];
    $myAssets->type = $type;
    $myAssets->depreciation = $depreciation;
    $myAssets->assetscatid = $assetscatid;
    $myAssets->Hourlyrate = $Hourlyrate;
    $myAssets->dailyentryid = $dailyentryid;
    $myAssets->assetsDescription = $assetsDescription;

    print_r($assetsDescription);
    print_r($myAssets->assetsDescription);

    $myAssets->assetId = $assetId;
    //print_r($myAssets);
    //reverseEntryWithItsID($dailyentryid);



    if ($type == 0) {

        //// تعديل الاصل

        $dailyentryid = split(',', $dailyentryid);



        $oldData = $myAssetsRecord->load($assetId);

        $treeId = $oldData->treeId;
        $treeData = $accountsTreeDAO->load($treeId);

        $loadAsset = $AssetscatDAO->load($assetscatid);

        $treeParent = $loadAsset->treeId;

        // print_r('<br>' . $treeParent . 'aaaaaaaaaaaaaaaaaaaaaaa');

        $accountsTree->customName = $assetName;
        $accountsTree->del = $treeData->del;
        $accountsTree->id = $treeId;
        $accountsTree->itemfrom = $treeData->itemfrom;
        $accountsTree->itemtype = $treeData->itemtype;
        $accountsTree->itemtype2 = $treeData->itemtype2;
        $accountsTree->layingOrder = $treeData->layingOrder;
        $accountsTree->sysdate = $treeData->sysdate;
        $accountsTree->name = $assetName;
        $accountsTree->notes = $treeData->notes;
        $accountsTree->parent = $treeParent;
        $accountsTree->theOrder = $treeData->theOrder;
        $accountsTree->theValue = $assetPrice;
        $accountsTree->userid = $treeData->userid;


        editTreeElement($accountsTree);

        //// تعديل مجمع الاهلاك
        $x1 = reverseEntryWithItsID($dailyentryid[1]);


        ///////من حساب راس المال الي حساب مخصص اهلاك

        $dailyEntry2->entryComment = 'تعديل اهلاك اصل قديم  (' . $assetName . ')';

        //////////////// start Rasl L maal

        $dailyEntryDebtorArray2 = array();
        $dailyEntryDebtor2->value = $depreciation;
        $dailyEntryDebtor2->accountstreeid = 121;

        //////////////// end Rasl L maal
        //////////////// start Mogam3 L Hlak

        $dailyEntryCreditorArray2 = array();
        $dailyEntryCreditor2->value = $depreciation;
        $dailyEntryCreditor2->accountstreeid = 8;

        //////////////// end  Mogam3 L Hlak

        array_push($dailyEntryDebtorArray2, $dailyEntryDebtor2);
        array_push($dailyEntryCreditorArray2, $dailyEntryCreditor2);

        insertEntery($dailyEntry2, $dailyEntryDebtorArray2, $dailyEntryCreditorArray2, 0, $assetId, "assetController.php?do=editprint&id=$assetId");
    } else {
        $oldData = $myAssetsRecord->load($assetId);

        $treeId = $oldData->treeId;
        $treeData = $accountsTreeDAO->load($treeId);

        $loadAsset = $AssetscatDAO->load($assetscatid);

        $treeParent = $loadAsset->treeId;

        // print_r('<br>' . $treeParent . 'aaaaaaaaaaaaaaaaaaaaaaa');

        $accountsTree->customName = $assetName;
        $accountsTree->del = $treeData->del;
        $accountsTree->id = $treeId;
        $accountsTree->itemfrom = $treeData->itemfrom;
        $accountsTree->itemtype = $treeData->itemtype;
        $accountsTree->itemtype2 = $treeData->itemtype2;
        $accountsTree->layingOrder = $treeData->layingOrder;
        $accountsTree->sysdate = $treeData->sysdate;
        $accountsTree->name = $assetName;
        $accountsTree->notes = $treeData->notes;
        $accountsTree->parent = $treeParent;
        $accountsTree->theOrder = $treeData->theOrder;
        $accountsTree->theValue = $assetPrice;
        $accountsTree->userid = $treeData->userid;


        editTreeElement($accountsTree);
    }



    $myAssetsRecord->update($myAssets, $assetsDescription);
    $type = $_POST["type"];
    if ($type == 2) {
        $checkwithdrawalid = $_POST["checkwithdrawalid"];
        $txtUser = $_POST["txtUser"];
        $textNote = $_POST["textNote"];

        //$checkWithdrawal->checkwithdrawalnote=$textNote;
        $checkWithdrawal
            ->checkwithdrawaluser = $txtUser;
        $checkWithdrawal->checkwithdrawalid = $checkwithdrawalid;

        //  print_r($checkWithdrawal);
        $checkWithdrawalExtDAO->updateuser($checkWithdrawal, $textNote);
    }
}

//show all asset cat
function showallcat()
{
    global $AssetscatDAO;
    global $Assetscat;


    $alldata = $AssetscatDAO->queryByDel(0);
    return $alldata;
}

function getSaveValueBefore($saveid = 0)
{

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


    if ($saveid < 1) {
        $saveid = $_SESSION['saveid'];
    }

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

    return $saveValuebefore;
}

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

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

    if ($saveid < 1) {
        $saveid = $_SESSION['saveid'];
    }
    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

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

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

    if ($saveid < 1) {
        $saveid = $_SESSION['saveid'];
    }
    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

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

    $id = $mySavedailyRecord->insert($mySavedaily);

    return $id;
}

function updateckeck($assetId)
{



    global $checkWithdrawal;
    global $checkWithdrawalDAO;
    global $checkWithdrawalExtDAO;
    global $Checkcontroller;
    global $CheckcontrollerDAO;

    global $accountMove;
    global $accountMoveDAO;
    global $accountDAO;
    global $account;
    global $accountExtDAO;
    //print_r('assetId'.$assetId."<br>");

    $mydata = $CheckcontrollerDAO->queryByControllerid($assetId);
    // print_r($mydata);
    //print_r("<br><br><br>");

    $checkid = $mydata->checkid;
    $checkwithdrawalid = $mydata->controllerid;
    //print_r('$checkid'.$checkid.'<br>');
    //print_r('$checkwithdrawalid'.$checkwithdrawalid.'<br>');


    $checkdata = $checkWithdrawalDAO->load($checkid);
    //  print_r($checkdata);

    $checkWithdrawal->conditions = 0;
    $checkWithdrawal->checkwithdrawalid = $checkid;
    $checkWithdrawal->userid = $_SESSION['userid'];

    $checkWithdrawalExtDAO->updatedel($checkWithdrawal);





    $accountid = $checkdata->bankaccountid;
    $checkwithdrawalamount = $checkdata->checkwithdrawalamount;
    $accountdata = $accountDAO->load($accountid);
    $accountBefore = $accountdata->accountbeginingbalance;
    $bankid = $accountdata->bankid;


    $account->accountbeginingbalance = $accountBefore + $checkwithdrawalamount;


    $account->accountid = $accountid;

    //update
    $accountExtDAO->updateacount($account);


    //-------------------
    //Insert in accountmovement table
    $accountMove->accountmovementbefore = $accountBefore;
    $accountMove->accountid = $accountid;
    $accountMove->bankid = $bankid;
    $accountMove->accountmovementamount = $checkwithdrawalamount;
    $accountMove->accountmovementafter = $accountBefore + $checkwithdrawalamount;
    $accountMove->accountmovementtype = 0;
    $accountMove->processname = "الغاء شراء اصل";
    $accountMove->tablename = "assetController.php";
    $accountMove->accountmovementmodelid = $assetId;
    $accountMove->accountmovementmodelname = "wirhdrawalCheckCTRL";
    $accountMove->accountmovementdate = date("Y-m-d");

    $accountMove->userid = $_SESSION['userid'];
    //Insert
    $accountMoveid = $accountMoveDAO->insert($accountMove);
    if ($accountMoveid > 0) {

        $note = "sucess";
    } else {
        $note = "لقد حث خطا اثناء اجراء العمليه ";
    }






    return $note;
}

function execute()
{
    global $AssetscatEX;
    global $AssetscatDAO;
    global $Assetscat;

    global $myAssets;
    global $myAssetsRecord;
    global $myAssetsEx;
    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];


    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $assetId) {

            $assetdata = $myAssetsRecord->load($assetId);
            //print_r($assetdata);
            $type = $assetdata->type;
            $assetsName = $assetdata->assetsName;
            $conditions = $assetdata->conditions;

            if ($operationType == '1' && $conditions == 0) { //tempdelete
                try {
                    $note = delete($type, $assetId);
                    if ($note != "sucess") {
                        //get product category name

                        if (count($assetscatid) > 0) {

                            $outputString .= $assetsName . ": " . $note . "<br/>";
                        }
                    }
                } catch (Exception $e) {
                }
            } else {
                $outputString .= $assetsName . ": لا يمكن الغاء هذا الاصل لانه ملغى سابقا<br/>";
            }


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

        //print_r($outputString);
    }
}


function createSupplierInUseSP($supplier)
{
    global $supplierExt;
    if ((int) $supplier > 1) {
        $supplierExt->createSupplierInUseSP();
    }
}
function getSupplierDataFromSupplierInUseSP($supplier)
{
    global $supplierExt;
    global $supplierDao;
    if ($supplier == 1) {
        $supplier_data = $supplierDao->load($supplier);
    } elseif ($supplier > 1) {
        $noOfTries = 0;
        $supplier_data = $supplierExt->callSupplierInUseSP($supplier);
        while ($supplier_data->suppliercurrentDebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free supplier=$supplier with redbean");
                R::exec('UPDATE supplier SET  inUse = 0 where supplierid = ' . $supplier);
            }
            $supplier_data = $supplierExt->callSupplierInUseSP($supplier);
        }
    }
    return $supplier_data;
}

function markSupplierAsNOTInUse($supplier)
{ //mark as not in use "free him to be able to change debt again"
    global $supplierExt;
    if ($supplier == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $supplierExt->markSupplierAsNOTInUse($supplier);
    }
}

function liveBackupComment($txt)
{
    $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
    $toWrite = "\r\n-- ----------------------------------------------------------------------------------------------------\r\n";
    $toWrite .= $txt;
    $toWrite .= "\r\n-- ----------------------------------------------------------------------------------------------------\r\n\r\n";
    fwrite($myfile, $toWrite);
}
