<?php

//the global file operation
include("../public/impOpreation.php");
//include("../library/regenerateSession.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");

//Dated Checked
require_once('../models/dao/DatedcheckedDAO.class.php');
require_once('../models/dto/Datedchecked.class.php');
require_once('../models/mysql/DatedcheckedMySqlDAO.class.php');
require_once('../models/mysql/ext/DatedcheckedMySqlExtDAO.class.php');

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

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

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

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

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

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

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

//Account Movement
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/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'];

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

  Controller Name :- datedChecked Controller

  OPERTATION in Controller

  1- add datedChecked
  2- edit datedChecked
  3- delete datedChecked

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

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

//here goes the instances and general variables
//datedChecked
$datedChecked = new Datedchecked();
$datedCheckedDAO = new DatedcheckedMySqlDAO();
$datedCheckedEX = new DatedcheckedMySqlExtDAO();

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


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

//Bank
$myBank = new Bank();
$myBankRecord = new BankMySqlDAO();
$myBankEx = new BankMySqlExtDAO();

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

//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveEX = new SaveMySqlExtDAO();

//save daily
$saveDaily = new Savedaily();
$saveDailyADO = new SavedailyMySqlDAO();
$saveDailyEX = new SavedailyMySqlExtDAO();

//bank
$bank = new Bank();
$bankADO = new BankMySqlDAO();
$bankEx = new BankMySqlExtDAO();

//Bank Account
$bankAccount = new Bankaccount();
$bankAccountADO = new BankaccountMySqlDAO();
$bankAccountEx = new BankaccountMySqlExtDAO();

//Checkdeposit
$checkDeposit = new Checkdeposit();
$checkDepositADO = new CheckdepositMySqlDAO();
$CheckdepositEX = new CheckdepositMySqlExtDAO();

//Clientdebtchange
$clientDebtChange = new Clientdebtchange();
$clientDebtChangeADO = new ClientdebtchangeMySqlDAO();
$clientDebtChangeEX = new ClientdebtchangeMySqlExtDAO();

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

//supplier Dept chang
$supplierDept = new Supplierdebtchange();
$supplierDeptDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptEX = new SupplierdebtchangeMySqlExtDAO();

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

//Account Movement
$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;
$accountMovementExt = new AccountmovementMySqlExtDAO();

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

if (empty($do)) {
    //here the permission check
    //include_once("../public/authentication.php");
    $smarty->display("datedCheckedView/start.html");
} elseif ($do == "selectCustomer") {

    $paytype = $_POST["paytype"];
    $smarty->assign("paytype", $paytype);

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

    $bank = $bankADO->queryAll();
    $smarty->assign("bank", $bank);


    if ($paytype == "0") {
        try {
            //all client
            $allClientData = $clientDAO->queryAll();

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

            $smarty->display("datedCheckedView/addClient.html");
            //header("location:?do=showClient");
        } catch (Exception $e) {
            echo $e;
            //header("location:?do=error");
        }
    } elseif ($paytype == "1") {
        try {
            //all supplier
            $allSupplier = $supplierDAO->queryAll();

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

            $smarty->display("datedCheckedView/addSupllier.html");
            // header("location:?do=showSupllier");
        } catch (Exception $e) {
            echo $e;
            //header("location:?do=error");
        }
    }
}

/* ------------------------------For Client  and suplier --------------------------------------- */

//add
elseif ($do == "add") {

    //authintcation
    include_once("../public/authentication.php");

    try {
        $typ = add();
        //  reduceDept();
        if ($typ == 0) {
            header("location:?do=showClient");
        } else {
            header("location:?do=showSupllier");
        }
    } catch (Exception $e) {
        echo $e;
        header("location:?do=error");
    }
}


//showClient
elseif ($do == "showClient") {
    //authintcation
    include_once("../public/authentication.php");

    try {
        $bank = $bankADO->queryAll();
        $smarty->assign("bank", $bank);


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


        // $row = $datedCheckedEX->queryAllWitClientName();
// //        print_r('<pre>');
// //        print_r($row);
// //        print_r('<pre>');
//         //print_r($row);
//         $smarty->assign("row", $row);
//         $notPayVal = 0;
//         foreach ($row as $val) {
//             if ($val->done == 0) {
//                 $notPayVal += $val->checkValue;
//             }
//         }
//         $smarty->assign("notPayVal", $notPayVal);
        //showAllDatat();
        $smarty->display("datedCheckedView/showClient.html");
        //header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        //header("location:?do=error");
    }
}

//payCheck for customer
elseif ($do == "payCheck") {
    //authintcation
    include_once("../public/authentication.php");

    try {
        //all supllier
        $allSupplier = $supplierDAO->queryAll();
        $smarty->assign("allSupplier", $allSupplier);

        //All Bank
        $bank = $bankADO->queryAll();
        $smarty->assign("bank", $bank);

        $savebefor = getSaveValueBefore();
        $allSave = $saveDAO->queryByConditions(0);
        $smarty->assign("savebefor", $savebefor);
        $smarty->assign("allSave", $allSave);

        //DatedChecked id
        $id = $_GET['id'];
        $supplierid = $_GET['supplierid'];
        $smarty->assign("supplierid", $supplierid);

        $row = $datedCheckedDAO->load($id);

        //Client Id
        $id1 = $row->clientNum;
        if ($supplierid) {
            $allClient = $supplierDAO->load($id1);
            $clName = $allClient->suppliername;
        } else {
            $allClient = $clientDAO->load($id1);
            $clName = $allClient->clientname;
        }
        $smarty->assign("clName", $clName);





        //savedailymodelid
        $idPost = $row->datedCheckedID;
        $smarty->assign("idPost", $idPost);
        $smarty->assign("row", $row);


        //BankAccount Id
        $accountid = $bankAccount->accountid;
        $smarty->assign("accountid", $accountid);


        $smarty->display("datedCheckedView/payCheck.html");
        //header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        //header("location:?do=error");
    }
}

