<?php

$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array();
if (!in_array($do, $ajaxDoArr) && !isset($_POST['curlpost'])) {
    //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("../library/num_to_ar.php");

//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
include_once("dailyentryfun.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');

//Checkdeposit
require_once('../models/dao/CheckdepositDAO.class.php');
require_once('../models/dto/Checkdeposit.class.php');
require_once('../models/mysql/CheckdepositMySqlDAO.class.php');
require_once('../models/mysql/ext/CheckdepositMySqlExtDAO.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');

//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.class.php');

//Premium
require_once('../models/dao/PremiumDAO.class.php');
require_once('../models/dto/Premium.class.php');
require_once('../models/mysql/PremiumMySqlDAO.class.php');
require_once('../models/mysql/ext/PremiumMySqlExtDAO.class.php');

//Breadcrumb
require_once("../library/breadcrumb.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');


//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
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("header.html");
}



//here goes the instances and general variables
//Clientdebtchange
$Clientdebtchange = new Clientdebtchange();
$ClientdebtchangeDAO = new ClientdebtchangeMySqlDAO();
$ClientdebtchangeEX = new ClientdebtchangeMySqlExtDAO();

//Client
$Client = new Client();
$ClientDAO = new ClientMySqlDAO();
$ClientEX = new ClientMySqlExtDAO();

//Premium
$premium = new Premium();
$premiumDAO = new PremiumMySqlDAO();
$premiumExt = new PremiumMySqlExtDAO();

//Checkdeposit
$Checkdeposit = new Checkdeposit();
$CheckdepositDAO = new CheckdepositMySqlDAO();
$CheckdepositEX = new CheckdepositMySqlExtDAO();

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

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

$bankDAO = new BankMySqlDAO;
$bank = new Bank;
$bankExtDAO = new BankMySqlExtDAO;


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

//Breadcrumb
$breadcrumbObject = new Breadcrumb();

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

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

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



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

    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);

    $today = date("Y-m-d");
    $smarty->assign("today", $today);

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

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

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

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


    $returnvalue = add();
    try {
        if ($_POST['curlpost'] == 1) {
            echo $returnvalue[1];
        } else {
            if ($returnvalue[0] == "0") {
                header("location:?do=sucess");
            } else {
                header("location:?do=error");

//            $url = "depositcheckController.php?do=show";
//            $smarty->assign('urldirect', $url);
//            $note = " عفوا لا حساب العميل  اكبر  من قيمه الشيك<br>
//			حدث خطأ ... يرجى المحاولة مرة أخرى<br>";
//            $smarty->assign('msgnote', $note);
//            $smarty->display("notes2.html");
            }
        }
    } catch (Exception $ex) {
        //print_r($ex);
    }
} elseif ($_GET['do'] == "executeOperation") {
    include_once("../public/authentication.php");

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



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



    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);



    try {
        execute();
        show();
        $youtubes = $youtubeLinkDAO->queryAll();
        $smarty->assign("youtubes", $youtubes);
        $smarty->display("depositcheckview/show.html");

        $smarty->assign("customCheck", 1);
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "show") {

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


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



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



    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);

    // here the function that do the action

    show();

    $today = date("Y-m-d");
    $smarty->assign("today", $today);
    //here the smarty templates
    $smarty->display("depositcheckview/show.html");
    $smarty->assign('customdepositchec', 1);

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

    try {
        $id = $_POST["id"];
        $dailyentryid = $_POST['action'];

        // here the function that do the action
        $note = delete($id, $dailyentryid);
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            echo ($note === "sucess") ? 1 : 0;
        } else {
            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) {
        // print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");

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





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

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

    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);




    $smarty->display("depositcheckview/edit.html");
} elseif ($do == "editprint") {
    //here the permssion check
    include_once("../public/authentication.php");

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





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

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

    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);



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

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


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

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





    $showData = edit();


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

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

    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);



    //
    $ar_number = new convert_ar($showData->checkdepositamount, "male");
    $ar_number = $ar_number->convert_number();


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

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

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

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





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

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

    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);




    $smarty->display("depositcheckview/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('customdepositchec', 1);
$smarty->assign('customValidation', 1);

//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

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

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

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



    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $ClientdebtchangeDAO;


    global $Client;
    global $ClientDAO;
    global $ClientEX;




    global $Checkdeposit;
    global $CheckdepositDAO;
    global $CheckdepositEX;

    global $accountMove;
    global $accountMoveDAO;

    global $accountDAO;
    global $accountExtDAO;
    global $account;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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


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

        $today = date("Y-m-d H:i:s");
        $clientid = $_POST["clientid"];
        $accountid = (int) $_POST["accountid"];
        $accountnumber = $_POST["accountnumberDis"];
        $accountbeginingbalance = $_POST["accountbeginingbalance"];
        if ($_POST["txtAmount"]) {
            $checkwithdrawalamount = $_POST["txtAmount"];
        } else {
            $checkwithdrawalamount = $_POST["payedDept"];
        }

        $checkwithdrawalnote = $_POST["textNote"];
        $checkwithdrawalnumber = $_POST["txtcheckNum"];
        $checkwithdrawaluser = $_POST["txtUser"];

        if ($_POST["checkdate"]) {
            $checkdate = $_POST["checkdate"];
        } else {
            $checkdate = $today;
        }




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

            $accountData = $accountDAO->load($accountid);
            $accountbeginingbalance = $accountData->accountbeginingbalance;



            //
            $Checkdeposit->bankaccountid = $accountid;
            $Checkdeposit->clientid = $clientid;

            $Checkdeposit->accountbeforevalue = $accountbeginingbalance;
            $Checkdeposit->checkdepositamount = $checkwithdrawalamount;
            $Checkdeposit->checkdepositdate = $today;
            $Checkdeposit->conditions = 0;

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


            $Checkdepositid = $CheckdepositDAO->insert($Checkdeposit, $checkwithdrawalnote);



            if ($Checkdepositid != null) {

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

                $clientdata = getClientDataFromClientInUseSP($clientid);
                //$clientdata = $ClientDAO->load($clientid);
                $debtBefore = $clientdata->clientdebt;

                //print("mmm".$debtBefore);
//        if ($clientdata->clientdebt <= 0) {
//            $Client->clientdebt = 0;
//
//            //   print_r('Checkdepositid' . $Checkdepositid);
//            $CheckdepositDAO->delete($Checkdepositid);
//            //header("location:?do=error"); //cannot subtract debt from check amount
//
//            return "1";
//            exit; //can't subtract
//        } else {
//            if ($debtBefore >= $checkwithdrawalamount) {
//                $Client->clientdebt = ($debtBefore - $checkwithdrawalamount );
//            } else {
//
//                $CheckdepositDAO->delete($Checkdepositid);
//                return "1";
//                exit; //can't subtract
//            }
//        }

                $Client->clientdate = $today;
                $Client->clientdebt = ($debtBefore - $checkwithdrawalamount );
                $Client->clientid = $clientid;
                $Client->userid = $_SESSION['userid'];
                $ClientEX->updatedept($Client);
                markClientAsNOTInUse($clientid);

//---------------------------------------
//Insert in supplier dept cahnge
                $Clientdebtchange->clientdebtchangebefore = $debtBefore;

                $Clientdebtchange->clientdebtchangeamount = $checkwithdrawalamount;
                $Clientdebtchange->clientdebtchangetype = 1;
                $Clientdebtchange->tablename = "depositcheckController.php";
                $Clientdebtchange->clientdebtchangemodelid = $Checkdepositid;
                $Clientdebtchange->clientid = $clientid;
                $Clientdebtchange->clientdebtchangeafter = $debtBefore - $checkwithdrawalamount;
                $Clientdebtchange->clientdebtchangedate = date("Y-m-d H:i:s");
                $Clientdebtchange->userid = $_SESSION['userid'];
                $Clientdebtchange->processname = "ايداع شيك";
                $Clientdebtchange->dailyentryid = 0;




                $ClientdebtchangeID = $ClientdebtchangeDAO->insert($Clientdebtchange);

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



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

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


                $account->accountdate = $today;

                $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 = 0;
                $accountMove->processname = "ايداع شيك";
                $accountMove->tablename = "depositcheckController.php";
                $accountMove->accountmovementmodelid = $Checkdepositid;
                $accountMove->clientid = $clientid;

                $accountMove->accountmovementdate = $today;

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

//Insert
                $accountMoveDAO->insert($accountMove);
                $dailyEntry->entryComment = 'تم عمل ايداع  شيك الى حساب العميل(  ' . $clientdata->clientname . ' ) ';

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

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

//// الي حساب المدينون (اسم العميل)

                $dailyEntryCreditorArray = array();
                $dailyEntryCreditor->value = $checkwithdrawalamount;
                $clientTreeId = $clientdata->treeId;
                $dailyEntryCreditor->accountstreeid = $clientTreeId;

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

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

                $rowData = $CheckdepositDAO->load($Checkdepositid);

                $Checkdeposit->bankaccountid = $rowData->bankaccountid;
                $Checkdeposit->clientid = $rowData->clientid;

                $Checkdeposit->accountbeforevalue = $rowData->accountbeforevalue;
                $Checkdeposit->checkdepositamount = $rowData->checkdepositamount;
                $Checkdeposit->checkdepositdate = $rowData->checkdepositdate;
                $Checkdeposit->conditions = $rowData->conditions;

                $Checkdeposit->checkdepositnumber = $rowData->checkdepositnumber;
                $Checkdeposit->checkdeposituser = $rowData->checkdeposituser;
                $Checkdeposit->userid = $rowData->userid;
                $Checkdeposit->dailyentryid = $did;
                $CheckdepositDAO->update($Checkdeposit, $checkwithdrawalnote);


                $premiumid = filter_input(INPUT_POST, 'premiumid');
                if (!empty($premiumid)) {
                    $premiumData = $premiumDAO->load($premiumid);
                    $dept_rest = $premiumData->value - $premiumData->rest;

                    if ($dept_rest < $checkwithdrawalamount) {
                        ## close chosed  $dept_details
                        $rest = $checkwithdrawalamount - $dept_rest;

                        $premiumData->payed = 1;
                        $premiumData->rest = $premiumData->rest + $rest;
                        $premiumData->value = $premiumData->value;
                        $premiumDAO->update($premiumData);

                        ## calculate the rest paid money
                        ## get all uncompleted installment
                        $premiumDetailId = filter_input(INPUT_POST, 'premiumDetailId');
                        $ClientPremiumData = $premiumExt->queryByPremiumclientConditionPayed($premiumDetailId);

                        foreach ($ClientPremiumData as $data) {
                            if ($rest <= 0) {
                                break;
                            }
                            ##
                            elseif ($rest >= ($data->value - $data->rest)) {
                                $data->payed = 1;
                                $data->rest = $data->value;
                                $premiumDAO->update($data);
                                $rest = $rest - $data->value;
                            }
                            ##
                            elseif ($rest < ($data->value - $data->rest)) {
                                $data->rest = $data->rest + $rest;
                                $premiumDAO->update($data);
                                $rest = 0;
                            }
                        }
                    }
                    ##
                    elseif ($dept_rest == $checkwithdrawalamount) {
                        $premiumData->payed = 1;
                        $premiumData->rest = $premiumData->rest + $dept_rest;
                        $premiumDAO->update($premiumData);
                    }
                    ##
                    else {
                        $premiumData->rest = $premiumData->rest + $checkwithdrawalamount;
                        $premiumDAO->update($premiumData);
                    }
                }
            }
        }

        $mytransactions->commit();
        return array("0", $ClientdebtchangeID);
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

