<?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");

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');
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');
//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.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
$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;
//Supplier
$Supplier = new Supplier();
$SupplierDAO = new SupplierMySqlDAO();
$SupplierEX = new SupplierMySqlExtDAO();
//Checkcontroller
$Checkcontroller = new Checkcontroller();
$CheckcontrollerDAO = new CheckcontrollerMySqlDAO();
$CheckcontrollerEX = new CheckcontrollerMySqlExtDAO();
//Accountmovement
$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;

$supDebtChangeDAO = new SupplierdebtchangeMySqlDAO;
$supDebtChangeExtDAO = new SupplierdebtchangeMySqlExtDAO;
$supDebtChange = new Supplierdebtchange;
//Breadcrumb
$breadcrumbObject = new Breadcrumb();

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


//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

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

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

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



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

    $allsuplierdata = getallsuplier();
    $smarty->assign("allsuplierdata", $allsuplierdata);

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

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

    //here the permssion check
    include_once("../public/authentication.php");
    $returnvalue = add();

    if ($returnvalue == "0") {

        header("location:?do=sucess");
    } else {
        //header("location:?do=error");

        $url = "checkwithdrawalController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = " عفوا لا حساب العميل اقل من قيمه الشيك<br>
			حدث خطأ ... يرجى المحاولة مرة أخرى<br>";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }


    /* try
      {
      //here the function that do the action

      header("location:?do=sucess");
      }
      catch(Exception $e)
      {
      header("location:?do=error");
      } */
} elseif ($do == "show") {

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


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



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

    $allsuplierdata = getallsuplier();
    $smarty->assign("allsuplierdata", $allsuplierdata);


    // here the function that do the action

    show();

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

    //here the smarty templates
    $smarty->display("checkwithdrawalview/show.html");

    $smarty->assign("customCheck", 1);
} elseif ($_GET['do'] == "executeOperation") {
    //here the permssion check
    include_once("../public/authentication.php");


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



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

    $allsuplierdata = getallsuplier();
    $smarty->assign("allsuplierdata", $allsuplierdata);





    try {
        execute();
        show();
        $smarty->display("checkwithdrawalview/show.html");

        $smarty->assign("customCheck", 1);
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "delete") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        // here the function that do the action
        $id = $_REQUEST["id"];
        $note = delete($id);
        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");
        }
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="checkwithdrawalController.php?do=show">الشيكات</a> > تعديل شيك', 'checkwithdrawalController.php', 0);
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);





    $showData = edit();
    $smarty->assign("showData", $showData);

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

    //allsuplierdata
    $allsuplierdata = getallsuplier();
    $smarty->assign("allsuplierdata", $allsuplierdata);




    $smarty->display("checkwithdrawalview/edit.html");
} elseif ($do == "editprint") {
    //here the permssion check
    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="checkwithdrawalController.php?do=show">الشيكات</a> > تعديل شيك', 'checkwithdrawalController.php', 0);
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);





    $showData = edit();
    $smarty->assign("showData", $showData);

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

    //allsuplierdata
    $allsuplierdata = getallsuplier();
    $smarty->assign("allsuplierdata", $allsuplierdata);



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

    $smarty->assign("customPrint", 1);
} elseif ($do == "update") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        // here the function that do the action
        update();

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

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="checkwithdrawalController.php?do=show">الشيكات</a> > تعديل شيك', 'checkwithdrawalController.php', 0);
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);





    $showData = edit();
    $smarty->assign("showData", $showData);

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

    //allsuplierdata
    $allsuplierdata = getallsuplier();
    $smarty->assign("allsuplierdata", $allsuplierdata);




    $smarty->display("checkwithdrawalview/details.html");
} elseif ($do == "sucess") {

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

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



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

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

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

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

// load Assets data
// add in Assets tbl
function add()
{



    global $supDebtChange;
    global $supDebtChangeDAO;
    global $supDebtChangeExtDAO;
    global $Supplier;
    global $SupplierDAO;
    global $SupplierEX;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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


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

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

        $supplierid = $_POST["supplierid"];
        $accountid = (int) $_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 H:i:s");

        $ddlBank = (int) $_POST["ddlBank"];
        if ($accountid > 0 && $ddlBank > 0) {

            $checkWithdrawal->bankaccountid = $accountid;
            $checkWithdrawal->supplierid = $supplierid;
            $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);  //$checkWithdrawalDAO -> insert($checkWithdrawal,$checkwithdrawalnote);
            //print_r('checkWithdrawalId ='.$checkWithdrawalId."<br>");

            if ($checkWithdrawalId != null) {

                //////////////////////////


                $supplierdata = getSupplierDataFromSupplierInUseSP($supplierid);
                //$supplierdata = $SupplierDAO->load($supplierid);
                $debtBefore = $supplierdata->suppliercurrentDebt;
                //print_r("debtBefore=".$debtBefore."<br>");
                //            if ($supplierdata->suppliercurrentDebt < 0) {
                //                $supplierdata->suppliercurrentDebt = 0;
                //                $checkWithdrawalDAO->delete($checkWithdrawalId);
                //                //	header("location:?do=error"); //cannot subtract debt from check amount
                //            } else {
                //                if ($debtBefore >= $checkwithdrawalamount) {
                //                    // print_r("debtBefore:".$debtBefore);
                //                    $Supplier->suppliercurrentDebt = ($debtBefore - $checkwithdrawalamount);
                //                } else {
                //                    //print("else");
                //                    $checkWithdrawalDAO->delete($checkWithdrawalId);
                //                    //header("location:?do=error");
                //
                //
                //
                //                    $mytransactions->rollback();
                //                    return "1";
                //                    exit; //can't subtract
                //                }
                //            }
                //print_r("debtBefore= ".$debtBefore."<br>");

                $Supplier->suppliercurrentDebt = ($debtBefore - $checkwithdrawalamount);
                $Supplier->supplierid = $supplierid;
                $Supplier->supplierdate = date("Y-m-d");
                $Supplier->userid = $_SESSION['userid'];
                //$supplierExtDAO -> updateSupplierCurrentDebt();
                $xx = $SupplierEX->updatedept($Supplier);
                markSupplierAsNOTInUse($supplierid);
                //print_r('xx ='.$xx);
                //---------------------------------------
                //Insert in supplier dept cahnge
                $supDebtChange->supplierdebtchangebefore = $debtBefore;
                $supDebtChange->supplierid = $supplierid;

                $supDebtChange->supplierdebtchangeamount = $checkwithdrawalamount;
                $supDebtChange->supplierdebtchangetype = 1;
                $supDebtChange->tablename = "checkwithdrawalController.php";
                $supDebtChange->supplierdebtchangemodelid = $checkWithdrawalId;
                $supDebtChange->supplierdebtchangeafter = $debtBefore - $checkwithdrawalamount;
                $supDebtChange->supplierdebtchangedate = date("Y-m-d");
                $supDebtChange->userid = $_SESSION['userid'];
                $supDebtChange->processname = "دفع شيك";
                $supDebtChange->dailyentryid = 0;


                // print_r($supDebtChange);
                //Insert
                $supDebtChangeDAO->insert($supDebtChange);

                ///////////////////////////



                $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 = "checkwithdrawalController.php";
                $accountMove->accountmovementmodelid = $checkWithdrawalId;

                $accountMove->accountmovementdate = $checkwithdrawaldate;

                $accountMove->userid = $_SESSION['userid'];;

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

                $dailyEntry->entryComment = 'تم عمل سحب شيك للمورد (  ' . $supplierdata->suppliername . ' )';
                //// من حساب  الدائنون (اسم المورد)
                $dailyEntryDebtorArray = array();
                $dailyEntryDebtor->value = $checkwithdrawalamount;
                $supplierTreeId = $supplierdata->treeId;
                $dailyEntryDebtor->accountstreeid = $supplierTreeId;

                //// الي حساب البنك

                $dailyEntryCreditorArray = array();
                $dailyEntryCreditor->value = $checkwithdrawalamount;
                $accountData = $accountDAO->load($accountid);
                $accountTreeId = $accountData->treeId;
                $dailyEntryCreditor->accountstreeid = $accountTreeId;


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

                $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $checkWithdrawalId, "checkwithdrawalController.php?do=show&id=$checkWithdrawalId");
                $did = $returnedData[1];

                $rowData = $checkWithdrawalDAO->load($checkWithdrawalId);

                $checkWithdrawal->bankaccountid = $rowData->bankaccountid;
                $checkWithdrawal->supplierid = $rowData->supplierid;
                $checkWithdrawal->accountnumber = $rowData->accountnumber;
                $checkWithdrawal->accountbeforevalue = $rowData->accountbeforevalue;
                $checkWithdrawal->checkwithdrawalamount = $rowData->checkwithdrawalamount;
                $checkWithdrawal->checkwithdrawaldate = $rowData->checkwithdrawaldate;
                $checkWithdrawal->conditions = $rowData->conditions;

                //$checkWithdrawal->checkwithdrawalnote=$checkwithdrawalnote;
                $checkWithdrawal->checkwithdrawalnumber = $rowData->checkwithdrawalnumber;
                $checkWithdrawal->checkwithdrawaluser = $rowData->checkwithdrawaluser;
                $checkWithdrawal->userid = $rowData->userid;
                $checkWithdrawal->dailyentryid = $did;

                print_r($did . 'adddddddddddd');
                $checkWithdrawalDAO->update($checkWithdrawal);



                $mytransactions->commit();
                return "0";
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        markSupplierAsNOTInUse($_POST["supplierid"]);
    }
}