//payment
elseif ($do == "payment") {
    $paytype = $_POST["paytype"];
    $supplierid = $_POST["supplierid"];
    // اضافه قيمه الشيك الى الخزينه
    if ($paytype == "0") {
        try {
            //insert in save table & Save daily Table
            $saveid = (int) $_POST["ddlsave"];
            if ($saveid > 0) {

                insertSaveAndSaveDaily();
                // reduceSave();
                done();
            }

            if ($supplierid) {
                header("location:?do=showSupllier");
            } else {
                header("location:?do=showClient");
            }
        } catch (Exception $e) {
            // echo $e;
            header("location:?do=error");
        }
    }

    // اضافه قيمه الشيك الى البنك
    elseif ($paytype == "1") {
        try {

            addInBankDeposit();
            done();
            if ($supplierid) {
                header("location:?do=showSupllier");
            } else {
                header("location:?do=showClient");
            }
        } catch (Exception $e) {
            //  print_r($e);
            header("location:?do=error");
        }
    }

    // اضافه قيمه الشيك الى مورد
    /* if ($paytype == "2") {
      try {
      $supID = $_POST['supName'];
      print_r("supID = " . $supID);

      $id = $_POST['suplierID'];
      $row1 = $supplierDAO->load($id);
      $suppliercurrentDebt = $row1->suppliercurrentDebt;
      $smarty->assign("suppliercurrentDebt", $suppliercurrentDebt);
      print_r("suppliercurrentDebt" . $suppliercurrentDebt);
      } catch (Exception $e) {
      echo $e;
      //header("location:?do=error");
      }
      } */
} elseif ($do == "details") {
    //authintcation
    include_once("../public/authentication.php");

    try {
        //all supllier
        $allSupplier = $supplierDAO->queryAll();
        $smarty->assign("allSupplier", $allSupplier);

        //All Bank
        $bank = $bankADO->queryAll();
        $smarty->assign("bank", $bank);

        $savebefor = getSaveValueBefore();
        $all = $saveDAO->queryAll();
        $smarty->assign("savebefor", $savebefor);

        //DatedChecked id
        $id = $_GET['id'];
        $row = $datedCheckedDAO->load($id);


        $accountMovement = $accountMovementExt->loadMovement('datedCheckedController.php', $id);
        $smarty->assign('accountMovement', $accountMovement);

        if ($row->addType == 1) {
            //Client Id
            $id1 = $row->clientNum;
            $allClient = $clientDAO->load($id1);
            $clName = $allClient->clientname;
        } else {
            $supID = $row->clientNum;
            $allSup = $supplierDAO->load($supID);
            $clName = $allSup->suppliername;
        }
        $smarty->assign("clName", $clName);

        //savedailymodelid
        $idPost = $row->datedCheckedID;
        $smarty->assign("idPost", $idPost);
        $smarty->assign("row", $row);


        //BankAccount Id
        $accountid = $bankAccount->accountid;
        $smarty->assign("accountid", $accountid);


        $smarty->display("datedCheckedView/details.html");

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

// checkCancled
else if ($do == 'checkCancledForClient') {
    $id = $_GET['id'];
    $smarty->assign("id", $id);

    //checkCancledForClient();


    $smarty->display("datedCheckedView/checkCancled.html");
} else if ($do == 'addcheckCancledForClient') {



    $id = $_POST['id'];
    $resonForRefused = $_POST['resonForRefused'];

    $datedCheckedEX->updatReson($id, $resonForRefused);
    checkCancledForClient();

    header("location:?do=showClient");
}



//add reson
else if ($do == 'addReson') {
    try {


        $id = $_POST['id'];
        $resonForRefused = $_POST['resonForRefused'];

        $datedCheckedEX->updatReson($id, $resonForRefused);

        // print_r($obj);


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

/* ------------------------------For supplier --------------------------------------- */
//add supplier
/*
  elseif ($do == "addSup") {
  //authintcation
  include_once("../public/authentication.php");

  try {
  add();
  reduceSupplierDept();
  header("location:?do=show");
  } catch (Exception $e) {
  echo $e;
  //header("location:?do=error");
  }
  }
 */

//showSupllier
elseif ($do == "showSupllier") {

    //authintcation
    include_once("../public/authentication.php");

    try {

        $bank = $bankADO->queryAll();
        $smarty->assign("bank", $bank);


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


        $allSupplier = $supplierDAO->queryAll();
        $smarty->assign("allSupplier", $allSupplier);


        // $row = $datedCheckedEX->queryAllWitSupplier();
        // $smarty->assign("row", $row);
        // $notPayVal = 0;
        // foreach ($row as $val) {
        //     if ($val->done == 0) {
        //         $notPayVal += $val->checkValue;
        //     }
        // }
        // $smarty->assign("notPayVal", $notPayVal);
        // $getsuppliercurrentDebt = $supplierEX->querysuppliercurrentDebt(6);
        // $dept = $getsuppliercurrentDebt[0]->suppliercurrentDebt;
        $smarty->display("datedCheckedView/showSupplier.html");
        //header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        //header("location:?do=error");
    }
}


//payCheck For supplier
elseif ($do == "payCheckForSup") {
    //authintcation
    include_once("../public/authentication.php");

    try {
        //all supllier
        $allSupplier = $supplierDAO->queryAll();
        $smarty->assign("allSupplier", $allSupplier);

        //bank
        $bank = $bankADO->queryAll();
        $smarty->assign("bank", $bank);

        $savebefor = getSaveValueBefore();
        $allSave = $saveDAO->queryByConditions(0);
        $smarty->assign("savebefor", $savebefor);
        $smarty->assign("allSave", $allSave);

        //DatedChecked id
        $id = $_GET['id'];
        $clientid = $_GET['clientid'];
        $smarty->assign("clientid", $clientid);
        $row = $datedCheckedDAO->load($id);


        $supID = $row->clientNum;

        if ($clientid) {
            $allSup = $clientDAO->load($supID);
            $supName = $allSup->clientname;
        } else {
            $allSup = $supplierDAO->load($supID);
            $supName = $allSup->suppliername;
        }

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


        //savedailymodelid
        $idPost = $row->datedCheckedID;
        $smarty->assign("idPost", $idPost);
        $smarty->assign("row", $row);


        //BankAccount Id
        $accountid = $bankAccount->accountid;
        $smarty->assign("accountid", $accountid);

        $smarty->display("datedCheckedView/payCheckSupplier.html");
        //   header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        header("location:?do=error");
    }
}


//payment for supplier
elseif ($do == "paymentSupplier") {
    $paytype = $_POST["paytype"];
    $clientid = $_GET["clientid"];
    // اضافه قيمه الشيك الى الخزينه
    if ($paytype == "0") {

        //Transaction
        $mytransactions = new Transaction();
        try {
            //insert in save table & Save daily Table
            $saveid = (int) $_POST["ddlsave"]; //$_SESSION['saveid'];
            if ($saveid > 0) {
                reduceSave();
                //reduceSupplierDept();
                done();
            }

            $mytransactions->commit();

            if ($clientid) {
                header("location:?do=showClient");
            } else {
                header("location:?do=showSupllier");
            }
        } catch (Exception $e) {
            echo $e;
            $mytransactions->rollback();
            //header("location:?do=error");
        }
    }

    // اضافه قيمه الشيك الى البنك
    elseif ($paytype == "1") {

        //Transaction
        $mytransactions = new Transaction();
        try {
            // supplierDebtChange();
            // reduceSupplierDept();
            reduceBankDeposit();
            done();

            $mytransactions->commit();
            if ($clientid) {
                header("location:?do=showClient");
            } else {
                header("location:?do=showSupllier");
            }
        } catch (Exception $e) {
            echo $e;
            $mytransactions->rollback();
            //header("location:?do=error");
        }
    }

    // اضافه قيمه الشيك الى مورد
    /*  if ($paytype == "2") {
      try {
      $supID = $_POST['supName'];
      print_r("supID = " . $supID);

      $id = $_POST['suplierID'];
      $row1 = $supplierDAO->load($id);
      $suppliercurrentDebt = $row1->suppliercurrentDebt;
      $smarty->assign("suppliercurrentDebt", $suppliercurrentDebt);
      print_r("suppliercurrentDebt" . $suppliercurrentDebt);
      } catch (Exception $e) {
      echo $e;
      //header("location:?do=error");
      }
      } */
}

// checkCancled For supplier
else if ($do == 'checkCancledForSupplier') {

    $id = $_GET['id'];
    $smarty->assign("id", $id);
    $smarty->display("datedCheckedView/checkCancledForSup.html");
} else if ($do == 'addcheckCancledForSupplier') {
    $id = $_POST['id'];
    $resonForRefused = $_POST['resonForRefused'];

    $datedCheckedEX->updatReson($id, $resonForRefused);
    checkCancelSup();

    header("location:?do=showSupllier");
}


//add reson for supplier
else if ($do == 'addResonForSup') {
    try {


        $id = $_POST['id'];
        $resonForRefused = $_POST['resonForRefused'];

        $datedCheckedEX->updatReson($id, $resonForRefused);

        // print_r($obj);


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

    $allData = $datedCheckedEX->queryAllChecked();
    $smarty->assign("allData", $allData);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //here the smarty templates
    $smarty->display("datedCheckedView/show.html");
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("datedCheckedView/showClient.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//Endorsement of a check "تظهير شيك"
elseif ($do == "endorse") {
    $id = $_GET["id"];

    $showData = $datedCheckedEX->load($id);
    $smarty->assign("showData", $showData);

    if ($showData->addType == "0") {//cheque for client get client data && endorse to supplier
        $allSupplierdata = $supplierDAO->queryAll();
        $smarty->assign("allSupplierdata", $allSupplierdata);
        //
        $client = $clientDAO->load($showData->clientNum);
        $showData->clientname = $client->clientname;
    } elseif ($showData->addType == "1") {//cheque for supplier get supplier data && endorse to client
        $clientData = $clientDAO->queryAll();
        $smarty->assign("clientData", $clientData);
        //
        $supplier = $supplierDAO->load($showData->clientNum);
        $showData->suppliername = $supplier->suppliername;
    }

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

    // add old asset
    $smarty->display("datedCheckedView/endorse.html");
} elseif ($do == "addEndorse") {
    try {
        //here the function that do the action
        addEndorse();
        header("location:?do=showClient");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}

//here the global templates
$smarty->assign("customDatedChecked", 1);
$smarty->assign("customSupplier", 1);
$smarty->display("footer.html");

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

//add
function add() {
    global $datedChecked;
    global $datedCheckedDAO;
    global $datedCheckedEX;


    global $myBankRecord;

    global $client;
    global $clientDAO;
    global $clientEX;

    global $clientDebtChange;
    global $clientDebtChangeADO;
    global $clientDebtChangeEX;

    global $supplierDept;
    global $supplierDeptDAO;
    global $supplierDeptEX;

    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;


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


        //clientNum = client id
        $clientNum = $_POST['clientNum'];
        $bankName = $_POST['bankName'];
        $accountNo = $_POST['accountNo'];
        $checkValue = $_POST['checkValue'];
        $checkNo = $_POST['checkNo'];
        $dueDate = $_POST['dueDate'];
        $antherDetailes = $_POST['antherDetailes'];
        $paytype = $_POST["paytype"];
        $paperType = $_POST["paperType"];
        $bankid = $_POST["ddlBank"];
        $accountid = $_POST["accountid"];
        //# date by tarek .
        $checkdate = $_POST["checkdate"];

        // print_r("checkValue = " . $checkValue . "</br>");
        if ($bankid > 0) {
            $bank = $myBankRecord->load($bankid);
            $bankName = $bank->bankname;
        }



        $datedChecked->clientNum = $clientNum;
        $datedChecked->bankName = $bankName;
        $datedChecked->accountNo = $accountNo;
        $datedChecked->checkValue = $checkValue;
        $datedChecked->checkNo = $checkNo;
        $datedChecked->dueDate = $dueDate;
        $datedChecked->antherDetailes = $antherDetailes;
        $datedChecked->done = 0;
        $datedChecked->addType = $paytype;
        $datedChecked->resonForRefused = "";
        $datedChecked->paperType = $paperType;
        $datedChecked->bankid = $bankid;
        $datedChecked->accountid = $accountid;

        $datedChecked->userID = $_SESSION['userid'];
        $datedChecked->operationDate = date("Y-m-d");
        $datedChecked->dailyentryid = 0;
        $datedChecked->checkdate = $checkdate;

        $Checkedid = $datedCheckedDAO->insert($datedChecked);




        /* $clientNum = $_POST['clientNum'];
          $clientAmount = $_POST['checkValue']; */
        /* Start Clients */
        if ($paytype == 0) {
            $clientData = $clientDAO->load($clientNum);
            $clientdebtBefor = $clientData->clientdebt;


            $clientdate = $clientData->clientdate;
            $userid = $clientData->userid;
            if ($paperType == 1) {
                $clientDept = $clientdebtBefor + $checkValue;
            } else {
                $clientDept = $clientdebtBefor - $checkValue;
            }

            $clientEX->updatedept1($clientNum, $clientDept);


            if ($paperType == 1) {
                $clientDebtChange->processname = '  دفع شيك  لعميل';
                $clientDebtChange->clientdebtchangetype = 0;
            } else {
                $clientDebtChange->processname = 'شيك مؤقت لعميل';
                $clientDebtChange->clientdebtchangetype = 1;
            }

            $clientDebtChange->clientid = $clientNum;
            $clientDebtChange->clientdebtchangebefore = $clientdebtBefor;
            $clientDebtChange->clientdebtchangeamount = $checkValue;
            $clientDebtChange->clientdebtchangemodelid = $Checkedid;
            $clientDebtChange->clientdebtchangeafter = $clientDept;
            $clientDebtChange->tablename = 'datedCheckedController.php';
            $clientDebtChange->comment = $comment;
            $clientDebtChange->totalOperationCost = $checkValue;
            $clientDebtChange->clientdebtchangedate = date("Y-m-d H:i:s");
            $clientDebtChange->userid = $_SESSION['userid'];
            $clientDebtChange->dailyentryid = 0;
            $clientDebtChangeADO->insert($clientDebtChange);

            if ($paperType == 1) {
                $dailyEntry->entryComment = 'دفع  شيك  للعميل  ' . $clientData->clientname;
            } else {
                $dailyEntry->entryComment = 'تم اضافة شيك  للعميل  ' . $clientData->clientname;
            }




            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $checkValue;
            //     $checkId = addTreeElement($checkNo, 31, 3, 0, 1, '', 0, 0);

            if ($paperType == 1) {
                $dailyEntryDebtor->accountstreeid = 90;
            } else {
                $dailyEntryDebtor->accountstreeid = 43;
            }


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

            $clientTreeId = $clientData->treeId;
            $dailyEntryCreditor->accountstreeid = $clientTreeId;

            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            if ($paperType == 1) {
                $returnedData = insertEntery($dailyEntry, $dailyEntryCreditorArray, $dailyEntryDebtorArray, 1);
            } else {
                $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            }
            $did = $returnedData[1];

            $rowData = $datedCheckedDAO->load($Checkedid);

            $datedChecked->clientNum = $rowData->clientNum;
            $datedChecked->bankName = $rowData->bankName;
            $datedChecked->accountNo = $rowData->accountNo;
            $datedChecked->checkValue = $rowData->checkValue;
            $datedChecked->checkNo = $rowData->checkNo;
            $datedChecked->dueDate = $rowData->dueDate;
            $datedChecked->antherDetailes = $rowData->antherDetailes;
            $datedChecked->done = $rowData->done;
            $datedChecked->addType = $rowData->addType;
            $datedChecked->resonForRefused = $rowData->resonForRefused;
            $datedChecked->addType = $paytype;
            $datedChecked->bankid = $bankid;
            $datedChecked->accountid = $accountid;
            $datedChecked->paperType = $paperType;
            $datedChecked->userID = $rowData->userID;
            $datedChecked->operationDate = $rowData->operationDate;
            $datedChecked->dailyentryid = $did;
            $datedCheckedDAO->update($datedChecked);






            $mytransactions->commit();
            return 0;
        }
        /* End Clients */ elseif ($paytype == 1) {


            $supplierdata = $supplierDAO->load($clientNum);
            $supplierdebtBefor = $supplierdata->suppliercurrentDebt;

            if ($paperType == 1) {
                $suppliercurrentdept = $supplierdebtBefor + $checkValue;
            } else {
                $suppliercurrentdept = $supplierdebtBefor - $checkValue;
            }

            //print_r('suppliercurrentdept'.$suppliercurrentdept);
            $supplierEX->updateSuppDept($clientNum, $suppliercurrentdept);


            if ($paperType == 1) {
                $supplierDept->processname = '   دفع شيك مؤقت لمورد';
                $supplierDept->supplierdebtchangetype = 0;
            } else {
                $supplierDept->processname = 'شيك مؤقت لمورد';
                $supplierDept->supplierdebtchangetype = 1;
            }


            $supplierDept->comment = "اضافه شيك مؤجل";
            $supplierDept->supplierdebtchangeafter = $suppliercurrentdept;
            $supplierDept->supplierdebtchangeamount = $checkValue;
            $supplierDept->supplierdebtchangebefore = $supplierdebtBefor;
            $supplierDept->supplierdebtchangedate = date("Y-m-d H:i:s");
            $supplierDept->supplierdebtchangemodelid = $Checkedid;
            $supplierDept->tablename = "datedCheckedController.php";
            $supplierDept->userid = $_SESSION['userid'];
            $supplierDept->supplierid = $clientNum;
            $supplierDept->dailyentryid = 0;

            //Insert
            $supplierDeptChangeId = $supplierDeptDAO->insert($supplierDept);

            if ($paperType == 1) {
                $dailyEntry->entryComment = 'دفع  شيك  للمورد ' . $supplierdata->suppliername;
            } else {
                $dailyEntry->entryComment = 'تم اضافة شيك مؤجل للمورد ' . $supplierdata->suppliername;
            }



//// من حساب الدائنون ( اسم المورد )

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

            $supplierTreeId = $supplierdata->treeId;
            $dailyEntryDebtor->accountstreeid = $supplierTreeId;

//// End
//// الى حساب اوراق الدقع


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

            //   $checkId = addTreeElement($checkNo, 33, 1, 0, 1, '', 0, 0);

            if ($paperType == 1) {
                $dailyEntryCreditor->accountstreeid = 43;
            } else {
                $dailyEntryCreditor->accountstreeid = 90;
            }


//// End

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

            if ($paperType == 1) {
                $returnedData = insertEntery($dailyEntry, $dailyEntryCreditorArray, $dailyEntryDebtorArray, 1);
            } else {
                $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            }
            $did = $returnedData[1];

            $rowData = $datedCheckedDAO->load($Checkedid);

            $datedChecked->clientNum = $rowData->clientNum;
            $datedChecked->bankName = $rowData->bankName;
            $datedChecked->accountNo = $rowData->accountNo;
            $datedChecked->checkValue = $rowData->checkValue;
            $datedChecked->checkNo = $rowData->checkNo;
            $datedChecked->dueDate = $rowData->dueDate;
            $datedChecked->antherDetailes = $rowData->antherDetailes;
            $datedChecked->done = $rowData->done;
            $datedChecked->addType = $rowData->addType;
            $datedChecked->resonForRefused = $rowData->resonForRefused;
            $datedChecked->addType = $paytype;
            $datedChecked->bankid = $bankid;
            $datedChecked->accountid = $accountid;
            $datedChecked->userID = $rowData->userID;
            $datedChecked->operationDate = $rowData->operationDate;
            $datedChecked->dailyentryid = $did;
            $datedChecked->paperType = $paperType;


            $datedCheckedDAO->update($datedChecked);




            $mytransactions->commit();

            return 1;
        }


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

//done
function done() {
    global $datedChecked;
    global $datedCheckedDAO;
    global $datedCheckedEX;

    $id = $_POST['id'];
    $datedCheckedEX->updateDone($id);
}

/* ------------------------------ for Save ------------------------------------- */

//getSaveValueBefore
function getSaveValueBefore() {

    global $save;
    global $saveDAO;

    $saveData = $saveDAO->load($_SESSION['saveid']);
    $saveValuebefore = $saveData->savecurrentvalue;
    //print_r($saveValuebefore);
    return $saveValuebefore;
}

// insert in save table  and save daily
function insertSaveAndSaveDaily() {
    global $save;
    global $saveDAO;

    global $saveDaily;
    global $saveDailyADO;

    global $datedChecked;
    global $datedCheckedDAO;
    global $datedCheckedEX;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

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

    global $myBank;
    global $myBankRecord;

    global $accountsTreeDAO;
    global $accountsTree;

    $saveid = (int) $_POST["ddlsave"]; //$_SESSION['saveid'];
    if ($saveid > 0) {
        $supplierid = $_POST["supplierid"];
        $accountid = $_POST["accountid"];
        $paytype = $_POST["paytype"];
        $save->saveid = $saveid;

        $row = $saveDAO->load($saveid);
        $saveName1 = $row->savename;
        $save->savename = $saveName1;

        //befor
        $savecurrentvalue1 = $row->savecurrentvalue;
        //print_r("savecurrentvalue1 = ".$savecurrentvalue1."</br>");
        //amount
        $id = $_POST['id'];
        $rowdatedChecked = $datedCheckedDAO->load($id);
        $newQt = $rowdatedChecked->checkValue;
        //print_r("newQt = ".$newQt."</br>");
        //after

        $newsavecurrentvalue = $savecurrentvalue1 + $newQt;
        $saveDaily->savedailychangetype = 0;
        $saveDaily->processname = "  اضافه قيمه شيك ";


        //insert in save details
        $saveDaily->savedailydate = date("Y-m-d H:i:s");
        $saveDaily->userid = $_SESSION['userid'];

        $saveDaily->savedailysavebefore = $savecurrentvalue1;
        $saveDaily->savedailychangeamount = $newQt;
        $saveDaily->saveid = $saveid;
        $saveDaily->savedailymodelid = $id;
        $saveDaily->savedailysaveafter = $newsavecurrentvalue;
        $saveDaily->tablename = "datedCheckedController.php";
        $saveDailyADO->insert($saveDaily);


        //update save
        $row->savecurrentvalue = $newsavecurrentvalue;
        $savedetails1 = $save->savedetails;
        $row->savedate = date('Y-m-d');
        $row->userid = $_SESSION['userid'];

        //   print_r("newsavecurrentvalue = " . $newsavecurrentvalue . "</br>");
        //   print_r($saveDaily);


        $saveDAO->update($row, $savedetails1);

        //// الخزنة

        $dailyEntry->entryComment = 'تسديد شيك ';

/// الخزنة
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $newQt;

        $idTreeSave = $row->treeId;
        $dailyEntryDebtor->accountstreeid = $idTreeSave;


/// اوراق القبض

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

        $dailyEntryCreditor->accountstreeid = 43;


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

        insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
    }
}

function reduceSave() {
    global $save;
    global $saveDAO;

    global $saveDaily;
    global $saveDailyADO;

    global $datedChecked;
    global $datedCheckedDAO;
    global $datedCheckedEX;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $accountsTreeDAO;
    global $accountsTree;
    $saveid = (int) $_POST["ddlsave"]; //$_SESSION['saveid'];
    $clientid = $_POST["clientid"];
    if ($saveid > 0) {


        $save->saveid = $saveid;

        $row = $saveDAO->load($saveid);
        $saveName1 = $row->savename;
        $save->savename = $saveName1;

        //befor
        $savecurrentvalue1 = $row->savecurrentvalue;
        // print_r("savecurrentvalue1 = " . $savecurrentvalue1 . "</br>");
        //amount
        $id = $_POST['id'];
        $rowdatedChecked = $datedCheckedDAO->load($id);
        $newQt = $rowdatedChecked->checkValue;
        // print_r("newQt = " . $newQt . "</br>");
        //after
        // if ($clientid) {
        //     $newsavecurrentvalue = $savecurrentvalue1 + $newQt;
        //     $saveDaily->processname = "  اضافه قيمه شيك ";
        //     $saveDaily->savedailychangetype = 0;
        // }else{
        $newsavecurrentvalue = $savecurrentvalue1 - $newQt;
        $saveDaily->processname = "  خصم قيمه شيك ";
        $saveDaily->savedailychangetype = 1;

        // }
        //insert in save details
        $saveDaily->savedailydate = date("Y-m-d H:i:s");
        $saveDaily->userid = $_SESSION['userid'];

        $saveDaily->savedailysavebefore = $savecurrentvalue1;
        $saveDaily->savedailychangeamount = $newQt;

        $saveDaily->saveid = $saveid;

        $saveDaily->savedailymodelid = $id;
        $saveDaily->savedailysaveafter = $newsavecurrentvalue;
        $saveDaily->tablename = "datedCheckedController.php";

        $saveDailyADO->insert($saveDaily);


        //update save
        $row->savecurrentvalue = $newsavecurrentvalue;
        $savedetails1 = $save->savedetails;
        $row->savedate = date('Y-m-d');
        $row->userid = $_SESSION['userid'];

        // print_r("newsavecurrentvalue = " . $newsavecurrentvalue . "</br>");
        //print_r($saveDaily);


        $saveDAO->update($row, $savedetails1);
        if ($clientid) {
            $dailyEntry->entryComment = 'تسديد  اوراق دفع ';
            ;
        } else {
            $dailyEntry->entryComment = 'تسديد شيك ';
        }


/// /ن حساب اوراق الدفع
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $newQt;
        $dailyEntryDebtor->accountstreeid = 90;



///  الخزنة

        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $newQt;
        $idTreeSave = $row->treeId;
        $dailyEntryCreditor->accountstreeid = $idTreeSave;

        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        // if ($clientid) {
        //     insertEntery($dailyEntry, $dailyEntryCreditorArray, $dailyEntryDebtorArray, 1);
        // }else{
        insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        // }
    }
}

/* ------------------------------ for Banke ------------------------------------- */

//insert in check deposit	Table and Bank Account
function addInBankDeposit() {
    global $checkDeposit;
    global $checkDepositADO;
    global $CheckdepositEX;

    global $bankAccount;
    global $bankAccountADO;
    global $bankAccountEx;

    global $datedChecked;
    global $datedCheckedDAO;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $accountsTreeDAO;
    global $accountsTree;

    global $accountMove;
    global $accountMoveDAO;
    global $accountDAO;
    global $accountExtDAO;
    /* -------------------------------insert in checkDeposit------------------------------------- */
    $supplierid = $_POST['supplierid'];
    $bankaccountid = $_POST['ddlBank'];
    $clientid = $_POST['clientNum'];
    $checkdepositnumber = $_POST['checkdepositnumber'];
    $checkdeposituser = $_POST['txtUser'];
    $checkdepositamount = $_POST['txtAmount'];
    $accountbeforevalue = $_POST['accountbeginingbalance'];
    $checkdepositnote = $_POST['textNote'];
    $accountid1 = $_POST['accountid1'];


    $checkDeposit->userid = $_SESSION['userid'];
    $checkDeposit->checkdepositdate = date("Y-m-d");
    $checkDeposit->conditions = 0;
    $checkDeposit->bankaccountid = $bankaccountid;
    $checkDeposit->clientid = $clientid;
    $checkDeposit->checkdepositnumber = $checkdepositnumber;
    $checkDeposit->checkdeposituser = $checkdeposituser;
    $checkDeposit->checkdepositamount = $checkdepositamount;
    $checkDeposit->accountbeforevalue = $accountbeforevalue;
    $checkDeposit->checkdepositnote = $checkdepositnote;
    $checkDeposit->dailyentryid = 0;


    $checkDepositADO->insert($checkDeposit, $checkdepositnote);


    /* ------------------------ update accountbeginingbalance in bankaccount----------------------------------------- */
    $ddlAccount = $_POST['accountid1'];

    $amountBefor = $_POST['accountbeginingbalance'];

    $newAmount = $amountBefor + $checkdepositamount;


    //line below is hased as it is repeated
    //$bankAccountEx->updateAccountbeginingbalance1($newAmount, $ddlAccount, $bankaccountid);

    $id = $_POST['id'];
    $rowdatedChecked = $datedCheckedDAO->load($id);


    $dailyEntry->entryComment = 'تسديد شيك ';




/// البنك
    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $checkdepositamount;
    $bankData = $bankAccountADO->load($accountid1);

    $idTreeSave = $bankData->treeId;
    $dailyEntryDebtor->accountstreeid = $idTreeSave;

/// اوراق القبض

    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $checkdepositamount;
    $dailyEntryCreditor->accountstreeid = 43;

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

    insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);





    /////////// insert into account movement////////////////////


    if ($id != null) {
        //update bank account balance
        $accoundatat = $accountDAO->load($accountid1);
        $accountBefore = $accoundatat->accountbeginingbalance;
        if ($supplierid) {
            $account->accountbeginingbalance = $accountBefore - $checkdepositamount;
            $accountmovementafter = $accountBefore - $checkdepositamount;
        } else {
            $account->accountbeginingbalance = $accountBefore + $checkdepositamount;
            $accountmovementafter = $accountBefore + $checkdepositamount;
        }



        $account->accountdate = date("Y-m-d");
        $account->accountid = $accountid1;

        //update
        $accountExtDAO->updateacount($account);
        if ($supplierid) {
            $accountMove->processname = 'دفع شيك  لمورد';
        } else {

            $accountMove->processname = 'تسديد شيك لعميل';
        }

        //Insert in accountmovement table
        $accountMove->accountmovementtype = 0;
        $accountMove->accountmovementbefore = $accountBefore;
        $accountMove->accountid = $accountid1;
        $accountMove->bankid = $bankaccountid;
        $accountMove->accountmovementamount = $checkdepositamount;
        $accountMove->accountmovementafter = $accountmovementafter;

        $accountMove->tablename = "datedCheckedController.php";
        $accountMove->accountmovementmodelid = $id;
        $accountMove->accountmovementdate = date("Y-m-d");
        $accountMove->userid = $_SESSION['userid'];

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

function reduceBankDeposit() {
    global $checkDeposit;
    global $checkDepositADO;
    global $CheckdepositEX;

    global $bankAccount;
    global $bankAccountADO;
    global $bankAccountEx;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $accountsTreeDAO;
    global $accountsTree;

    global $datedChecked;
    global $datedCheckedDAO;

    global $accountMove;
    global $accountMoveDAO;
    global $accountDAO;
    global $accountExtDAO;
    /* -------------------------------insert in checkDeposit------------------------------------- */
    $clientids = $_POST['clientid'];
    $bankaccountid = $_POST['ddlBank'];
    $clientid = $_POST['clientNum'];
    $checkdepositnumber = $_POST['checkdepositnumber'];
    $checkdeposituser = $_POST['txtUser'];
    $checkdepositamount = $_POST['txtAmount'];
    $accountbeforevalue = $_POST['accountbeginingbalance'];
    $checkdepositnote = $_POST['textNote'];
    $accountid1 = $_POST['accountid1'];



    $checkDeposit->userid = $_SESSION['userid'];
    $checkDeposit->checkdepositdate = date("Y-m-d");
    $checkDeposit->conditions = 0;


    $checkDeposit->bankaccountid = $bankaccountid;
    $checkDeposit->clientid = $clientid;
    $checkDeposit->checkdepositnumber = $checkdepositnumber;
    $checkDeposit->checkdeposituser = $checkdeposituser;
    $checkDeposit->checkdepositamount = $checkdepositamount;
    $checkDeposit->accountbeforevalue = $accountbeforevalue;
    $checkDeposit->checkdepositnote = $checkdepositnote;
    $checkDeposit->dailyentryid = 0;


    $checkDepositADO->insert($checkDeposit, $checkdepositnote);

    $id = $_POST['id'];
    $rowdatedChecked = $datedCheckedDAO->load($id);
    $newQt = $rowdatedChecked->checkValue;
    /* ------------------------ update accountbeginingbalance in bankaccount----------------------------------------- */
    $ddlAccount = $_POST['accountid1'];

    $amountBefor = $_POST['accountbeginingbalance'];

    $newAmount = $amountBefor - $checkdepositamount;
    $dailyEntry->entryComment = 'تسديد شيك ';


    //the line below is hased as it is repeated
    //$bankAccountEx->updateAccountbeginingbalance1($newAmount, $ddlAccount, $bankaccountid);
    //print_r($newAmount);
//// من حساب اوراق الدفع
    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $newQt;



    $dailyEntryDebtor->accountstreeid = 90;



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

    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $checkdepositamount;
    $bankData = $bankAccountADO->load($accountid1);
    $idTreeBank = $bankData->treeId;
    $dailyEntryCreditor->accountstreeid = $idTreeBank;

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


    insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);




    if ($id != null) {
        //update bank account balance
        $accoundatat = $accountDAO->load($accountid1);
        $accountBefore = $accoundatat->accountbeginingbalance;
        if ($clientids) {
            $account->accountbeginingbalance = $accountBefore + $checkdepositamount;
            $accountmovementafter = $accountBefore + $checkdepositamount;
        } else {
            $account->accountbeginingbalance = $accountBefore - $checkdepositamount;
            $accountmovementafter = $accountBefore - $checkdepositamount;
        }


        $account->accountdate = date("Y-m-d");
        $account->accountid = $accountid1;

        //update
        $accountExtDAO->updateacount($account);
        if ($clientids) {
            $accountMove->processname = ' تسديد ورقه دفع لعميل';
        } else {

            $accountMove->processname = 'تسديد شيك مورد';
        }

        //Insert in accountmovement table
        $accountMove->accountmovementbefore = $accountBefore;
        $accountMove->accountmovementtype = 1;
        $accountMove->accountid = $accountid1;
        $accountMove->bankid = $bankaccountid;
        $accountMove->accountmovementamount = $checkdepositamount;
        $accountMove->accountmovementafter = $accountmovementafter;

        $accountMove->tablename = "datedCheckedController.php";
        $accountMove->accountmovementmodelid = $id;
        $accountMove->accountmovementdate = date("Y-m-d");
        $accountMove->userid = $_SESSION['userid'];

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

/* ------------------------------ for Client------------------------------------- */

//reduse the client dept
function reduceDept() {
    global $client;
    global $clientDAO;
    global $clientEX;


    $clientNum = $_POST['clientNum'];
    $clientData = $clientDAO->load($clientNum);

    $clientdebtBefor = $clientData->clientdebt;



    $clientdate = $clientData->clientdate;
    $userid = $clientData->userid;

    $clientAmount = $_POST['checkValue'];


    $clientDept = $clientdebtBefor - $clientAmount;



    $clientEX->updatedept1($clientNum, $clientDept);
}

//checkCancled
function checkCancledForClient() {
    global $client;
    global $clientDAO;
    global $clientEX;

    global $datedChecked;
    global $datedCheckedDAO;
    global $datedCheckedEX;


    global $clientDebtChange;
    global $clientDebtChangeADO;

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

//print_r('55555555555555555555555');
        $id = $_POST['id'];
        $paper = $_POST['paper'];
        $row = $datedCheckedDAO->load($id);
        //print_r($row);

        $clientNum = $row->clientNum;
        $clientData = $clientDAO->load($clientNum);

        $clientdebtBefor = $clientData->clientdebt;
        //print_r("clientdebtBefor = ".$clientdebtBefor);
        // print_r($row->dailyentryid);

        $clientdate = $clientData->clientdate;
        $userid = $clientData->userid;

        $clientAmount = $row->checkValue;
        // print_r("checkValue = ".$clientAmount);
        if ($paper) {
            $clientDept = $clientdebtBefor - $clientAmount;
            $pprocessname = 'الغاء شيك مؤقت';
            $pclientdebtchangetype = 1;
        } else {
            $clientDept = $clientdebtBefor + $clientAmount;
            $pprocessname = 'الغاء شيك مؤقت';
            $pclientdebtchangetype = 0;
        }




        // print_r("clientDept = ".$clientDept);

        $clientEX->updatedept1($clientNum, $clientDept);


        $clientDebtChange->clientid = $clientNum;
        $clientDebtChange->clientdebtchangebefore = $clientdebtBefor;
        $clientDebtChange->clientdebtchangeamount = $clientAmount;
        $clientDebtChange->clientdebtchangetype = $pclientdebtchangetype;
        $clientDebtChange->processname = $pprocessname;
        $clientDebtChange->clientdebtchangemodelid = $id;
        $clientDebtChange->clientdebtchangeafter = $clientDept;
        $clientDebtChange->tablename = 'datedCheckedController.php';
        $clientDebtChange->comment = $comment;
        $clientDebtChange->totalOperationCost = $checkValue;

        $clientDebtChange->clientdebtchangedate = date("Y-m-d H:i:s");
        $clientDebtChange->userid = $_SESSION['userid'];
        $clientDebtChange->dailyentryid = 0;

        $clientDebtChangeADO->insert($clientDebtChange);

        reverseEntryWithItsID($row->dailyentryid, 1);

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

//insert in clientDebtChange
function insertInClientDebtChange() {
    //clientDebtChange
    global $clientDebtChange;
    global $clientDebtChangeADO;
    global $clientDebtChangeEX;

    //client
    global $clientDAO;

    //bank
    global $bankADO;

    //datedchecked
    global $datedCheckedDAO;


    $id = $_GET['id'];
    $row = $datedCheckedDAO->load($id);

    $clientNum = $row->clientNum;
    $clientData = $clientDAO->load($clientNum);

    //$clientNum = $_POST['clientNum'];
    //get clientdebt
    $getClient = $clientDAO->load($clientNum);
    $clientdebt = $getClient->clientdebt;

    $clientdebtchangebefore = $clientdebt;
    $clientdebtchangeamount = $_POST['checkValue'];
    $clientdebtchangetype = 1;  //0 for mins
    $processname = " خصم قيمه الشيك من حساب العميل ";
    $clientdebtchangemodelid = 10;  //$client->clientid;
    $clientdebtchangeafter = $clientdebtchangebefore - $clientdebtchangeamount;
    $tablename = "datedCheckedController.php";
    $comment = "comment";
    $totalOperationCost = 0;


    $clientDebtChange->clientid = $clientNum;
    $clientDebtChange->clientdebtchangebefore = $clientdebtchangebefore;
    $clientDebtChange->clientdebtchangeamount = $clientdebtchangeamount;
    $clientDebtChange->clientdebtchangetype = $clientdebtchangetype;
    $clientDebtChange->processname = $processname;
    $clientDebtChange->clientdebtchangemodelid = $clientdebtchangemodelid;
    $clientDebtChange->clientdebtchangeafter = $clientdebtchangeafter;
    $clientDebtChange->tablename = $tablename;
    $clientDebtChange->comment = $comment;
    $clientDebtChange->totalOperationCost = $totalOperationCost;

    $clientDebtChange->clientdebtchangedate = date("Y-m-d H:i:s");
    $clientDebtChange->userid = $_SESSION['userid'];

    $clientDebtChangeADO->insert($clientDebtChange);
}

/* ------------------------------ for Supplier------------------------------------- */

function reduceSupplierDept() {
    global $supplier;
    global $supplierDAO;
    global $supplierEX;


    $clientNum = $_POST['clientNum'];
    $supllierData = $supplierDAO->load($clientNum);

    $supDebtBefor = $supllierData->suppliercurrentDebt;

    $checkAmount = $_POST['checkValue'];

    $supDept = $supDebtBefor - $checkAmount;

    //print_r("clientDept = ".$supDept);

    $supplierEX->updateSuppDept($clientNum, $supDept);
}

//insert in supplierDebtChange
function supplierDebtChange() {
    //supplierDebtChange
    global $supplierDept;
    global $supplierDeptDAO;
    global $supplierDeptEX;



    //supplier
    global $supplierDAO;

    //bank
    global $bankADO;

    //datedchecked
    global $datedCheckedDAO;


    $id = $_POST['clientNum'];
    $row = $datedCheckedDAO->load($id);

    //$supplierid = $row->clientNum;
    $supplierData = $supplierDAO->load($id);
    //print_r($supplierData);

    $supplierid = $_POST['clientNum'];

    //get supplierdebt
    //$getSupplier = $supplierDAO->load($id);
    $Supplierdebt = $supplierData->suppliercurrentDebt;

    $supplierdebtchangebefore = $Supplierdebt;
    //print_r("supplierdebtchangebefore = ".$supplierdebtchangebefore);

    $supplierdebtchangeamount = $_POST['checkValue'];
    //print_r("supplierdebtchangeamount = ".$supplierdebtchangeamount);

    $supplierdebtchangetype = 1;  //0 for mins
    $processname = " خصم قيمه الشيك من حساب العميل ";
    $supplierdebtchangemodelid = 10;  //$client->clientid;

    $supplierdebtchangeafter = $supplierdebtchangebefore - $supplierdebtchangeamount;
    //print_r("supplierdebtchangeafter = ".$supplierdebtchangeafter);

    $tablename = "datedCheckedController.php";
    $comment = "comment";
    $totalOperationCost = 0;


    $supplierDept->supplierid = $supplierid;
    $supplierDept->supplierdebtchangebefore = $supplierdebtchangebefore;
    $supplierDept->supplierdebtchangeamount = $supplierdebtchangeamount;
    $supplierDept->supplierdebtchangetype = $supplierdebtchangetype;
    $supplierDept->processname = $processname;
    $supplierDept->supplierdebtchangemodelid = $supplierdebtchangemodelid;
    $supplierDept->supplierdebtchangeafter = $supplierdebtchangeafter;
    $supplierDept->tablename = $tablename;
    $supplierDept->comment = $comment;
    $supplierDept->totalOperationCost = $totalOperationCost;
    $supplierDept->processname = $processname;

    $supplierDept->supplierdebtchangedate = date("Y-m-d H:i:s");
    $supplierDept->userid = $_SESSION['userid'];

    $supplierDeptDAO->insert($supplierDept);
}

function checkCancelSup() {
    global $supplier;
    global $supplierDAO;
    global $supplierEX;


    global $supplierDept;
    global $supplierDeptDAO;

    global $datedChecked;
    global $datedCheckedDAO;
    global $datedCheckedEX;


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

        $clientNum = $_POST['id'];
        $paper = $_POST['paper'];

        $checkData = $datedCheckedDAO->load($clientNum);
        $id = $checkData->clientNum;

        //print_r($id );

        $supplierData = $supplierDAO->load($id);


        $supDebtBefor = $supplierData->suppliercurrentDebt;
        // print_r("supDebtBefor = ".$supDebtBefor);

        $checkAmount = $checkData->checkValue;
        // print_r("checkAmount = ".$checkAmount);
        if ($paper) {
            $supDept = $supDebtBefor - $checkAmount;
            $pcomment = "الغاء شيك ";
            $psupplierdebtchangetype = 1;
        } else {
            $supDept = $supDebtBefor + $checkAmount;
            $pcomment = "الغاء شيك ";
            $psupplierdebtchangetype = 0;
        }



        //print_r("supDept = ".$supDept);

        $supplierEX->updateSuppDept($id, $supDept);

        $supplierDept->comment = $supplierDept->processname = $pcomment;
        $supplierDept->supplierdebtchangeafter = $supDept;
        $supplierDept->supplierdebtchangeamount = $checkAmount;
        $supplierDept->supplierdebtchangebefore = $supDebtBefor;
        $supplierDept->supplierdebtchangedate = date("Y-m-d H:i:s");
        ;
        $supplierDept->supplierdebtchangemodelid = $clientNum;
        $supplierDept->supplierdebtchangetype = 0;
        $supplierDept->tablename = "datedCheckedController.php";
        $supplierDept->userid = $_SESSION['userid'];
        $supplierDept->supplierid = $id;
        $supplierDept->dailyentryid = $checkData->dailyentryid;

        //Insert
        $supplierDeptChangeId = $supplierDeptDAO->insert($supplierDept);
        reverseEntryWithItsID($checkData->dailyentryid, 1);

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

function addEndorse() {
    global $supplierDeptDAO;
    global $supplierDeptEX;

    global $clientDAO;

    global $supplierDAO;
    global $supplierEX;

    global $datedCheckedDAO;
    global $datedCheckedEX;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

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

        $today = date("Y-m-d");
        $supplierid = $_POST["supplierID"];
        $suppliercomment = $_POST["suppliercomment"];
        $datedCheckedId = $_POST["id"];
        $datedCheckedData = $datedCheckedDAO->load($datedCheckedId);
        $value = $datedCheckedData->checkValue;

        $datedCheckedData->done = 3;
        $datedCheckedData->endorseDate = $today;
        $datedCheckedData->endorsePersonId = $supplierid;
        $datedCheckedDAO->update($datedCheckedData);


        $supplierData = $supplierDAO->load($supplierid);
        $clientData = $clientDAO->load($datedCheckedData->clientNum);
        if ($datedCheckedId > 0) {
            $debtBefore = $supplierData->suppliercurrentDebt;


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

            //$supplierExtDAO -> updateSupplierCurrentDebt();
            $supplierEX->updatedept($Supplier);

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

            $Supplierdebtchange->supplierdebtchangeamount = $value;
            $Supplierdebtchange->supplierdebtchangetype = 1;
            $Supplierdebtchange->tablename = "datedCheckedController.php";
            $Supplierdebtchange->supplierdebtchangemodelid = $datedCheckedId;
            $Supplierdebtchange->supplierdebtchangeafter = $debtBefore - $value;
            $Supplierdebtchange->supplierdebtchangedate = date("Y-m-d H:i:s");
            $Supplierdebtchange->userid = $_SESSION['userid'];
            $Supplierdebtchange->processname = "تظهير شيك مؤقت من عميل $clientData->clientname الى مورد $supplierData->suppliername";
            $Supplierdebtchange->dailyentryid = 0;


            //print_r($Supplierdebtchange);
            //Insert
            $supplierDeptDAO->insert($Supplierdebtchange);
            ///////////////////////////
        }
        //$dailyEntry->entryComment = 'تم تظهير شيك لمورد ( ' . $supplierData->suppliername . ' ) ';
        $dailyEntry->entryComment = "تظهير شيك مؤقت من عميل $clientData->clientname الى مورد $supplierData->suppliername";
        $dailyEntry->reverseofid = 0;


//// من حساب  مورد
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $value;
        //$clientTreeId = $clientData->treeId;
        $supplierTreeId = $supplierData->treeId;
        $dailyEntryDebtor->accountstreeid = $supplierTreeId;

//// الى شيكات
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $value;
//        $supplierTreeId = $supplierData->treeId;
        $dailyEntryCreditor->accountstreeid = 43; //$supplierTreeId;


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

        insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);

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

?>