// show the form

function show() {
//to use the variable out side the funcion
    global $Checkdeposit;
    global $CheckdepositDAO;
    global $CheckdepositEX;

    global $ClientDAO;


    global $bankExtDAO;
    global $smarty;

//select all data from Assets tbl

    $clientId = $_REQUEST["clientid"];
    $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 = $CheckdepositEX->queryWithDateExt($from, $to);

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

        $message = "عرض الايداعات للعميل : " . $myclientdata->clientname;
        $smarty->assign('message', $message);

// get the all colums number
        $shownData = $CheckdepositEX->queryWithClientIdExt($clientId);

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

        $message = "عرض الايداعات  من تاريخ : " . $from . "";
        $smarty->assign('message', $message);
        $condition = '>=';
// get the all colums number
        $shownData = $CheckdepositEX->queryWithOneDate($condition, $from);

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

        $message = "عرض الايداعات  الى تاريخ : " . $to . "";
        $smarty->assign('message', $message);
        $condition = '<=';
// get the all colums number
        $shownData = $CheckdepositEX->queryWithOneDate($condition, $to);

// 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 = $CheckdepositEX->loadEX($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 = $CheckdepositEX->queryWithDateExt(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, $dailentry) {
//to use the variable out side the funcion


    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $ClientdebtchangeDAO;


    global $Client;
    global $ClientDAO;
    global $ClientEX;


    global $Checkdeposit;
    global $CheckdepositDAO;
    global $CheckdepositEX;


    global $accountMove;
    global $accountMoveDAO;

    global $accountDAO;
    global $accountExtDAO;
    global $account;


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

        $id = $id; //$_GET["id"];
        $Checkdepositid = $id;
        $dailyentryid = $dailentry;
        $dailyentryid2 = $_POST['dailyentryid'];
        $today = date("Y-m-d");
        $Checkdeposit = $CheckdepositDAO->load($Checkdepositid);

        ########################################################################
        //choose erpDB user has choosen in obygy_app
        //it is reuired by eng.sherif to keep edit info to person who add, not the one who is updating as long as it is not الاستقبال group
        if (isset($_POST["erpDB"]) && !empty($_POST["erpDB"])) {
            if (isset($_POST['obgyGroupId']) && $_POST['obgyGroupId'] == 3) {
                //it is reception الاستقبال// and its id @royal=3
                //use data coming for user who make update
            } else {
                //keep using the same data of user who made bill
                //get user id
                $_POST['userid'] = $Checkdeposit->userid;
                $_SESSION['userid'] = (isset($_POST['userid']) && $_POST['userid'] > 0) ? (int) $_POST['userid'] : 1;
            }
        }
        ########################################################################
        //del only in same day
        // if ($today == $Checkdeposit->checkdate) {
            if (empty($dailyentryid)) {
                $dailyentryid = $Checkdeposit->dailyentryid;
            }
            if (empty($dailyentryid2)) {
                $dailyentryid2 = $Checkdeposit->dailyentryid;
            }

            $Checkdeposit->checkdepositid = $id;
            $Checkdeposit->userid = $_SESSION['userid'];
            $Checkdeposit->conditions = 1;
            $CheckdepositEX->updatdel($Checkdeposit);


            $checkdata = $CheckdepositDAO->load($id);
            $clientid = $checkdata->clientid;
            $checkdepositamount = $checkdata->checkdepositamount;
            $accountid = $checkdata->bankaccountid;




            if ($Checkdepositid != null) {

                $clientdata = getClientDataFromClientInUseSP($clientid);
                //$clientdata = $ClientDAO->load($clientid);
                $debtBefore = $clientdata->clientdebt;

// print("debtBefore:".$debtBefore);
                $Client->clientdebt = ($debtBefore + $checkdepositamount );


//print_r("debtafter".$debtBefore + $checkdepositamount."<br>");
                $Client->clientdate = $today;
                $Client->clientdebt = ($debtBefore + $checkdepositamount );
                $Client->clientid = $clientid;
                $Client->userid = $_SESSION['userid'];
//$supplierExtDAO -> updateSupplierCurrentDebt();
                $ClientEX->updatedept($Client);
                markClientAsNOTInUse($clientid);

//---------------------------------------
//Insert in supplier dept cahnge
                $Clientdebtchange->clientdebtchangebefore = $debtBefore;
                $Clientdebtchange->clientid = $clientid;
                $Clientdebtchange->clientdebtchangeamount = $checkdepositamount;
                $Clientdebtchange->clientdebtchangetype = 0;
                $Clientdebtchange->tablename = "depositcheckController.php";
                $Clientdebtchange->clientdebtchangemodelid = $Checkdepositid;
                $Clientdebtchange->clientdebtchangeafter = $debtBefore + $checkdepositamount;
                $Clientdebtchange->clientdebtchangedate = date("Y-m-d H:i:s");
                $Clientdebtchange->userid = $_SESSION['userid'];
                $Clientdebtchange->processname = "الغاء ايداع شيك";
                if (isset($dailyentryid) && $dailyentryid2 == '') {
                    $Clientdebtchange->dailyentryid = $dailyentryid;
                } else {
                    $Clientdebtchange->dailyentryid = $dailyentryid2;
                }

//print_r($Clientdebtchange);
//Insert
                $ClientdebtchangeDAO->insert($Clientdebtchange);

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



                $accoundatat = $accountDAO->load($accountid);
                $accountBefore = $accoundatat->accountbeginingbalance;
                $bankid = $accoundatat->bankid;
                if ($accountBefore >= $checkwithdrawalamount) {
                    $account->accountbeginingbalance = $accountBefore - $checkdepositamount;
                }


                $account->accountdate = $today;

                $account->accountid = $accountid;

//        print_r("<pre>");
//        print_r($account);
//        print_r("<pre>");
//update
                $accountExtDAO->updateacount($account);


//-------------------
//Insert in accountmovement table
                $accountMove->accountmovementbefore = $accountBefore;
                $accountMove->accountid = $accountid;
                $accountMove->bankid = $bankid;
                $accountMove->accountmovementamount = $checkdepositamount;
                $accountMove->accountmovementafter = $accountBefore - $checkdepositamount;
                $accountMove->accountmovementtype = 1;
                $accountMove->processname = "الغاء ايداع شيك";
                $accountMove->tablename = "depositcheckController.php";
                $accountMove->accountmovementmodelid = $Checkdepositid;
                $accountMove->clientid = $clientid;

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

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

//Insert
                if ($accountMoveDAO->insert($accountMove)) {
                    if (isset($dailyentryid) && $dailyentryid2 == '') {
                        reverseEntryWithItsID($dailyentryid, 1);
                    } else {
                        reverseEntryWithItsID($dailyentryid2, 1);
                    }





                    $mytransactions->commit();
                    return "sucess";
                } else {



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

// edit in table

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


    global $Checkdeposit;
    global $CheckdepositDAO;
    global $CheckdepositEX;
    global $ClientDAO;
    global $smarty;

    $checkdepositid = $_POST["checkdepositid"];

    $id = '';
    if ($checkdepositid == '') {

        $id = $_GET["id"];
    } else {
        $id = $checkdepositid;
    }
    $showData = $CheckdepositEX->loadEX($id);

    $clientData = $ClientDAO->load($showData->clientid);
    $smarty->assign('clientdebt', $clientData->clientdebt);
//    print_r("<pre>");
//    print_r($showData);
//
//    print_r("<pre>");

    return $showData;
}

// update table

function update() {



    global $Checkdeposit;
    global $CheckdepositDAO;
    global $CheckdepositEX;





    $checkdepositid = $_POST["checkdepositid"];
    $txtUser = $_POST["txtUser"];
    $checkdepositnote = $_POST["checkdepositnote"];


    $Checkdeposit->checkdeposituser = $txtUser;
    $Checkdeposit->checkdepositid = $checkdepositid;

    $CheckdepositEX->updateuser($Checkdeposit, $checkdepositnote);
}

//show all asset cat

function showallcat() {
    global $AssetscatDAO;
    global $Assetscat;


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

function getallclient() {

    global $ClientDAO;
    global $Client;
    global $ClientEX;


    $allclientdata = $ClientDAO->queryAll();

    return $allclientdata;
}

function execute() {
    global $Checkdeposit;
    global $CheckdepositDAO;


    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];

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

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

            $checkdepositnumber = $checkdata->checkdepositnumber;
            $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($dailyentryid);
                            $outputString .= $checkdepositnumber . ": " . $note . "<br/>";
                        }
                    } else {

                        reverseEntryWithItsID($dailyentryid);

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

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


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

function getClientDataFromClientInUseSP($clientid) {
    global $ClientEX;
    global $ClientDAO;
    if ($clientid == 1) {
        $client_data = $ClientDAO->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $ClientEX->callClientInUseSP($clientid);
        while ($client_data->clientdebt == '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 client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $ClientEX->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

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

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

?>