// show the form
function show()
{
    //to use the variable out side the funcion
    global $checkWithdrawal;
    global $checkWithdrawalDAO;
    global $checkWithdrawalExtDAO;
    global $bankExtDAO;
    global $SupplierDAO;

    global $smarty;

    //select all data from Assets tbl

    $supplierid = $_REQUEST["supplierid"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];
    $id = (int) $_REQUEST["id"];

    if (isset($to) && $to != "" && isset($from) && $from != "") {
        $message = "عرض المسحوبات  من تاريخ : " . $from . "  الى تاريخ  " . $to;
        $smarty->assign('message', $message);

        // get the all colums number
        $shownData = $checkWithdrawalExtDAO->queryBydateExt($from, $to);


        // assign your db results to the template
        $smarty->assign('shownData', $shownData);
    } elseif (isset($supplierid) && $supplierid != "-1") {

        $mysupplierdata = $SupplierDAO->load($supplierid);

        $message = "عرض المسحوبات للمورد : " . $mysupplierdata->suppliername;
        $smarty->assign('message', $message);


        // get the all colums number
        $shownData = $checkWithdrawalExtDAO->queryWithSupplieridExt($supplierid);

        // assign your db results to the template
        $smarty->assign('shownData', $shownData);
    } elseif (isset($id) && $id > 0) {

        $message = "عرض المسحوبات  رقم: " . $id . "";
        $smarty->assign('message', $message);
        // get the all colums number
        $temp = $checkWithdrawalExtDAO->loadExt($id);
        $shownData = array($temp);

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

        $message = "عرض المسحوبات  من تاريخ : " . date("Y-m-d") . "  الى تاريخ :   " . date("Y-m-d");
        $smarty->assign('message', $message);


        // get the all colums number
        $shownData = $checkWithdrawalExtDAO->queryBydateExt(date("Y-m-d"), date("Y-m-d"));

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

//update tempdelete in Assets tbl

function delete($id)
{
    //to use the variable out side the funcion


    global $supDebtChange;
    global $supDebtChangeDAO;
    global $supDebtChangeExtDAO;
    global $Supplier;
    global $SupplierDAO;
    global $SupplierEX;



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

    global $accountMove;
    global $accountMoveDAO;
    global $accountDAO;
    global $account;
    global $accountExtDAO;

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

        $dailyentry = $_GET['action'];

        $dailyentryid2 = $_POST['dailyentryid'];

        $checkid = $id; //$_GET["id"];
        {


            $checkdata = $checkWithdrawalDAO->load($checkid);
            $accountid = $checkdata->bankaccountid;
            $checkwithdrawalamount = $checkdata->checkwithdrawalamount;



            //////////////////////////
            $supplierid = $checkdata->supplierid;

            $supplierdata = getSupplierDataFromSupplierInUseSP($supplierid);
            //$supplierdata = $SupplierDAO->load($supplierid);
            $debtBefore = $supplierdata->suppliercurrentDebt;
            //print("mmm".$debtBefore);
            //print_r("debtBefore".$debtBefore."<br>");

            $Supplier->suppliercurrentDebt = ($debtBefore + $checkwithdrawalamount);
            $Supplier->supplierid = $supplierid;
            $Supplier->userid = $_SESSION['userid'];
            $Supplier->supplierdate = date("Y-m-d");

            //$supplierExtDAO -> updateSupplierCurrentDebt();
            $SupplierEX->updatedept($Supplier);
            markSupplierAsNOTInUse($supplierid);

            //---------------------------------------
            //Insert in supplier dept cahnge
            $supDebtChange->supplierdebtchangebefore = $debtBefore;
            $supDebtChange->supplierid = $supplierid;

            $supDebtChange->supplierdebtchangeamount = $checkwithdrawalamount;
            $supDebtChange->supplierdebtchangetype = 0;
            $supDebtChange->tablename = "checkwithdrawalController.php";
            $supDebtChange->supplierdebtchangemodelid = $checkid;
            $supDebtChange->supplierdebtchangeafter = $debtBefore + $checkwithdrawalamount;
            $supDebtChange->supplierdebtchangedate = date("Y-m-d");
            $supDebtChange->userid = $_SESSION['userid'];
            $supDebtChange->processname = "حذف دفع شيك";
            if (isset($dailyentry) && $dailyentryid2 == '') {
                $supDebtChange->dailyentryid = $dailyentry;
            } else {
                $supDebtChange->dailyentryid = $dailyentryid2;
            }

            //print_r($supDebtChange);
            //Insert
            $supDebtChangeDAO->insert($supDebtChange);

            ///////////////////////////

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


            //print_r($checkWithdrawal);
            $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 = "wirhdrawalCheckController.php";
                $accountMove->accountmovementmodelid = $checkid;

                $accountMove->accountmovementdate = date("Y-m-d H:i:s");

                $accountMove->userid = $_SESSION['userid'];
                //Insert

                if ($accountMoveDAO->insert($accountMove)) {
                    if (isset($dailyentry) && $dailyentryid2 == '') {

                        reverseEntryWithItsID($dailyentry, 1);
                    } else {
                        reverseEntryWithItsID($dailyentryid2, 1);
                    }





                    $mytransactions->commit();
                    return "sucess";
                } else {
                    $mytransactions->rollback();
                    return "لم تتم العمليه بنجاح";
                }
            }
        }

        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        markSupplierAsNOTInUse($supplierid);
    }
}

