<?php

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

include_once("initiateStaticSessionCommingWithCurl.php");


//global varable
global $showoutside;

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


//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
include_once("../library/num_to_ar.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 :- SavedailyCTRL تقرير يومية الخزينة

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

} else {
    $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();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//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();
//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']);
//print_r($usergroupdata);
//check and use the condetion that suite this action
if ($do == "show" || 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 = loadSave();
    $saveData = loadSaveByUserPrivileg();
    $smarty->assign("saveData", $saveData);
    $usersData = loadUserByUserPrivileg();
    $smarty->assign("usersData", $usersData);



    $allprocess = loadprocess();
    $smarty->assign("allprocess", $allprocess);

    $saveId = $_REQUEST['saveId'];
    $userId = (int) $_REQUEST['userId'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $processid = $_REQUEST['processid'];
    $order = $_REQUEST['order'];
    /////////////////////////////////////////nooooooooooooooooooooor//////////////////////////////////////////////
    if ((isset($saveId) && $saveId != '-1') || (isset($processid) && $processid != '-1') || (!empty($startDate) && !empty($endDate))) {
        $mysavedata = $mySaveRecord->load($saveId);
        $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 = "تقرير يوميه  " . $mysavedata->savename . "  من  " . $startDate . "  الى  " . $endDate;
        $smarty->assign('message', $message);

        if ($_SESSION['searchinonesave'] == 0) {
            $returnSerach = search($saveId, $processid, $startDate, $endDate, $userId);
        } else {
            $returnSerach = search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        // $sumValue=sumCreditById($saveId);
    } else {
        $message = "تقرير يوميه الخزنه ";
        $smarty->assign('message', $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, $processid, $startDate, $endDate, $userId);
        } else {
            $returnSerach = search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        //	$sumValue=sumCredit();
    }

    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
        list($savedailyData, $allMovements) = getRoyalData($returnSerach['savePayments'], $returnSerach['bankPayments']);
        echo json_encode(array("savePayments" => $savedailyData, "bankPayments" => $allMovements));
        exit();
    } else {
        //breadcrumb
        $breadcrumbObject->add('الادارة><a href="savedailyController.php">التقارير</a> >تقرير يومية الخزينة', 'savedailyController.php', 0);
        //Now output the navigation.
        $breadCrumb = $breadcrumbObject->output();
        $smarty->assign("breadCrumb", $breadCrumb);

        //    if ($returnSerach == -1) {
        //        $smarty->display("noData.html");
        //    } else {
        //        //here the smarty templates
        //        $smarty->display("savedailyview/show.html");
        //    }
        if ($lang == "en")
            $smarty->display("savedailyview/show_ltr.html");
        else
            $smarty->display("savedailyview/show.html");
    }
} elseif ($do == "showdailywithoptic") {
//here the permssion check
    include_once("../public/authentication.php");


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

    $storeData = loadStoresByUserId();
    $smarty->assign("storeData", $storeData);

    $branchData = loadAllBranches();
    $smarty->assign("branchData", $branchData);

    $allprocess = loadprocess();
    $smarty->assign("allprocess", $allprocess);

    $saveId = $_REQUEST['saveId'];
    $userId = (int) $_REQUEST['userId'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $processid = $_REQUEST['processid'];

    $cash = 0; //(int) $_REQUEST['cash'];
    $insurance = (int) $_REQUEST['insurance'];
    $network = (int) $_REQUEST['network'];


    $billsData = array();
    $billsRetData = array();
    $billsBuyData = array();
    /////////////////////////////////////////nooooooooooooooooooooor//////////////////////////////////////////////
    if ((isset($saveId) && $saveId != '-1') || (!empty($startDate) && !empty($endDate))) {
        $mysavedata = $mySaveRecord->load($saveId);

        $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 = "تقرير يومية الخزنة بالبصريات   " . $mysavedata->savename . "  من  " . $startDate . "  الى  " . $endDate;
        $smarty->assign('message', $message);


        if ($_SESSION['searchinonesave'] == 0) {
            //getOpticData($saveId, $startDate, $endDate, $cash, $insurance, $network);
            $returnSerach = search($saveId, $processid, $startDate, $endDate, $userId);
        } else {
            //getOpticData($_SESSION['saveid'], $startDate, $endDate, $cash, $insurance, $network);
            $returnSerach = search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        // $sumValue=sumCreditById($saveId);
    } else {
        $message = "تقرير يومية الخزنة بالبصريات";
        $smarty->assign('message', $message);
        $startDate = $endDate = date('Y-m-d');
        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";
        }
        if ($_SESSION['searchinonesave'] == 0) {
            //getOpticData($saveId, date("Y-m-d"), date("Y-m-d"), $cash, $insurance, $network);
            $returnSerach = search($saveId, $processid, $startDate, $endDate, $userId);
        } else {
            //getOpticData($_SESSION['saveid'], date("Y-m-d"), date("Y-m-d"), $cash, $insurance, $network);
            $returnSerach = search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        //	$sumValue=sumCredit();
    }


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

//    if ($returnSerach == -1) {
//        $smarty->display("noData.html");
//    } else {
//        //here the smarty templates
//        $smarty->display("savedailyview/show.html");
//    }
    $smarty->display("savedailyview/showoptic.html");
} elseif ($do == "show2") {

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

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

    $allprocess = loadprocess();
    $smarty->assign("allprocess", $allprocess);

    $saveId = $_REQUEST['saveId'];
    $userId = (int) $_REQUEST['userId'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $processid = $_REQUEST['processid'];

    /////////////////////////////////////////nooooooooooooooooooooor//////////////////////////////////////////////
    if ((isset($saveId) && $saveId != '-1') || (isset($processid) && $processid != '-1') || (!empty($startDate) && !empty($endDate))) {
        $mysavedata = $mySaveRecord->load($saveId);
        $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 = "تقرير يوميه  " . $mysavedata->savename . "  من  " . $startDate . "  الى  " . $endDate;
        $smarty->assign('message', $message);


        if ($_SESSION['searchinonesave'] == 0) {
            search($saveId, $processid, $startDate, $endDate, $userId);
        } else {
            search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        // $sumValue=sumCreditById($saveId);
    } else {
        $message = "تقرير يوميه الخزنه ";
        $smarty->assign('message', $message);
        $startDate = $endDate = date('Y-m-d');
        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";
        }
        if ($_SESSION['searchinonesave'] == 0) {
            search($saveId, $processid, $startDate, $endDate, $userId);
        } else {
            search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        //	$sumValue=sumCredit();
    }


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



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

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


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

    $allprocess = loadprocess();
    $smarty->assign("allprocess", $allprocess);

    $saveId = $_REQUEST['saveId'];
    $userId = (int) $_REQUEST['userId'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $processid = $_REQUEST['processid'];



    /////////////////////////////////////////nooooooooooooooooooooor//////////////////////////////////////////////
    if ((isset($saveId) && $saveId != '-1') || (isset($processid) && $processid != '-1') || (!empty($startDate) && !empty($endDate))) {
        $mysavedata = $mySaveRecord->load($saveId);
        $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 = "تقرير يوميه  " . $mysavedata->savename . "  من  " . $startDate . "  الى  " . $endDate;
        $smarty->assign('message', $message);


        if ($_SESSION['searchinonesave'] == 0) {
            search($saveId, $processid, $startDate, $endDate, $userId);
        } else {
            search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        // $sumValue=sumCreditById($saveId);
    } else {
        $message = "تقرير يوميه الخزنه ";
        $smarty->assign('message', $message);

        $startDate = $endDate = date('Y-m-d');
        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";
        }

        if ($_SESSION['searchinonesave'] == 0) {
            search($saveId, $processid, $startDate, $endDate, $userId);
        } else {
            search($_SESSION['saveid'], $processid, $startDate, $endDate, $userId);
        }
        //	$sumValue=sumCredit();
    }


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



    if (!isset($saveId) || empty($saveId)) {
        $saveId = -1;
    }

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


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

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

    // here the function that do the action
    $savedailyDetail = showDetail();
    $smarty->assign('savedailyDetail', $savedailyDetail);


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

    //here the smarty templates
    $smarty->display("savedailyview/showdetail.html");
} elseif ($do == "joined") {
    // here the function that do the action
    if ($_SESSION['searchinonesave'] == 0) {
        $saveQuery = '';
        if ($_SESSION['saveids'] != 0) {
            $saveQuery .= ' and saveid in (' . $_SESSION['saveids'] . ')';
        }
    } else {
        $saveQuery = ' and saveid= ' . $_SESSION['saveid'];
    }
    $saveData = R::getAll('SELECT  *  FROM `save` WHERE conditions = 0 ' . $saveQuery);
    $smarty->assign("allSave", $saves);
    //$smarty->assign("saveid", $_SESSION['saveid']);
    $smarty->assign("saveData", $saveData);

    $usersData = loadUserByUserPrivileg();
    $smarty->assign("usersData", $usersData);

    $saveId = (int) $_REQUEST['saveId'];
    $userId = (int) $_REQUEST['userId'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $search = $_REQUEST['search'];
    if (empty($startDate) && empty($endDate)) {
        $startDate = $endDate = date('Y-m-d');
    }
    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 = '';
    $queryString = '';
    if ($saveId > 0) {
        $queryString .= " and saveid = $saveId ";
        $savename = R::getCell('select savename from save where saveid=' . $saveId);
        $message .= " خزينة ( $savename )";
    }
    if ($userId > 0) {
        $queryString .= " and userid = $userId ";
        $employeename = R::getCell('select employeename from user where userid=' . $userId);
        $message .= " المستخدم ( $employeename )";
    }
    if (!empty($startDate)) {
        $queryString .= " and savedailydate >= '" . $startDate . "' ";
        $message .= " من تاريخ $startDate ";
    }
    if (!empty($endDate)) {
        $queryString .= " and savedailydate <= '" . $endDate . "' ";
        $message .= " الى تاريخ $endDate ";
    }
    $smarty->assign('message', $message);

    $laterNakdiClient = $Programsetting->laterNakdiClientId;

    ## save value before
    if ($saveId > 0)
        $valueFirstOfPeriod = R::getCell('select savedailysavebefore from savedaily where 1 ' . $queryString . ' order by savedailyid asc');
    else{
        $valueFirstOfPeriodAllSave = R::getAll('select savedailysavebefore from savedaily where 1 ' . $queryString . ' group by saveid order by savedailyid asc');
        $valueFirstOfPeriod = 0;
        foreach($valueFirstOfPeriodAllSave  as $data)
        {
            $valueFirstOfPeriod += $data['savedailysavebefore'];
        }
    }
    ##expenses
    $expensesVal = R::getCell('select SUM(IF(`savedailychangetype` = 0, -`savedailychangeamount`, `savedailychangeamount`)) AS net
             from savedaily where tablename="expensesController.php" ' . $queryString);

    ##client payments
    $payedDeptVal = R::getCell('select SUM(IF(`savedailychangetype` = 0, `savedailychangeamount`, -`savedailychangeamount`)) AS net
             from savedaily where tablename="clientPayedDeptController.php" and clientid !=' . $laterNakdiClient . $queryString);
    ##sellbill payments or paing at bill itself
    $payedDeptSellBillVal = R::getCell('select SUM(IF(`savedailychangetype` = 0, `savedailychangeamount`, -`savedailychangeamount`)) AS net
             from savedaily where 1 and (tablename="clientPayedDeptSellBillsController.php" || tablename="sellbillController.php") and clientid !=' . $laterNakdiClient . $queryString);
    ##retsellbill payments or paing at bill itself
    $payedDeptRetSellBillVal = R::getCell('select SUM(IF(`savedailychangetype` = 0, abs(`savedailychangeamount`), -abs(`savedailychangeamount`))) AS net
             from savedaily where 1 and (tablename="clientPayedDeptReturnSellBillsController.php" || tablename="returnsellbillController.php") and clientid !=' . $laterNakdiClient . $queryString);
    $payedDeptRetSellBillVal = abs($payedDeptRetSellBillVal);

    ##later nakdi
    $payedDeptValLaterNakdi = R::getCell('select SUM(IF(`savedailychangetype` = 0, `savedailychangeamount`, -`savedailychangeamount`)) AS net
             from savedaily where tablename="clientPayedDeptController.php" and clientid =' . $laterNakdiClient . $queryString);
    ##sellbill payments or paing at bill itself
    $payedDeptSellBillValLaterNakdi = R::getCell('select SUM(IF(`savedailychangetype` = 0, `savedailychangeamount`, -`savedailychangeamount`)) AS net
             from savedaily where 1 and (tablename="clientPayedDeptSellBillsController.php" || tablename="sellbillController.php") and clientid =' . $laterNakdiClient . $queryString);
    ##retsellbill payments or paing at bill itself
    $payedDeptRetSellBillValLaterNakdi = R::getCell('select SUM(IF(`savedailychangetype` = 0, abs(`savedailychangeamount`), -abs(`savedailychangeamount`))) AS net
             from savedaily where 1 and (tablename="clientPayedDeptReturnSellBillsController.php" || tablename="returnsellbillController.php") and clientid =' . $laterNakdiClient . $queryString);
    $payedLaterNakdiVal = $payedDeptValLaterNakdi + $payedDeptSellBillValLaterNakdi + $payedDeptRetSellBillValLaterNakdi;

    $payedSellBillVal = R::getCell('select SUM(IF(`savedailychangetype` = 0, `savedailychangeamount`, -`savedailychangeamount`)) AS net
             from savedaily where 1 and (tablename="clientPayedDeptSellBillsController.php")' . $queryString);
             
    $payedRetSellBillVal = R::getCell('select SUM(savedailychangeamount) AS net
             from savedaily where 1 and (tablename="clientPayedDeptReturnSellBillsController.php")' . $queryString);
             
    $cashPayed = R::getCell('SELECT SUM(if(`processname` = "ايصال دفع لمورد", `savedailychangeamount` ,-`savedailychangeamount`)) from savedaily where 1 and ( `processname` ="ايصال دفع لمورد" || `processname` = "الغاء سداد ديون مورد")'. $queryString);
    
    $laterPayed = R::getCell('SELECT SUM(if(`processname` = "ايصال تحصيل (( قبض من عميل ))", `savedailychangeamount` ,-`savedailychangeamount`)) from savedaily where 1 and ( `processname` ="ايصال تحصيل (( قبض من عميل )" || `processname` = "الغاء سداد ديون عميل")'. $queryString);
    
    ###############################
    #totals
    $totalIncome = $valueFirstOfPeriod +$payedSellBillVal+ $laterPayed;//$payedDeptVal + $payedLaterNakdiVal;
    $totalexp = $expensesVal + $payedRetSellBillVal + $cashPayed;//$payedDeptVal + $payedDeptSellBillVal + $payedDeptRetSellBillVal + $expensesVal;
    $net = $totalIncome - $totalexp;

    if ($net != 0) {
        $ar_number = new convert_ar(abs($net), "male");
        $netWritten = $ar_number->convert_number();
        $netWritten .= ' ' . $Programsetting->currancy . ' فقط لاغير';
        $smarty->assign('netWritten', $netWritten);
    }

    $smarty->assign('valueFirstOfPeriod', $valueFirstOfPeriod);
    $smarty->assign('payedDeptVal', $payedDeptVal);
    $smarty->assign('payedDeptSellBillVal', $payedDeptSellBillVal);
    $smarty->assign('payedDeptRetSellBillVal', $payedDeptRetSellBillVal);
    $smarty->assign('expensesVal', $expensesVal);
    $smarty->assign('payedLaterNakdiVal', $payedLaterNakdiVal);
    $smarty->assign('payedSellBillVal', $payedSellBillVal);
    $smarty->assign('payedRetSellBillVal', $payedRetSellBillVal);
    $smarty->assign('cashPayed', $cashPayed);
    $smarty->assign('laterPayed', $laterPayed);

    $smarty->assign('totalIncome', $totalIncome);
    $smarty->assign('totalexp', $totalexp);
    $smarty->assign('net', $net);

    //here the smarty templates
    $smarty->display("savedailyview/joined.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
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

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

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

//select all save data
function loadSave() {

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

    //load all save data
    $saveData = $mySaveRecord->queryByConditions(0);

    return $saveData;
}

//# load saves by user id
function loadSaveByUserId() {

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

    //load all save data
    $saveData = $mySaveRecord->queryByUserid($_SESSION['userid']);

    return $saveData;
}

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

//# load saves by user id
function loadUserByUserPrivileg() {

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

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


    return $userArray;
}

//# load sotre by user id
function loadStoresByUserId() {

    //to use the variable out side the funcion
    global $myStoreRecord;

    //load all stores data
    $storeData = $myStoreRecord->queryByUserId($_SESSION['userid']);

    return $storeData;
}

//# load all branchs
function loadAllBranches() {

    //to use the variable out side the funcion
    global $BranchDAO;

    //load all Branch data
    $branchData = $BranchDAO->queryAll();

    return $branchData;
}

///////////////////////select process////////////
function loadprocess() {
    global $mySavedailyEx;

    $allprocess = $mySavedailyEx->queryAllPROCESS();
    return $allprocess;
}

///////////////////////save currentvalue////////////////////////////////////
function sumCredit() {
    global $mySaveRecord;

    //select all data from save tbl
    $saveData = $mySaveRecord->queryByConditions(0);

    //get the sum of value
    $sumValue = 0;
    foreach ($saveData as $save) {
        $savecurrentValue = $save->savecurrentvalue;


        $sumValue += $savecurrentValue;
    }

    return $sumValue;
}

function sumCreditById($id) {
    //to use the variable out side the funcion
    global $mySaveRecord;

    //load data from save tbl by id
    $saveData = $mySaveRecord->load($id);


    //get the sum of value in save
    $savecurrentValue = $saveData->savecurrentvalue;
    $sumValue = $savecurrentValue;

    return $sumValue;
}

//load savedaily detail
function showDetail() {
    //to use the variable out side the funcion
    global $mySavedailyEx;

    //get variable
    $savedailyid = $_GET['savedailyid'];

    //load savedaily data by id
    $savedailyDetail = $mySavedailyEx->queryAllBysavedailyid($savedailyid);

    return $savedailyDetail;
}

///////////////////////////////////////////////nooooooooooooooor///////////////////////////
function search($saveid, $processid, $startDate, $endDate, $userId = 0) {
    global $mySavedailyRecord;
    global $mySavedailyEx;
    global $mySaveRecord;
    global $clientDAO;
    global $supplierDAO;
    global $supplierExt;
    global $clientDeptChangeExt;
    global $smarty;
    global $queryString;
    global $do;
    global $billsData;
    global $billsRetData;
    global $billsBuyData;
    global $myUserRecord;
    global $accountMovementEX;

    $bure = $_POST["bure"];
    $db = $_POST["db"];

    $queryString = ' WHERE';
    $accountQS = '';
 $message = "تقرير يوميه الخزينة ";
    if (isset($saveid) && $saveid > 0) {
        $mysavedata = $mySaveRecord->load($saveid);
       $message .=  " " . $mysavedata->savename;

        $sumValue = sumCreditById($saveid);
        $queryString .= ' savedaily.saveid = ' . $saveid . ' AND';
    } else {
        if ($_SESSION['searchinonesave'] == 0) {
            if ($_SESSION['saveids'] != 0) {
                $queryString .= ' savedaily.saveid in (' . $_SESSION['saveids'] . ') AND';
            }
        }

        $sumValue = sumCredit();
    }

    if (isset($processid) && $processid != '-1') {



        $queryString .= ' savedaily.processname = "' . $processid . '" AND';
    }
    if (isset($userId) && $userId > 0) {



        $queryString .= ' savedaily.userid = "' . $userId . '" AND';
        $accountQS .= ' and accountmovement.userid = ' . $userId . ' ';
    }

    if (!empty($startDate) && !empty($endDate)) {
        $message .= " من  " . $startDate . "  الى " . $endDate;
        $queryString .= ' savedaily.savedailydate >= ("' . $startDate . '" ) AND savedaily.savedailydate <= ("' . $endDate . '") AND';
        $accountQS .= ' and accountmovementdate >= "' . $startDate . '" and  accountmovementdate <= "' . $endDate . '" and bankaccount.visa = 1 and bankaccount.conditions = 0';
    }


        $smarty->assign('message', $message);
    $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 = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }
    $order = "desc";
    if (isset($_REQUEST['order']) && $_REQUEST['order'] == "asc") {
        $order = "asc";
    }

    $savedailyData = $mySavedailyEx->searchInAdsindexWithUsername($queryString, $order);
    $allMovements = $accountMovementEX->queryAllMovements($accountQS);
    $sumValOfVisaAccount = $accountMovementEX->sumValOfVisaAccount();
    $changeAmountSum_account = 0;
    foreach ($allMovements as $value) {
        if ($value->accountmovementtype == 0) {
            $changeAmountSum_account += $value->accountmovementamount;
        } else {
            $changeAmountSum_account -= $value->accountmovementamount;
        }
    }
    $smarty->assign('sumValOfVisaAccount', $sumValOfVisaAccount);
    $smarty->assign('changeAmountSum_account', $changeAmountSum_account);
    $smarty->assign('allMovements', $allMovements);
    #
    $savecur = $savedailyData[0]->savedailysavebefore;
    $smarty->assign('savecur', $savedailyData[0]->savedailysavebefore);


    foreach ($billsData as $value) {
        $obj = new stdClass();
        $client_data = $clientDAO->load($value->clientid);
        $obj->clientname = $client_data->clientname;

        $obj->savedailyid = 1; //it must be >0 to be displayed in tbl
        $obj->savedailysavebefore = 0;
        $obj->processname = "فاتورة بصريات (  ";
        $amount = 0;
        if ($value->cash == 1) {
            $amount += $value->cashvalue;
            $obj->processname .= " كاش= " . $value->cashvalue . "  &nbsp&nbsp";
        }
        if ($value->insurance == 1) {
            $amount += $value->customercarry + $value->companycarry;
            $obj->processname .= " تأمين= " . ($value->customercarry + $value->companycarry) . "  &nbsp&nbsp";
        }
        if ($value->card == 1) {
            $amount += $value->cardvalue;
            $obj->processname .= " شبكة= " . $value->cardvalue . "  &nbsp&nbsp";
        }
        if ($value->waitvalue > 0) {
            $obj->processname .= " اجل= " . $value->waitvalue;
        }
        $obj->processname .= " )";

        $obj->savedailychangeamount = $amount;
        $obj->savedailychangetype = 0;
        $obj->savedailymodelid = $value->id;
        $obj->savedailysaveafter = 0;
        $obj->savedailydate = substr($value->billdate, 0, 10);
        $obj->userid = $value->userid;
        $obj->tablename = "bills.php";
        $obj->finalstring = "";
        $mysavedata = $mySaveRecord->load($value->saveid);
        $obj->savename = $mysavedata->savename;
        $obj->link = "nosave";

        array_push($savedailyData, $obj);
    }
    foreach ($billsRetData as $value) {
        $obj = new stdClass();
        $client_data = $clientDAO->load($value->clientid);
        $obj->clientname = $client_data->clientname;
        $obj->savedailyid = 1; //it must be >0 to be displayed in tbl
        $obj->savedailysavebefore = 0;
        $obj->processname = "فاتورة مردود بصريات (  ";
        $amount = $value->clientreceivevalue;
        $amount += $value->clientreceivevalue;
        $obj->processname .= " المبلغ المرتجع للعميل= " . $value->clientreceivevalue;

        $obj->processname .= " )";

        $obj->savedailychangeamount = $amount;
        $obj->savedailychangetype = 1;
        $obj->savedailymodelid = $value->id;
        $obj->savedailysaveafter = 0;
        $obj->savedailydate = $value->date;
        $obj->userid = $value->userid;
        $obj->tablename = "billsreturn.php";
        $obj->finalstring = "";
        if ($value->saveid > 0) {
            $mysavedata = $mySaveRecord->load($value->saveid);
            $obj->savename = $mysavedata->savename;
        } else {
            $obj->savename = "لا يوجد";
        }
        $obj->link = "nosave";
        array_push($savedailyData, $obj);
    }
    foreach ($billsBuyData as $value) {
        $obj = new stdClass();
        $client_data = $clientDAO->load($value->clientid);
        $obj->clientname = $client_data->clientname;
        $obj->savedailyid = 1; //it must be >0 to be displayed in tbl
        $obj->savedailysavebefore = 0;
        $obj->processname = "فاتورة شراء بصريات (  ";
        $amount = 0;
        if ($value->cash == 1) {
            $amount += $value->cashvalue;
            $obj->processname .= " كاش= " . $value->cashvalue . "  &nbsp&nbsp";
        }
        if ($value->card == 1) {
            $amount += $value->cardvalue;
            $obj->processname .= " بنك= " . $value->cardvalue . "  &nbsp&nbsp";
        }
        if ($value->waitvalue > 0) {
            $obj->processname .= " اجل= " . $value->waitvalue;
        }

        $obj->processname .= " )";

        $obj->savedailychangeamount = $amount;
        $obj->savedailychangetype = 1;
        $obj->savedailymodelid = $value->id;
        $obj->savedailysaveafter = 0;
        $obj->savedailydate = substr($value->billdate, 0, 10);
        $obj->userid = $value->userid;
        $obj->tablename = "bills.php?do=buybill";
        $obj->finalstring = "";
        $mysavedata = $mySaveRecord->load($value->saveid);
        $obj->savename = $mysavedata->savename;
        $obj->link = "nosave";
        array_push($savedailyData, $obj);
    }

    $changeAmountSum = 0;
    ##for OperationName list by if
    list($suppDebtChangeIdsArr, $buyIdsArr, $retBuyIdsArr, $buyAndRetIdsArr,
            $clientDebtChangeIdsArr, $retSellIdsArr, $sellIdsArr, $sellAndRetIdsArr, $expensesIdsArr, $incomeIdsArr,
            $partnerwithdrawalidsArr, $employeePersonelIdsArr, $clientidsArrSaveDaily, $useridsArrSaveDaily) = [[], [], [], [], [], [], [], [], [], [], [], [], [], []];
    foreach ($allMovements as $value) {
        $clientidsArrSaveDaily[] = $value->clientid;
    }
    foreach ($savedailyData as $data) {
        //define table names to redirect to the right file
        $tablename = $data->tablename;
        //get sum for today
        if ($tablename == "supplierPayedDeptController.php" || $tablename == "clientPayedDeptController.php") {
            //do nothing
            if ($data->savedailychangetype == 0) {//plus
                $changeAmountSum += $data->savedailychangeamount;
            } else if ($data->savedailychangetype == 1) {//minus
                $changeAmountSum -= $data->savedailychangeamount;
            }
        } else {
            if ($data->savedailychangetype == 0) {//plus
                if ($data->savedailychangeamount > 0) {
                    $changeAmountSum += $data->savedailychangeamount;
                } else {
                    $changeAmountSum += ($data->savedailychangeamount) * -1;
                    $data->savedailychangeamount = $data->savedailychangeamount * -1;
                }
            } else if ($data->savedailychangetype == 1) {//minus
                if ($data->savedailychangeamount > 0) {
                    $changeAmountSum -= $data->savedailychangeamount;
                } else {
                    $changeAmountSum -= ($data->savedailychangeamount) * -1;
                    $data->savedailychangeamount = $data->savedailychangeamount * -1;
                }
            }
        }


        ##for OperationName list by if
        switch ($tablename) {
            case "supplierPayedDeptController.php":
            case "supplierDeficitController.php":
                $suppDebtChangeIdsArr[] = $data->savedailymodelid;
                break;
            case "clientPayedDeptController.php":
            case "clientDeficitController.php":
                $clientDebtChangeIdsArr[] = $data->savedailymodelid;
                break;
            //
            case "returnsellbillController.php":
            case "clientPayedDeptReturnSellBillsController.php":
                $retSellIdsArr[] = $data->savedailymodelid;
                break;
            case "sellbillController.php":
            case "clientPayedDeptSellBillsController.php":
                $sellIdsArr[] = $data->savedailymodelid;
                break;
            case "sellbillandruternController.php":
                $sellAndRetIdsArr[] = $data->savedailymodelid;
                break;
            //
            case "partnerwithdrawalController.php":
                $partnerwithdrawalidsArr[] = $data->savedailymodelid;
                break;
            case "expensesController.php":
                $expensesIdsArr[] = $data->savedailymodelid;
                break;
            case "incomeController.php":
                $incomeIdsArr[] = $data->savedailymodelid;
                break;
            //
            case "buyBillController.php":
                $buyIdsArr[] = $data->savedailymodelid;
                break;
            case "buyAndReturnBillController.php":
                $buyAndRetIdsArr[] = $data->savedailymodelid;
                break;
            case "returnBuyBillController.php":
                $retBuyIdsArr[] = $data->savedailymodelid;
                break;
            case "employeePersonalController.php":
                $employeePersonelIdsArr[] = $data->savedailymodelid;
                break;
        }
        $clientidsArrSaveDaily[] = $data->clientid;
        $useridsArrSaveDaily[] = $data->userid;
    }
    $suppDebtChangeIdsArr = !empty($suppDebtChangeIdsArr) ? array_unique($suppDebtChangeIdsArr) : [0];
    $buyIdsArr = !empty($buyIdsArr) ? array_unique($buyIdsArr) : [0];
    $retBuyIdsArr = !empty($retBuyIdsArr) ? array_unique($retBuyIdsArr) : [0];
    $buyAndRetIdsArr = !empty($buyAndRetIdsArr) ? array_unique($buyAndRetIdsArr) : [0];
    $clientDebtChangeIdsArr = !empty($clientDebtChangeIdsArr) ? array_unique($clientDebtChangeIdsArr) : [0];
    $retSellIdsArr = !empty($retSellIdsArr) ? array_unique($retSellIdsArr) : [0];
    $sellIdsArr = !empty($sellIdsArr) ? array_unique($sellIdsArr) : [0];
    $sellAndRetIdsArr = !empty($sellAndRetIdsArr) ? array_unique($sellAndRetIdsArr) : [0];
    $expensesIdsArr = !empty($expensesIdsArr) ? array_unique($expensesIdsArr) : [0];
    $incomeIdsArr = !empty($incomeIdsArr) ? array_unique($incomeIdsArr) : [0];
    $partnerwithdrawalidsArr = !empty($partnerwithdrawalidsArr) ? array_unique($partnerwithdrawalidsArr) : [0];
    $employeePersonelIdsArr = !empty($employeePersonelIdsArr) ? array_unique($employeePersonelIdsArr) : [0];
    $clientidsArrSaveDaily = !empty($clientidsArrSaveDaily) ? array_unique($clientidsArrSaveDaily) : [0];
    $useridsArrSaveDaily = !empty($useridsArrSaveDaily) ? array_unique($useridsArrSaveDaily) : [0];


    /* ==============================================رصيد صافى=============================================== */
    if ($bure == "1") {




        $smarty->assign('burex', $bure);
        foreach ($savedailyData as $data) {
            if ($data->savedailyid != -1) {


                $finalstring = $data->finalstring;

                $type = $data->savedailychangetype;
                $savedailyid = $data->savedailyid;



                if ($type == 1) {

                    $otherfinal = substr_replace($finalstring, '0', -1);


                    //now for one type = -1 ,remove one row not all posibilities as it would be wrong like edit expenses for example
                    $flag = checkFunc($savedailyData, $data, $otherfinal);
                    if ($flag != -1) {
                        $savedailyData[$flag]->savedailyid = -1;
                        $data->savedailyid = -1;
                    }
                }
            }
        }
    }

    list($clientIdsArr, $supplierIdsArr) = [[], []];
    ##for OperationName list by if ##get data
    ##sql for operation name
    //
    $suppDebtChangeData = R::getAll('SELECT supplierdebtchangeid,supplierid
		FROM supplierdebtchange
		WHERE supplierdebtchangeid in(' . implode(',', $suppDebtChangeIdsArr) . ')');
    $suppDebtChangeData = customArrayIndexOne($suppDebtChangeData, 'supplierdebtchangeid');
    foreach ($suppDebtChangeData as $value) {
        $supplierIdsArr[] = $value['supplierid'];
    }
    //
    $clientDebtChangeData = R::getAll('SELECT clientdebtchangeid,clientid
		FROM clientdebtchange
		WHERE clientdebtchangeid in(' . implode(',', $clientDebtChangeIdsArr) . ')');
    $clientDebtChangeData = customArrayIndexOne($clientDebtChangeData, 'clientdebtchangeid');
    foreach ($clientDebtChangeData as $value) {
        $clientIdsArr[] = $value['clientid'];
    }
    //
    $retSellData = R::getAll('SELECT returnsellbillid, returnsellbillclientid as clientid
		 FROM returnsellbill
		 WHERE returnsellbillid in(' . implode(',', $retSellIdsArr) . ')');
    $retSellData = customArrayIndexOne($retSellData, 'returnsellbillid');
    foreach ($retSellData as $value) {
        $clientIdsArr[] = $value['clientid'];
    }
    //
    $sellData = R::getAll('SELECT sellbillid, sellbillclientid as clientid
		 FROM sellbill
		 WHERE sellbillid in(' . implode(',', $sellIdsArr) . ')');
    $sellData = customArrayIndexOne($sellData, 'sellbillid');
    foreach ($sellData as $value) {
        $clientIdsArr[] = $value['clientid'];
    }
    //
    $sellAndRetData = R::getAll('SELECT sellbillid, sellbillclientid as clientid
		 FROM sellbillandrutern
                 JOIN client ON sellbillandrutern.sellbillclientid = client.clientid
		 WHERE sellbillandrutern.sellbillid in(' . implode(',', $sellAndRetIdsArr) . ')');
    $sellAndRetData = customArrayIndexOne($sellAndRetData, 'sellbillid');
    foreach ($sellAndRetData as $value) {
        $clientIdsArr[] = $value['clientid'];
    }
    //
    $partnerwithdrawalData = R::getAll('SELECT partnerwithdrawalid, partner.partnername
			 FROM partnerwithdrawal JOIN partner
			 ON partnerwithdrawal.partnerid = partner.partnerid
			 where partner.conditions = 0
			 and partnerwithdrawalid in(' . implode(',', $partnerwithdrawalidsArr) . ')');
    $partnerwithdrawalData = customArrayIndexOne($partnerwithdrawalData, 'partnerwithdrawalid');
    //
    $expensesData = R::getAll('SELECT expensesid,expensesname FROM expenses WHERE expensesid in(' . implode(',', $expensesIdsArr) . ')');
    $expensesData = customArrayIndexOne($expensesData, 'expensesid');
    //
    $incomeData = R::getAll('SELECT incomeId,incomeName FROM income WHERE incomeId in(' . implode(',', $incomeIdsArr) . ')');
    $incomeData = customArrayIndexOne($incomeData, 'incomeId');
    //
    $buyData = R::getAll('SELECT buybillid, buybillsupplierid as supplierid
		 FROM buybill
		 WHERE buybillid in(' . implode(',', $buyIdsArr) . ')');
    $buyData = customArrayIndexOne($buyData, 'buybillid');
    foreach ($buyData as $value) {
        $supplierIdsArr[] = $value['supplierid'];
    }
    //
    $buyAndRetData = R::getAll('SELECT buybillid, buybillsupplierid as supplierid
		 FROM buyandruternbill
		 WHERE buybillid in(' . implode(',', $buyAndRetIdsArr) . ')');
    $buyAndRetData = customArrayIndexOne($buyAndRetData, 'buybillid');
    foreach ($buyAndRetData as $value) {
        $supplierIdsArr[] = $value['supplierid'];
    }
    //
    $retBuyData = R::getAll('SELECT returnbuybillid, returnbuybillsupplierid as supplierid
		 FROM returnbuybill
		 WHERE returnbuybillid in(' . implode(',', $retBuyIdsArr) . ')');
    $retBuyData = customArrayIndexOne($retBuyData, 'returnbuybillid');
    foreach ($retBuyData as $value) {
        $supplierIdsArr[] = $value['supplierid'];
    }

    //
    $employeePersonelData = R::getAll('SELECT employeepersonnelid,employeeName
                 FROM employeepersonnel
                 join employee on  employee.employeeId = employeepersonnel.employeeid
                 WHERE employeepersonnelid in(' . implode(',', $employeePersonelIdsArr) . ')');
    $employeePersonelData = customArrayIndexOne($employeePersonelData, 'employeepersonnelid');


    $clientidsArrSaveDaily = array_merge($clientidsArrSaveDaily, $clientIdsArr);
    $clientidsArrSaveDaily = !empty($clientidsArrSaveDaily) ? array_unique($clientidsArrSaveDaily) : [0];

    $suppDebtChangeIdsArr = array_merge($suppDebtChangeIdsArr, $supplierIdsArr);
    $suppDebtChangeIdsArr = !empty($suppDebtChangeIdsArr) ? array_unique($suppDebtChangeIdsArr) : [0];
    ##
    $clientData = R::getAll('select clientid,clientname from client where clientid in(' . implode(',', $clientidsArrSaveDaily) . ') ');
    $clientData = customArrayIndexOne($clientData, 'clientid');

    $supplierData = R::getAll('select supplierid,suppliername from supplier where supplierid in(' . implode(',', $suppDebtChangeIdsArr) . ') ');
    $supplierData = customArrayIndexOne($supplierData, 'supplierid');

    $userSaveDailyData = R::getAll('SELECT userid,employeename FROM user WHERE userid in(' . implode(',', $useridsArrSaveDaily) . ') ');
    $userSaveDailyData = customArrayIndexOne($userSaveDailyData, 'clientid');


    //get client name
    foreach ($allMovements as $value) {
        $value->clientName = $clientData[$value->clientid]['clientname'];
    }

    $ii = 0;
    //select all data from storemovement
    $startbefore = array();
    $startafter = array();
    foreach ($savedailyData as $mov) {

        //$mov->savecurrentvalue = operationName($mov);
        $mov->savecurrentvalue = 0;
        switch ($mov->tablename) {
            case "supplierPayedDeptController.php":
            case "supplierDeficitController.php":
                $mov->savecurrentvalue = $supplierData[$suppDebtChangeData[$mov->savedailymodelid]['supplierid']]['suppliername'];
                break;
            case "clientPayedDeptController.php":
            case "clientDeficitController.php":
                $mov->savecurrentvalue = $clientData[$clientDebtChangeData[$mov->savedailymodelid]['clientid']]['clientname'];
                break;
            //
            case "returnsellbillController.php":
            case "clientPayedDeptReturnSellBillsController.php":
                $mov->savecurrentvalue = $clientData[$retSellData[$mov->savedailymodelid]['clientid']]['clientname'];
                break;
            case "sellbillController.php":
            case "clientPayedDeptSellBillsController.php":
                $mov->savecurrentvalue = $clientData[$sellData[$mov->savedailymodelid]['clientid']]['clientname'];
                break;
            case "sellbillandruternController.php":
                $mov->savecurrentvalue = $clientData[$sellAndRetData[$mov->savedailymodelid]['clientid']]['clientname'];
                break;
            //
            case "partnerwithdrawalController.php":
                $mov->savecurrentvalue = $partnerwithdrawalData[$mov->savedailymodelid]['partnername'];
                break;
            case "expensesController.php":
                $mov->savecurrentvalue = $expensesData[$mov->savedailymodelid]['expensesname'];
                break;
            case "incomeController.php":
                $mov->savecurrentvalue = $incomeData[$mov->savedailymodelid]['incomeName'];
                break;
            //
            case "buyBillController.php":
                $mov->savecurrentvalue = $supplierData[$buyData[$mov->savedailymodelid]['supplierid']]['suppliername'];
                break;
            case "buyAndReturnBillController.php":
                $mov->savecurrentvalue = $supplierData[$buyAndRetData[$mov->savedailymodelid]['supplierid']]['suppliername'];
                break;
            case "returnBuyBillController.php":
                $mov->savecurrentvalue = $supplierData[$retBuyData[$mov->savedailymodelid]['supplierid']]['suppliername'];
                break;
            case "employeePersonalController.php":
                $mov->savecurrentvalue = $employeePersonelData[$mov->savedailymodelid]['employeeName'];
                break;
        }


        ////
        if ($mov->savedailyid > 0) {
            //if($bure=="1" && $mov->savedailyid > 0 ){
            //print_r('mov->tablename--------------' . $mov->tablename . '<br>');
            if ($db == '') {
                $mytable = $mov->tablename;
                if (!isset($startbefore[$mov->saveid])) {
                    $startbefore[$mov->saveid] = $mov->savedailysavebefore;
                    $startafter[$mov->saveid] = $mov->savedailysaveafter;
                } else {

                    $changeamount = $mov->savedailychangeamount;
                    $mov->savedailysavebefore = $startafter[$mov->saveid];
                    if ($mov->savedailychangetype == "1") {

                        //# m7md
                        if ($db == '') {
                            if ($mov->tablename == 'returnsellbillController.php' || $mov->tablename == 'billsreturn.php') {

                                $mov->savedailysaveafter = $mov->savedailysavebefore - abs($changeamount);
                            } else {
                                $mov->savedailysaveafter = $mov->savedailysavebefore - $changeamount;
                            }
                            $startbefore[$mov->saveid] = $mov->savedailysavebefore;
                            $startafter[$mov->saveid] = $mov->savedailysaveafter;
                        }
                    } else {

                        //# checked by m7md
                        if ($db == '') {
                            if ($mov->tablename == 'returnBuyBillController.php') {
                                $mov->savedailysaveafter = $mov->savedailysavebefore + abs($changeamount);
                            } else {
                                $mov->savedailysaveafter = $mov->savedailysavebefore + $changeamount;
                            }
                            $startbefore[$mov->saveid] = $mov->savedailysavebefore;
                            $startafter[$mov->saveid] = $mov->savedailysaveafter;
                        }
                    }


                    //new product name with all path
                }
            }
            //# m7md .
            //$user_dara = $myUserRecord->load($mov->userid);
            $mov->userName = $userSaveDailyData[$mov->userid]['employeename']; //$user_dara->username;
            if ($mov->clientid > 0 && empty($mov->savecurrentvalue)) {
                //$client_data = $clientDAO->load($mov->clientid);
                $mov->personName = $clientData[$mov->clientid]['employeename']; //$client_data->clientname;
            }



            $ii++;
        }
    }




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

        if ((isset($_POST["showbyday"]) && $_POST["showbyday"] == 1) || $do == "show3") {
            $savedailyData = showByDay($savedailyData);
        }



        $smarty->assign('savedailyData', $savedailyData);
        $smarty->assign('changeAmountSum', $changeAmountSum);
        $smarty->assign('sumValue', $sumValue);

        #
        $smarty->assign('allMovements', $allMovements);

        return array("savePayments" => $savedailyData, "bankPayments" => $allMovements);
    }
}

function checkFunc($savedailyData, $data, $otherfinal) {
    $i = 0;
    foreach ($savedailyData as $xx) {

        if ($xx->finalstring == $otherfinal && $xx->savedailyid != -1) {



            $xx->savedailyid = -1;
            $data->savedailyid = -1;
            return $i;
        }
        $i++;
    }
    return -1;
}

function showByDay($savedailyData) {
    global $smarty;
    $dateArr = array();
//    $k = 0;
//    $j = 0;
    foreach ($savedailyData as $savedaily) {
//        if ($savedaily->savedailychangetype == 0) {
//            $j+=$savedaily->savedailychangeamount;
//        } elseif ($savedaily->savedailychangetype == 1 && $savedaily->tablename == "returnsellbillController.php") {
//            $k-=$savedaily->savedailychangeamount;
//        } else {
//            $k+=$savedaily->savedailychangeamount;
//        }
        //get sum for today
        $changeAmountSum = 0;
        if ($savedaily->savedailychangetype == 0) {//plus
            if ($savedaily->savedailychangeamount > 0) {
                $changeAmountSum += $savedaily->savedailychangeamount;
            } else {
                $changeAmountSum -= $savedaily->savedailychangeamount;
            }
        } else if ($savedaily->savedailychangetype == 1) {//minus
            if ($savedaily->savedailychangeamount > 0) {
                $changeAmountSum -= $savedaily->savedailychangeamount;
            } else {
                $changeAmountSum += $savedaily->savedailychangeamount;
            }
        }
        //
        if (!isset($dateArr[$savedaily->savedailydate])) {
            $dateArr[$savedaily->savedailydate] = $changeAmountSum;
        } else {
            $dateArr[$savedaily->savedailydate] += $changeAmountSum;
        }
    }

//    $smarty->assign('k', $k);
//    $smarty->assign('j', $j);


    return $dateArr;
}

function getOpticData($saveId, $startDate, $endDate, $cash, $insurance, $network) {
    global $billsEX;
    global $billsBuyEX;
    global $billsReturnEX;
    global $billsData;
    global $billsRetData;
    global $billsBuyData;
    $queryString = '';
    if (isset($saveId) && $saveId > 0) {
        $queryString .= ' and saveid = ' . $saveId;
    }
    if (isset($startDate) && !empty($startDate)) {
        $queryString .= " and billdate >= '" . $startDate . "'";
    }
    if (isset($endDate) && !empty($endDate)) {
        $queryString .= " and billdate <= '" . $endDate . "'";
    }
    if ($cash == 1 || $insurance == 1 || $network == 1) {
        $queryString .= " and (";
        if ($cash == 1) {
            $queryString .= " cash = 1 ";
        }
        if ($cash == 1 && $insurance == 1)
            $queryString .= " or ";
        if ($insurance == 1) {
            $queryString .= " insurance = 1 ";
        }
        if (($cash == 1 || $insurance == 1) && $network == 1)
            $queryString .= " or ";
        if ($network == 1) {
            $queryString .= " card = 1 ";
        }
        $queryString .= " ) ";
    }
    $billsData = $billsEX->queryAllNotDelWithQuerySrting($queryString);
    $queryString2 = '';
    if (isset($saveId) && $saveId > 0) {
        $queryString2 .= ' and bills.saveid = ' . $saveId;
    }
    if (isset($startDate) && !empty($startDate)) {
        $queryString2 .= " and billsreturn.`date` >= '" . $startDate . "'";
    }
    if (isset($endDate) && !empty($endDate)) {
        $queryString2 .= " and billsreturn.`date` <= '" . $endDate . "'";
    }
    if ($cash == 1 || $insurance == 1 || $network == 1) {
        $queryString2 .= " and (";
        if ($cash == 1) {
            $queryString2 .= " bills.cash = 1 ";
        }
        if ($cash == 1 && $insurance == 1)
            $queryString2 .= " or ";
        if ($insurance == 1) {
            $queryString2 .= " bills.insurance = 1 ";
        }
        if (($cash == 1 || $insurance == 1) && $network == 1)
            $queryString2 .= " or ";
        if ($network == 1) {
            $queryString2 .= " bills.card = 1 ";
        }
        $queryString2 .= " ) ";
    }
    $billsRetData = $billsReturnEX->queryAllNotDelWithQuerySrting($queryString2);
    $queryString = '';
    if (isset($saveId) && $saveId > 0) {
        $queryString .= ' and saveid = ' . $saveId;
    }
    if (isset($startDate) && !empty($startDate)) {
        $queryString .= " and Date(billdate) >= '" . $startDate . "'";
    }
    if (isset($endDate) && !empty($endDate)) {
        $queryString .= " and Date(billdate) <= '" . $endDate . "'";
    }
    if ($cash == 1 || $insurance == 1 || $network == 1) {
        $queryString .= " and (";
        if ($cash == 1) {
            $queryString .= " cash = 1 ";
        }
        if ($cash == 1 && $insurance == 1)
            $queryString .= " or ";
        if ($insurance == 1) {
            $queryString .= " insurance = 1 ";
        }
        if (($cash == 1 || $insurance == 1) && $network == 1)
            $queryString .= " or ";
        if ($network == 1) {
            $queryString .= " card = 1 ";
        }
        $queryString .= " ) ";
    }
    $billsBuyData = $billsBuyEX->queryAllNotDelWithQuerySrting($queryString);
}

function operationName($data) {
    global $mySavedailyRecord;
    global $mySavedailyEx;
    global $mySaveRecord;
    global $clientDAO;
    global $supplierDAO;
    global $supplierExt;
    global $clientDeptChangeExt;
    global $ExpenseDAO;
    global $incomeDAO;
    global $empDao;
    global $EmployeepersonnelDAO;
    global $sellBillExt;
    global $mySellbillandruternEx;
    global $myPartnerwithdrawalEx;
    global $buyBillExt;
    global $buyAndReturnBillExt;
    global $returnBuyBillExt;
    global $billsReturnDAO;
    global $returnSellBillExt;

    //define table names to redirect to the right file
    $tablename = $data->tablename;

    if ($tablename == "supplierPayedDeptController.php" || $tablename == "supplierDeficitController.php" || $tablename == "supplierDeficitController.php") {
        $supplierData = $supplierExt->loadSupplierBySupplierdebtchangeId($data->savedailymodelid); //supplierdebtchangeid
        if (count($supplierData) > 0) {
            $personName = $supplierData->suppliername;
        }
    } elseif ($tablename == "clientPayedDeptController.php" || $tablename == "clientDeficitController.php") {
        $clientData = $clientDeptChangeExt->getClientName($data->savedailymodelid); //clientdebtchangeid
        if (count($clientData) > 0) {
            $personName = $clientData->clientname;
        }
    } elseif ($tablename == "returnsellbillController.php") {


        $clientData = $returnSellBillExt->loadReturnsellbillById($data->savedailymodelid); //clientdebtchangeid
        if (count($clientData) > 0) {
            $personName = $clientData->clientname;
        }
    } elseif ($tablename == "sellbillController.php") {


        $clientData = $sellBillExt->loadSellBillById($data->savedailymodelid); //clientdebtchangeid
        if (count($clientData) > 0) {
            $personName = $clientData->clientname;
        }
    } elseif ($tablename == "sellbillandruternController.php") {


        $clientData = $mySellbillandruternEx->loadSellbillandruternById($data->savedailymodelid); //clientdebtchangeid
        if (count($clientData) > 0) {
            $personName = $clientData->clientname;
        }
    } elseif ($tablename == "partnerwithdrawalController.php") {


        $clientData = $myPartnerwithdrawalEx->loadPartnerwithdrawalById($data->savedailymodelid);
        if (count($clientData) > 0) {
            $personName = $clientData->partnername;
        }
    } elseif ($tablename == "expensesController.php") {


        $clientData = $ExpenseDAO->load($data->savedailymodelid);
        if (count($clientData) > 0) {
            $personName = $clientData->expensesname;
        }
    } elseif ($tablename == "incomeController.php") {


        $clientData = $incomeDAO->load($data->savedailymodelid);
        if (count($clientData) > 0) {
            $personName = $clientData->incomeName;
        }
    } elseif ($tablename == "buyBillController.php") {
        $supplierData = $buyBillExt->loadExt($data->savedailymodelid); //supplierdebtchangeid
        if (count($supplierData) > 0) {
            $personName = $supplierData->suppliername;
        }
    } elseif ($tablename == "buyAndReturnBillController.php") {
        $supplierData = $buyAndReturnBillExt->loadExt($data->savedailymodelid); //supplierdebtchangeid
        if (count($supplierData) > 0) {
            $personName = $supplierData->suppliername;
        }
    } elseif ($tablename == "returnBuyBillController.php") {
        $supplierData = $returnBuyBillExt->loadExt($data->savedailymodelid); //supplierdebtchangeid
        if (count($supplierData) > 0) {
            $personName = $supplierData->suppliername;
        }
    } elseif ($tablename == "bills.php") {
        $billsData = $billsEX->loadExt($data->savedailymodelid); //clientdebtchangeid
        if (count($billsData) > 0) {
            $personName = $billsData->clientname;
        }
    } elseif ($tablename == "billsreturn.php") {
        $billsreturnData = $billsReturnDAO->load($data->savedailymodelid); //clientdebtchangeid
        $billsData = $billsEX->loadExt($billsreturnData->billid);

        if (count($billsData) > 0) {
            $personName = $billsData->clientname;
        }
    } elseif ($tablename == "employeePersonalController.php") {

        $employeepersonnelData = $EmployeepersonnelDAO->load($data->savedailymodelid); //clientdebtchangeid
        $empData = $empDao->load($employeepersonnelData->employeeid);

        if (count($empData) > 0) {
            $personName = $empData->employeeName;
        }
    } else {
        $personName = 0;
    }

    return $personName;
}

function getRoyalData($savedailyData, $allMovements) {

    list($billIDs, $userIDs) = [[], []];
    foreach ($savedailyData as $value) {
        $billIDs[] = $value->savedailymodelid;
        $userIDs[] = $value->userid;
    }
    foreach ($allMovements as $value) {
        $billIDs[] = $value->accountmovementmodelid;
        $userIDs[] = $value->userid;
    }

    $billIDs = !empty($billIDs) ? array_unique($billIDs) : [0];
    $userIDs = !empty($userIDs) ? array_unique($userIDs) : [0];
    ##getting bills
    $sellbillData = R::getAll('SELECT sellbillid,obygyVisitId as visitid
                                   FROM sellbill where sellbillid in(' . implode(',', $billIDs) . ')'); //. ' ORDER BY sellbilldate desc ,sellbillid desc '
    $sellbillData = customArrayIndexOne($sellbillData, 'sellbillid');
    ##getting userIds@royal
    $userData = R::getAll('SELECT userid,obygyDoctorId as royaluserid
                                   FROM user where userid in(' . implode(',', $userIDs) . ')'); //. ' ORDER BY sellbilldate desc ,sellbillid desc '
    $userData = customArrayIndexOne($userData, 'userid');

    foreach ($savedailyData as $value) {
        $value->obygyVisitId = $sellbillData[$value->savedailymodelid]['visitid'];
        $value->obygyUserId = $userData[$value->userid]['royaluserid'];
    }
    foreach ($allMovements as $value) {
        $value->obygyVisitId = $sellbillData[$value->accountmovementmodelid]['visitid'];
        $value->obygyUserId = $userData[$value->userid]['royaluserid'];
    }


    return array($savedailyData, $allMovements);
}

?>