<?php

//the global file operation
include("../public/impOpreation.php");



//global varable
global $showoutside;

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


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

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

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');

//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');

//Bill
require_once('../models/dao/BillsDAO.class.php');
require_once('../models/dto/Bill.class.php');
require_once('../models/mysql/BillsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsMySqlExtDAO.class.php');
//Billsbuy
require_once('../models/dao/BillsbuyDAO.class.php');
require_once('../models/dto/Billsbuy.class.php');
require_once('../models/mysql/BillsbuyMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsbuyMySqlExtDAO.class.php');
//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');

//Returnsellbill
require_once('../models/dao/ReturnsellbillDAO.class.php');
require_once('../models/dto/Returnsellbill.class.php');
require_once('../models/mysql/ReturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillMySqlExtDAO.class.php');

//Sellbillandrutern
require_once('../models/dao/SellbillandruternDAO.class.php');
require_once('../models/dto/Sellbillandrutern.class.php');
require_once('../models/mysql/SellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruternMySqlExtDAO.class.php');

//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');


//Buybill
require_once('../models/dao/BuybillDAO.class.php');
require_once('../models/dto/Buybill.class.php');
require_once('../models/mysql/BuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillMySqlExtDAO.class.php');

//Returnbuybill
require_once('../models/dao/ReturnbuybillDAO.class.php');
require_once('../models/dto/Returnbuybill.class.php');
require_once('../models/mysql/ReturnbuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillMySqlExtDAO.class.php');

//Buyandruternbill
require_once('../models/dao/BuyandruternbillDAO.class.php');
require_once('../models/dto/Buyandruternbill.class.php');
require_once('../models/mysql/BuyandruternbillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillMySqlExtDAO.class.php');

// EmployeepersonnelDAO
require_once('../models/dao/EmployeepersonnelDAO.class.php');
require_once('../models/dto/Employeepersonnel.class.php');
require_once('../models/mysql/EmployeepersonnelMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeepersonnelMySqlExtDAO.class.php');

require_once('../models/dao/EmployeepersonnelDAO.class.php');
require_once('../models/dto/Employeepersonnel.class.php');
require_once('../models/mysql/EmployeepersonnelMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeepersonnelMySqlExtDAO.class.php');

//Branch
require_once('../models/dao/BranchDAO.class.php');
require_once('../models/dto/Branch.class.php');
require_once('../models/mysql/BranchMySqlDAO.class.php');
require_once('../models/mysql/ext/BranchMySqlExtDAO.class.php');
//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');
//Accountmovement
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');
//Breadcrumb
require_once("../library/breadcrumb.php");



//get the do the action
$do = isset($_GET['do']) ? $_GET['do'] : '';
$lang = isset($_GET['lang']) ? $_GET['lang'] : '';

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

  Controller Name :- cashSaveFlowCTRL تقرير تدفق النقدية بالخزنة

  OPERTATION in Controller

  1-load save data
  2-display show form
  3-display details form for save
  4-display details for operation in savedaily

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


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


//here goes the instances and general variables

$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
//Income
$incomeDAO = new IncomeMySqlDAO();

$mySaveRecord = new SaveMySqlDAO();
$mySaveExt = new SaveMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//supplierDebtChange
$supplierDebtChangeExt = new SupplierdebtchangeMySqlExtDAO();
//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

//Store
$myStore = new Store();
$myStoreRecord = new StoreMySqlDAO();
$myStoreEx = new StoreMySqlExtDAO();

//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();

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

//user
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

//Breadcrumb
$breadcrumbObject = new Breadcrumb();

//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();
//bill
$billsReturn = new Billsreturn();
$billsReturnDAO = new BillsreturnMySqlDAO();
$billsReturnEX = new BillsreturnMySqlExtDAO();
//Billsbuy
$billsBuy = new Billsbuy();
$billsBuyDAO = new BillsbuyMySqlDAO();
$billsBuyEX = new BillsbuyMySqlExtDAO();

//Branch
$Branch = new Branch();
$BranchDAO = new BranchMySqlDAO();
$BranchEX = new BranchMySqlExtDAO();

//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();
//
$accountMovement = new Accountmovement();
$accountMovementDAO = new AccountmovementMySqlDAO();
$accountMovementEX = new AccountmovementMySqlExtDAO();

//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();