// edit in table
function edit()
{
    //to use the variable out side the funcion


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

    global $smarty;



    $id = $_GET["id"];

    $showData = $checkWithdrawalExtDAO->queryByIdExtwithsuplier($id);
    //print_r($showData);
    if ($showData->suppliername) {
        $debtRow = R::getRow('select supplierdebtchangebefore,supplierdebtchangeafter from supplierdebtchange where tablename="checkwithdrawalController.php" and supplierdebtchangemodelid=' . $id);
        $debtBefore = $debtRow['supplierdebtchangebefore'];
        $debtAfter = $debtRow['supplierdebtchangeafter'];
    }

    $smarty->assign('debtBefore', $debtBefore);
    $smarty->assign('debtAfter', $debtAfter);
    return $showData;
}

// update table
function update()
{


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



    $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 getallsuplier()
{

    global $SupplierDAO;
    global $Supplier;
    global $SupplierEX;


    $allsuplierdata = $SupplierDAO->queryAll();
    return $allsuplierdata;
}

function execute()
{

    global $checkWithdrawal;
    global $checkWithdrawalDAO;

    global $checkWithdrawal;
    global $checkWithdrawalDAO;

    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];

    $dailyentry = filter_input(INPUT_POST, 'dailyentryid');
    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $checkId) {

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

            $checkwithdrawalnumber = $checkdata->checkwithdrawalnumber;
            $conditions = $checkdata->conditions;

            if ($operationType == '1' && $conditions == 0) { //tempdelete
                try {
                    $note = delete($checkId);
                    if ($note != "sucess") {
                        //get product category name
                        if (count($assetscatid) > 0) {
                            reverseEntryWithItsID($dailyentry);

                            $outputString .= $checkwithdrawalnumber . ": " . $note . "<br/>";
                        }
                    } else {

                        reverseEntryWithItsID($dailyentry);

                        $outputString .= $checkwithdrawalnumber . ": تمت العملية بنجاح <br/>";
                    }
                } catch (Exception $e) {
                }
            } else {

                $outputString .= $checkwithdrawalnumber . ": لا يمكن الغاء هذا الشيك لانه ملغى سابقا<br/>";
            }


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

        //print_r($outputString);
    }
}

function getSupplierDataFromSupplierInUseSP($supplier)
{
    global $SupplierEX;
    global $SupplierDAO;
    if ($supplier == 1) {
        $supplier_data = $SupplierDAO->load($supplier);
    } elseif ($supplier > 1) {
        $noOfTries = 0;
        $supplier_data = $SupplierEX->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 = $SupplierEX->callSupplierInUseSP($supplier);
        }
    }
    return $supplier_data;
}

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