//Buyandruternbill
$buyAndReturnBill = new Buyandruternbill();
$buyAndReturnBillDAO = new BuyandruternbillMySqlDAO();
$buyAndReturnBillExt = new BuyandruternbillMySqlExtDAO();

//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();

$myPartnerwithdrawalEx = new PartnerwithdrawalMySqlExtDAO();
//Sellbill
$sellBillDAO = new SellbillMySqlDAO();
$sellBillExt = new SellbillMySqlExtDAO();

//Returnsellbill
$returnSellBillDAO = new ReturnsellbillMySqlDAO();
$returnSellBillExt = new ReturnsellbillMySqlExtDAO();
//Sellbillandrutern
$mySellbillandrutern = new Sellbillandrutern();
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
//$buyBillDAO->load();
$buyBillExt = new BuybillMySqlExtDAO();

$usergroupID = $_SESSION['usergroupid'];

$empDao = new EmployeeMySqlDAO();
$emp = new Employee();
$empEX = new EmployeeMySqlExtDAO();

$EmployeepersonnelDAO = new EmployeepersonnelMySqlDAO();
$Employeepersonnel = new Employeepersonnel();
$EmployeepersonnelEX = new EmployeepersonnelMySqlExtDAO();

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

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

//Accountmovement
$myAccountmovement = new Accountmovement();
$myAccountmovementRecord = new AccountmovementMySqlDAO();
$accountMovementExt = new AccountmovementMySqlExtDAO();

$CheckdepositEX = new CheckdepositMySqlExtDAO();
$checkWithdrawalExtDAO = new CheckwithdrawalMySqlExtDAO;
$cashTransferExt = new CashtransferMySqlExtDAO();
$datedCheckedEX = new DatedcheckedMySqlExtDAO();

$mySellbillEx = new SellbillMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

$usergroupdata = $UsergroupDAO->load($usergroupID);
$smarty->assign("savedailydate", $usergroupdata->savedailydate);


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

$billsData = array();
$billsRetData = array();
$billsBuyData = array();
$smarty->assign("searchinonesave", $_SESSION['searchinonesave']);
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    // here the function that do the action
    $saveData = loadSaveByUserPrivileg();
    $smarty->assign("saveData", $saveData);

    $allAccounts = $myBankaccountEx->queryAllWithBankName();
    $smarty->assign("allAccounts", $allAccounts);

    $message = "تقرير تدفق النقدية بالخزينة والبنك اليوم";

    $today = date('Y-m-d');
    $yesterday = date("Y-m-d", strtotime('-1 days'));
    if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
        $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
        $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
        $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
        //
        $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
    } else {
        $endToday = $today . ' 23:59:59';
        $startToday = $today . " 00:00:00";
        //
        $endYesterday = $today . ' 23:59:59';
        $startYesterday = $today . " 00:00:00";
    }
    if (date('H') < $Programsetting->reportsPlusHours) {
        $startDate = $startYesterday;
        $endDate = $endYesterday;
    } else {
        $startDate = $startToday;
        $endDate = $endToday;
    }
    ##############

    if ($_SESSION['searchinonesave'] == 0) {
        $returnSerach = search($saveId, $startDate, $endDate, $accountId);
    } else {
        $returnSerach = search($_SESSION['saveid'], $startDate, $endDate, $accountId);
    }
    $smarty->assign('message', $message);

    //breadcrumb
    $breadcrumbObject->add('الادارة><a href="cashSaveFlowController.php">التقارير</a> >تقرير تدفق النقدية بالخزنة', 'cashSaveFlowController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);

    $smarty->display("cashsaveflowview/show.html");
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    // here the function that do the action
    $saveData = loadSaveByUserPrivileg();
    $smarty->assign("saveData", $saveData);

    $allAccounts = $myBankaccountEx->queryAllWithBankName();
    $smarty->assign("allAccounts", $allAccounts);
    $save = $_REQUEST['saveId'];
    if ($save) {
        $save = explode('_', $save);
        $type = $save[0];
        $id = $save[1];
        if ($type == 'save')
            $saveId = $id;
        else
            $accountId = $id;
    }
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $message = "تقرير تدفق النقدية ";
    if ((isset($saveId) && $saveId != '-1')) {
        $mysavedata = $mySaveRecord->load($saveId);
        $message .= 'بالخزينة ' . $mysavedata->savename;
    }
    if ((isset($accountId) && $accountId != '-1')) {
        $accountData = $myBankaccountRecord->load($accountId);
        $search = $_REQUEST['search'];
        $message .= "بالحساب البنكي " . $accountData->accountname;
    }
    if (!empty($startDate) && !empty($endDate)) {
        $search = $_REQUEST['search'];
        if ($search == "dateOnly") {
            if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
                $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
                $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
                $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
            } else {
                $endDate = $endDate . ' 23:59:59';
                $startDate = $startDate . " 00:00:00";
            }
        }
        $message .= " من  " . $startDate . "  الى  " . $endDate;
    }
    if ($_SESSION['searchinonesave'] == 0) {
        $returnSerach = search($saveId, $startDate, $endDate, $accountId);
    } else {
        $returnSerach = search($_SESSION['saveid'], $startDate, $endDate, $accountId);
    }
    $smarty->assign('message', $message);

    //breadcrumb
    $breadcrumbObject->add('الادارة><a href="cashSaveFlowController.php">التقارير</a> >تقرير تدفق النقدية بالخزنة', 'cashSaveFlowController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);

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

    //here the smarty templates

    $smarty->display("error.html");
}

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

/* ===============================
  function in this CONTROLLER
  ================================ */
//# load saves by user id
function loadSaveByUserPrivileg()
{

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

    $userData = $myUserRecord->load($_SESSION['userid']);
    if ($userData->searchinonesave == 0) {
        //load all save data
        $saveData = $mySaveRecord->queryByConditions(0);
    } else {
        $saveData = array();
        $userSave = $mySaveRecord->load($userData->saveid);
        array_push($saveData, $userSave);
    }


    return $saveData;
}


function search($saveid, $startDate, $endDate, $accountId)
{
    global $mySavedailyEx;
    global $mySaveRecord;
    global $mySaveExt;
    global $clientDeptChangeExt;
    global $smarty;
    global $queryString;
    global $supplierDebtChangeExt;
    global $myBankaccountRecord;
    global $accountMovementExt;
    global $CheckdepositEX;
    global $checkWithdrawalExtDAO;
    global $cashTransferExt;
    global $datedCheckedDAO;
    global $supplierDAO;
    global $clientDAO;
    global $mySellbillEx;

    $save = $_REQUEST['saveId'];
    $all = 0;
    if (!$save || $save == -1)
        $all = 1;
    else {
        $type = explode('_', $save)[0];
    }
    $queryString = ' WHERE';
    $accQueryString = '';
    if (isset($saveid) && $saveid != '-1') {
        $mysavedata = $mySaveRecord->load($saveid);
        $message = "تقرير تدفق النقدية بالخزنة  " . $mysavedata->savename;
        $smarty->assign('message', $message);

        // $sumValue = sumCreditById($saveid);
        $queryString .= ' savedaily.saveid = ' . $saveid . ' AND';
    } elseif (isset($accountId) && $accountId != '-1') {
        $accountData = $myBankaccountRecord->load($accountId);
        $message = "تقرير تدفق النقدية بالحساب البنكي  " . $accountData->accountname;
        $smarty->assign('message', $message);

        $accQueryString .= ' and accountmovement.accountid = ' . $accountId;
    } else {
        if ($_SESSION['searchinonesave'] == 0) {
            if ($_SESSION['saveids'] != 0) {
                $queryString .= ' savedaily.saveid in (' . $_SESSION['saveids'] . ') AND';
            }
        }
    }

    if (!empty($startDate) && !empty($endDate)) {
        $message = "تقرير تدفق النقدية بالخزنة من  " . $startDate . "  الى " . $endDate;
        $smarty->assign('message', $message);
        $queryString .= ' savedaily.savedailydate >= ("' . $startDate . '" ) AND savedaily.savedailydate <= ("' . $endDate . '") AND';

        if ($startDate)
            $accQueryString .= ' and accountmovement.accountmovementdate >= "' . $startDate . '"';

        if ($endDate)
            $accQueryString .= ' and accountmovement.accountmovementdate <= "' . $endDate . '"';
    }

    $arr = explode(' ', $queryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            $queryString = ' ';
        }
    }
    $order = "asc";
    if ($all == 1 || $type == 'save') {
        $savedailyData = $mySavedailyEx->searchInAdsindexWithUsername($queryString, $order);
        $smarty->assign('savecur', $savedailyData[0]->savedailysavebefore);
        $savesData = $accountsData = $outData = $inData = $outDataAcc = $inDataAcc = [];
        $allSell = [];
        $allSellAccount = [];
        $allBuy = [];
        $saveids  = '';
        $accountids  = '';
        foreach ($savedailyData as $data) {
            if (!key_exists($data->saveid, $allSell)) {
                $sellObj = new stdClass();
                $sellObj->tablename = 'allSell';
                $sellObj->processname = 'اجمالي المبيعات';
                $sellObj->savedailychangeamount = 0;
                $allSell[$data->saveid] = $sellObj;
            }

            if (!key_exists($data->saveid, $allBuy)) {
                $buyObj = new stdClass();
                $buyObj->tablename = 'allBuy';
                $buyObj->processname = 'اجمالي المشتريات';
                $buyObj->savedailychangeamount = 0;
                $allBuy[$data->saveid] = $buyObj;
            }

            $outSum = 0;
            $inSum = 0;

            if (in_array($data->tablename, ["sellbillController.php", "sellbillandruternController.php", "returnsellbillController.php"])) {
                // var_dump($data);
                if ($data->savedailychangetype == 1) { //minus
                    if ($data->savedailychangeamount >= 0) {
                        $data->savedailychangeamount = $data->savedailychangeamount * -1;
                        $inSum = $data->savedailychangeamount;
                    }
                } else if ($data->savedailychangetype == 0) { //plus
                    if ($data->savedailychangeamount >= 0) {
                        $inSum = $data->savedailychangeamount;
                    } else {
                        $data->savedailychangeamount = $data->savedailychangeamount * -1;
                        $inSum = $data->savedailychangeamount;
                    }
                }
                $allSell[$data->saveid]->savedailychangeamount += $data->savedailychangeamount;
            } elseif (in_array($data->tablename, ["buyBillController.php", "returnBuyBillController.php"])) {
                // var_dump($data);
                if ($data->savedailychangetype == 1) { //minus
                    if ($data->savedailychangeamount >= 0) {
                        $outSum = $data->savedailychangeamount;
                    } else {
                        $data->savedailychangeamount = $data->savedailychangeamount * -1;
                        $outSum = $data->savedailychangeamount;
                    }
                } else if ($data->savedailychangetype == 0) { //plus
                    if ($data->savedailychangeamount >= 0) {
                        $data->savedailychangeamount = $data->savedailychangeamount * -1;
                        $outSum = $data->savedailychangeamount;
                    } else {
                        $outSum = $data->savedailychangeamount;
                    }
                }
                $allBuy[$data->saveid]->savedailychangeamount += $data->savedailychangeamount;
            } else {
                switch ($data->tablename) {
                    case "supplierPayedDeptController.php":
                    case "supplierDeficitController.php":
                        $data->savecurrentvalue = $supplierDebtChangeExt->getSupplierName($data->savedailymodelid)->suppliername;
                        break;
                    case "clientPayedDeptController.php":
                    case "clientDeficitController.php":
                        $data->savecurrentvalue = $clientDeptChangeExt->getClientName($data->savedailymodelid)->clientname;
                        break;
                    case "partnerwithdrawalController.php":
                        $data->savecurrentvalue = R::getRow('SELECT partner.partnername
                FROM partnerwithdrawal JOIN partner
                ON partnerwithdrawal.partnerid = partner.partnerid
                where partner.conditions = 0
                and partnerwithdrawalid =' . $data->savedailymodelid)['partnername'];
                        break;
                    case "expensesController.php":
                        $data->savecurrentvalue = R::getRow('SELECT expensesname FROM expenses WHERE expensesid =' . $data->savedailymodelid)['expensesname'];
                        break;
                    case "incomeController.php":
                        $data->savecurrentvalue = R::getRow('SELECT incomeName FROM income WHERE incomeId =' . $data->savedailymodelid)['incomeName'];
                        break;
                    case "employeePersonalController.php":
                        $data->savecurrentvalue = R::getRow('SELECT employeeName
                FROM employeepersonnel
                join employee on  employee.employeeId = employeepersonnel.employeeid
                WHERE employeepersonnelid=' . $data->savedailymodelid)['employeeName'];
                        break;
                }

                if ($data->savedailychangetype == 1) { //minus
                    if ($data->savedailychangeamount >= 0) {
                        $outData[] = $data;
                        $outSum = $data->savedailychangeamount;
                    } else {
                        $data->savedailychangeamount = $data->savedailychangeamount * -1;
                        $inData[] = $data;
                        $inSum = $data->savedailychangeamount;
                    }
                } else if ($data->savedailychangetype == 0) { //plus
                    if ($data->savedailychangeamount >= 0) {
                        $inData[] = $data;
                        $inSum = $data->savedailychangeamount;
                    } else {
                        $data->savedailychangeamount = $data->savedailychangeamount * -1;
                        $inData[] = $data;
                        $inSum = $data->savedailychangeamount;
                    }
                }
            }
            if (!array_key_exists($data->saveid, $savesData)) {
                $saveids .= $data->saveid . ',';
                $saveData = $mySaveRecord->load($data->saveid);
                $savesData[$data->saveid] = ['savename' => $data->savename, 'balance' => $data->savedailysavebefore, 'currentBalance' => $saveData->savecurrentvalue, 'inSum' => $inSum, 'outSum' => $outSum];
            } else {
                $savesData[$data->saveid]['inSum'] += $inSum;
                $savesData[$data->saveid]['outSum'] += $outSum;
            }
        }
        if ($all == 1) {
            $qs = '';
            $saveids = rtrim($saveids, ',');
            if ($saveids != '') {
                $qs = ' and saveid not in (' . $saveids . ')';
            }
            $otherSaves = R::getAll('select * from save where conditions = 0' . $qs);
            foreach ($otherSaves as $save) {
                $lastSaveDailyData = R::getRow('select * from savedaily where saveid = ' . $save['saveid'] . ' and savedailydate < "' . $startDate . '" order by savedailyid desc limit 1');
                if ($lastSaveDailyData) {
                    $savesData[$save['saveid']] = ['savename' => $save['savename'], 'balance' => $lastSaveDailyData['savedailysaveafter'], 'currentBalance' => $save['savecurrentvalue'], 'inSum' => 0, 'outSum' => 0];

                    $sellObj = new stdClass();
                    $sellObj->tablename = 'allSell';
                    $sellObj->processname = 'اجمالي المبيعات';
                    $sellObj->savedailychangeamount = 0;
                    $allSell[$save['saveid']] = $sellObj;

                    $buyObj = new stdClass();
                    $buyObj->tablename = 'allBuy';
                    $buyObj->processname = 'اجمالي المشتريات';
                    $buyObj->savedailychangeamount = 0;
                    $allBuy[$save['saveid']] = $buyObj;
                }
            }
        }
        $smarty->assign('savedailyData', $savedailyData);
        $smarty->assign('allSell', $allSell);
        $smarty->assign('allBuy', $allBuy);
        $smarty->assign('savesData', $savesData);
        $smarty->assign('outData', $outData);
        $smarty->assign('inData', $inData);
    }
    if ($all == 1 || $type == 'bank') {
        $allMovements = $accountMovementExt->queryAllMovements($accQueryString);
        foreach ($allMovements as $movement) {
            if (!key_exists($movement->accountid, $allSellAccount)) {
                $sellObj = new stdClass();
                $sellObj->tablename = 'allSell';
                $sellObj->processname = 'اجمالي المبيعات';
                $sellObj->accountmovementamount = 0;
                $allSellAccount[$movement->accountid] = $sellObj;
            }
            $outSum = 0;
            $inSum = 0;

            if ($movement->tablename == "depositcheckController.php") {
                $depositData = $CheckdepositEX->loadEX($movement->accountmovementmodelid);
                $movement->clientname = $depositData->clientname;
                if ($movement->accountmovementtype == 0) {
                    $inSum = $movement->accountmovementamount;
                    $inDataAcc[] = $movement;
                } else {
                    $outSum = $movement->accountmovementamount;
                    $outDataAcc[] = $movement;
                }
            } elseif ($movement->tablename == "checkwithdrawalController.php") {
                $withdrawalData = $checkWithdrawalExtDAO->queryByIdExtwithsuplier($movement->accountmovementmodelid);
                $movement->clientname = $withdrawalData->suppliername;
                if ($movement->accountmovementtype == 0) {
                    $inSum = $movement->accountmovementamount;
                    $inDataAcc[] = $movement;
                } else {
                    $outSum = $movement->accountmovementamount;
                    $outDataAcc[] = $movement;
                }
            } elseif ($movement->tablename == "cashTransferController.php") {
                $transferData = $cashTransferExt->loadExt($movement->accountmovementmodelid);
                if ($transferData->type == 1)
                    $movement->processname = "تحويل تقدي من بنك (" . $movement->bankname . " ) إلى خزنة (" . $transferData->savename . ")";
                if ($movement->accountmovementtype == 0) {
                    $inSum = $movement->accountmovementamount;
                    $inDataAcc[] = $movement;
                } else {
                    $outSum = $movement->accountmovementamount;
                    $outDataAcc[] = $movement;
                }
            } elseif ($movement->tablename == "datedCheckedController.php") {
                $row = $datedCheckedDAO->load($movement->accountmovementmodelid);
                if ($row->addType == 1) {
                    $supID = $row->clientNum;
                    $allSup = $supplierDAO->load($supID);
                    $clName = $allSup->suppliername;
                } else {
                    $id1 = $row->clientNum;
                    $allClient = $clientDAO->load($id1);
                    $clName = $allClient->clientname;
                }
                $movement->clientname = $clName;

                if ($movement->accountmovementtype == 0) {
                    $inSum = $movement->accountmovementamount;
                    $inDataAcc[] = $movement;
                } else {
                    $outSum = $movement->accountmovementamount;
                    $outDataAcc[] = $movement;
                }
            } elseif ($movement->tablename == "sellbillController.php") {
                $sellData = $mySellbillEx->loadExtWithClient($movement->accountmovementmodelid);
                $movement->clientname = " " . $sellData->clientname . " / " . $movement->accountmovementmodelid . " ";

                $inSum = $movement->accountmovementamount;
                $allSellAccount[$movement->accountid]->accountmovementamount += $movement->accountmovementamount;
            } else {
                if ($movement->accountmovementtype == 0) {
                    $inSum = $movement->accountmovementamount;
                    $inDataAcc[] = $movement;
                } else {
                    $outSum = $movement->accountmovementamount;
                    $outDataAcc[] = $movement;
                }
            }

            if (!array_key_exists($movement->accountid, $accountsData)) {
                $accountids .= $movement->accountid . ',';
                $accountData = $myBankaccountRecord->load($movement->accountid);
                $accountsData[$movement->accountid] = ['accountname' => $movement->accountname, 'balance' => $movement->accountmovementbefore, 'currentBalance' => $accountData->accountbeginingbalance, 'inSum' => $inSum, 'outSum' => $outSum];
            } else {
                $accountsData[$movement->accountid]['inSum'] += $inSum;
                $accountsData[$movement->accountid]['outSum'] += $outSum;
            }
        }
        if ($all == 1) {
            $qsAcc = '';
            $accountids = rtrim($accountids, ',');
            if ($accountids != '') {
                $qsAcc = ' and accountid not in (' . $accountids . ')';
            }
            $otherAcc = R::getAll('select * from bankaccount where conditions = 0' . $qsAcc);
            foreach ($otherAcc as $acc) {
                $lastAccMovement = R::getRow('select * from accountmovement where accountid = ' . $acc['accountid'] . ' and accountmovementdate < "' . $startDate . '" order by accountmovementid desc limit 1');
                if ($lastAccMovement) {
                    $accountsData[$acc['accountid']] = ['accountname' => $acc['accountname'], 'balance' => $lastAccMovement['accountmovementafter'], 'currentBalance' => $acc['accountbeginingbalance'], 'inSum' => 0, 'outSum' => 0];

                    $sellObj = new stdClass();
                    $sellObj->tablename = 'allSell';
                    $sellObj->processname = 'اجمالي المبيعات';
                    $sellObj->accountmovementamount = 0;
                    $allSellAccount[$acc['accountid']] = $sellObj;
                }
            }
        }
        $smarty->assign('allMovements', $allMovements);
        $smarty->assign('allSellAccount', $allSellAccount);
        $smarty->assign('accountsData', $accountsData);
        $smarty->assign('outDataAcc', $outDataAcc);
        $smarty->assign('inDataAcc', $inDataAcc);
    }

    if (empty($savedailyData) && empty($allMovements)) {
        return -1;
    } else {
        return 0;
    }
}
