<?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
include("../public/include_dao.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');
//// ################### بداية المبيعات
//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');
//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.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');
//Returnsellbilldetail
require_once('../models/dao/ReturnsellbilldetailDAO.class.php');
require_once('../models/dto/Returnsellbilldetail.class.php');
require_once('../models/mysql/ReturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbilldetailMySqlExtDAO.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');
//Sellandruternbilldetail
require_once('../models/dao/SellandruternbilldetailDAO.class.php');
require_once('../models/dto/Sellandruternbilldetail.class.php');
require_once('../models/mysql/SellandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellandruternbilldetailMySqlExtDAO.class.php');
//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.class.php');
//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.class.php');
//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.class.php');
//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');
//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.class.php');
//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');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');
//Unit
require_once('../models/dao/UnitDAO.class.php');
require_once('../models/dto/Unit.class.php');
require_once('../models/mysql/UnitMySqlDAO.class.php');
require_once('../models/mysql/ext/UnitMySqlExtDAO.class.php');
//Productserial
require_once('../models/dao/ProductserialDAO.class.php');
require_once('../models/dto/Productserial.class.php');
require_once('../models/mysql/ProductserialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductserialMySqlExtDAO.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');
//Soldserialproduct
require_once('../models/dao/SoldserialproductDAO.class.php');
require_once('../models/dto/Soldserialproduct.class.php');
require_once('../models/mysql/SoldserialproductMySqlDAO.class.php');
require_once('../models/mysql/ext/SoldserialproductMySqlExtDAO.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');
//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.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');
//Returnbuybilldetail
require_once('../models/dao/ReturnbuybilldetailDAO.class.php');
require_once('../models/dto/Returnbuybilldetail.class.php');
require_once('../models/mysql/ReturnbuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybilldetailMySqlExtDAO.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');
//Buyandruternbilldetail
require_once('../models/dao/BuyandruternbilldetailDAO.class.php');
require_once('../models/dto/Buyandruternbilldetail.class.php');
require_once('../models/mysql/BuyandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbilldetailMySqlExtDAO.class.php');
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');
//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.class.php');
//expense
require_once('../models/dao/ExpensesDAO.class.php');
require_once('../models/dto/Expense.class.php');
require_once('../models/mysql/ExpensesMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensesMySqlExtDAO.class.php');
//Currency
require_once('../models/dao/CurrencyDAO.class.php');
require_once('../models/dto/Currency.class.php');
require_once('../models/mysql/CurrencyMySqlDAO.class.php');
require_once('../models/mysql/ext/CurrencyMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');
//get the do the action
$do = $_GET['do'];

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

  Controller Name :-

  OPERTATION in Controller

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


//here goes the instances and general variables
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
$Expense = new Expense();
$ExpenseExt = new ExpensesMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Usergroup
$userGroup = new Usergroup();
$userGroupDAO = new UsergroupMySqlDAO();
$userGroupExt = new UsergroupMySqlExtDAO();
//User
$user = new User();
$userDAO = new UserMySqlDAO();
$userExt = new UserMySqlExtDAO();
//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

//Unit
$unit = new Unit();
$unitDAO = new UnitMySqlDAO();

//Supplier
$mySupplierRecord = new SupplierMySqlDAO();
$mySupplierEx = new SupplierMySqlExtDAO();

$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();

$mySaveRecord = new SaveMySqlDAO();

//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

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

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

//// ################### بداية المبيعات
//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();
//Sellbilldetail
$mySellbilldetail = new Sellbilldetail();
$mySellbilldetailRecord = new SellbilldetailMySqlDAO();
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();
//Returnsellbill
$myReturnsellbill = new Returnsellbill();
$myReturnsellbillRecord = new ReturnsellbillMySqlDAO();
$myReturnsellbillEx = new ReturnsellbillMySqlExtDAO();
//Returnsellbilldetail
$myReturnsellbilldetail = new Returnsellbilldetail();
$myReturnsellbilldetailRecord = new ReturnsellbilldetailMySqlDAO();
$myReturnsellbilldetailEX = new ReturnsellbilldetailMySqlExtDAO();

//Sellbillandrutern
$mySellbillandrutern = new Sellbillandrutern();
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
//Sellandruternbilldetail
$mySellandruternbilldetail = new Sellandruternbilldetail();
$mySellandruternbilldetailRecord = new SellandruternbilldetailMySqlDAO();
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();
//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();
//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();

//Product
$myProductRecord = new ProductMySqlDAO();
$myProductEx = new ProductMySqlExtDAO();
//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Client
$myClientRecord = new ClientMySqlDAO();
$myClient = new Client();
$myClientEx = new ClientMySqlExtDAO();
//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();
//Billname
$myBillnameRecord = new BillnameMySqlDAO();
$myBillnameEx = new BillnameMySqlExtDAO();
//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();
//User
$myUserEx = new UserMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//Productcat
$myProductcatRecord = new ProductcatMySqlDAO();
$myProductcatEx = new ProductcatMySqlExtDAO();
//Unit
$myUnitRecord = new UnitMySqlDAO();
//Productserial
$myProductserial = new Productserial();
$myProductserialEx = new ProductserialMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Soldserialproduct
$soldSerialProduct = new Soldserialproduct();
$soldSerialProductDAO = new SoldserialproductMySqlDAO();
$soldSerialProductExt = new SoldserialproductMySqlExtDAO();
//
$myUserGroupRecord = new UsergroupMySqlDAO();


$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();

//###################### بداية المشتريات
//Buybill
$buyBill = new Buybill();
$buyBillDAO = new BuybillMySqlDAO();
$buyBillExt = new BuybillMySqlExtDAO();
//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();
//Returnbuybilldetail
$returnBuyBillDetail = new Returnbuybilldetail();
$returnBuyBillDetailDAO = new ReturnbuybilldetailMySqlDAO();
$returnBuyBillDetailExt = new ReturnbuybilldetailMySqlExtDAO();
//Buyandruternbill
$buyAndReturnBill = new Buyandruternbill();
$buyAndReturnBillDAO = new BuyandruternbillMySqlDAO();
$buyAndReturnBillExt = new BuyandruternbillMySqlExtDAO();
//Buyandruternbilldetail
$buyAndReturnBillDetail = new Buyandruternbilldetail();
$buyAndReturnBillDetailDAO = new BuyandruternbilldetailMySqlDAO();
$buyAndReturnBillDetailExt = new BuyandruternbilldetailMySqlExtDAO();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDebtChange = new Supplierdebtchange();
$supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDebtChangeExt = new SupplierdebtchangeMySqlExtDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Billname
$billNameDAO = new BillnameMySqlDAO();
$billNameExt = new BillnameMySqlExtDAO();
//Billsetting
$billSettingExt = new BillsettingsMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport;
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Savedaily
$saveDaily = new Savedaily();
$saveDailyDAO = new SavedailyMySqlDAO();
$saveDailyExt = new SavedailyMySqlExtDAO();
//Productserial
$Productserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = new ProductserialMySqlExtDAO();

$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailDAO = new StoredetailMySqlDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//check and use the condition that suits this action
if (empty($do)) {
    $from = filter_input(INPUT_POST, "from");
    $to = filter_input(INPUT_POST, "to");
    if (isset($from) && !empty($from) && isset($to) && !empty($to)) {
        $today = $to;
        $yesterday = $from;
    } else {
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
    }

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

    $Programsetting = $ProgramsettingDAO->load(1);
    ################
//    $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) {
        $start = $startYesterday;
        $end = $endYesterday;
    } else {
        $start = $startToday;
        $end = $endToday;
    }
    ##############
    //# اجمالى الخزن

    search($_SESSION['saveid'], $processid, $start, $end);

    //# المبيعات
    showAll($start, $end);

    //# مردودات المبيعات
    returnshowAll($start, $end);

    //# تقرير فواتير المشتريات
    showBuyBill($start, $end);

    //# مردودات المشتريات
    showBuyReturn($start, $end);

    //# اجمالى التحصيل
    showx('-1', '-1', $start, $end);

    //# اجمالى الدفعات
    showxDofat('-1', $start, $end);

    //مديونية العملاء
    $totalclientdebt = clientdebt();
    $smarty->assign("totalclientdebt", $totalclientdebt);

    //مديونية الموردين
    $totalsupplierdebt = supplierdebt();
    $smarty->assign("totalsupplierdebt", $totalsupplierdebt);

    //# المخزون
    //totalproductinstores
    if ($generalSettings->showM5zon == 0) {
        $totalprice = totalproduct();
        $smarty->assign("totalprice", $totalprice);
    }
    $smarty->assign("showM5zon", $generalSettings->showM5zon);

    //expenses of day
    $totalExpense = (float) $ExpenseExt->getSumByQueryString(" and expenses.expensesdate >= '" . $start . "' and expenses.expensesdate <= '" . $end . "' ");
    $smarty->assign("totalExpense", $totalExpense);

    $smarty->display("operationstotalview/indexReport.html");
    //$smarty->display("indexReport/show.html");
}

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


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

function search($saveid, $processid, $startDate, $endDate) {

    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;

    $bure = $_POST["bure"];

    $queryString = ' WHERE';


    if (isset($saveid) && $saveid != '-1') {
        $mysavedata = $mySaveRecord->load($saveid);
        $message = "تقرير يوميه   " . $mysavedata->savename;
        $smarty->assign('message', $message);

        $sumValue = sumCreditById($saveid);
        //$queryString .= ' savedaily.saveid = ' . $saveid . ' AND';
    } else {

        $sumValue = sumCredit();
    }

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



        $queryString .= ' savedaily.processname = "' . $processid . '" AND';
        //$sumValue=sumCredit();
        //print_r($sumValue);
    }

    if (!empty($startDate) && !empty($endDate)) {
        $savedailyData2 = $mySavedailyEx->searchInAdsindex22($endDate);

        $message = "تقرير يوميه للخزينه من  " . $startDate . "  الى " . $endDate;
        $smarty->assign('message', $message);

        $queryString .= ' savedaily.savedailydate >= ("' . $startDate . '" ) AND savedaily.savedailydate <= ("' . $endDate . '") AND';
    }


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

    $savedailyData = $mySavedailyEx->searchInAdsindex11($queryString);


    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);
    }
    //	print_r($savedailyData2);
    $changeAmountSum = 0;
    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;
                }
            }
        }

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


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




        $smarty->assign('burex', $bure);
        foreach ($savedailyData as $data) {


            $finalstring = $data->finalstring;

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



            if ($type == 1) {

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

                foreach ($savedailyData as $xx) {

                    if ($xx->finalstring == $otherfinal) {



                        $xx->savedailyid = -1;
                        $data->savedailyid = -1;
                    }
                }
            }
        }
    }



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

        //print_r($mov);
        //	print_r('<br><br>');
        if ($mov->savedailyid > 0) {
            //if($bure=="1" && $mov->savedailyid > 0 ){
            //print_r('mov->tablename--------------' . $mov->tablename . '<br>');

            $mytable = $mov->tablename;
            if ($ii == 0) {
                //print_r('savedailychangeamount'.$mov->savedailychangeamount .'<br>');
                if ($mov->tablename == 'returnBuyBillController.php') {
                    $startvalue = $mov->savedailychangeamount;
                    $mov->savedailychangeamount = $startvalue;
                    $startbefore = $mov->savedailysavebefore;
                    $startafter = $mov->savedailysaveafter;
                    $mov->savedailysavebefore = $startbefore;
                    $mov->savedailysaveafter = $startafter;
                } else {

                    $startvalue = $mov->savedailychangeamount;
                    $mov->savedailychangeamount = $startvalue;
                    $startbefore = $mov->savedailysavebefore;
                    $mov->savedailysavebefore = $startbefore;
                    $startafter = $mov->savedailysaveafter;
                    $mov->savedailysaveafter = $startafter;
                }
            } else {

                $startvalue = $mov->savedailychangeamount;
                $mov->savedailysaveafter = $startbefore;

                if ($mov->savedailychangetype == "1") {


                    if ($mov->tablename == 'returnsellbillController.php') {

                        //print_r('mov->tablename--------------'.$mov->tablename .'<br>');
                        $mov->savedailysavebefore = $startbefore - $startvalue;
                        $startbefore = $startbefore - $startvalue;
                    } elseif ($mov->tablename == 'billsreturn.php') {

                        //print_r('mov->tablename--------------'.$mov->tablename .'<br>');
                        $mov->savedailysavebefore = $startbefore - $startvalue;
                        $startbefore = $startbefore - $startvalue;
                    } else {
                        $mov->savedailysavebefore = $startbefore + $startvalue;
                        $startbefore = $startbefore + $startvalue;
                    }
                } else {
                    //print_r('in else if<br>');
                    //print_r('startvalue'.$startbefore .'<br>');
                    //	print_r('mov->tablename--------------'.$mov->tablename .'<br>');
                    if ($mov->tablename == 'returnBuyBillController.php') {
                        //print_r('mov->tablename--------------'.$mov->tablename .'<br>');
                        $mov->savedailysavebefore = $startbefore + $startvalue;
                        $startbefore = $startbefore + $startvalue;
                    } else {
                        $mov->savedailysavebefore = $startbefore - $startvalue;
                        $startbefore = $startbefore - $startvalue;
                    }
                }


                //new product name with all path
            }

            //# m7md .
            $user_dara = $myUserRecord->load($mov->userid);
            $mov->userName = $user_dara->username;
            if ($mov->clientid > 0) {
                $client_data = $clientDAO->load($mov->clientid);
                $mov->personName = $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);
        return 0;
    }
}

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

//# المبيعات
function showAll($startDate, $endDate) {
    global $mySellbillEx;
    global $mySellbillandruternEx;
    global $myClientRecord;

    global $mySellandruternbilldetailEx;
    global $mySellbilldetailEx;

    global $smarty;




    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['sellbillid'];
    $clientId = $_REQUEST['clientid'];

    $message = '';
    $queryString = ' WHERE';
    $returnqueryString = ' WHERE';

    if (isset($clientId) && $clientId != '-1') {
        $messageData = $myClientRecord->load($clientId);
        $message = $message . '<br>' . "إسم العميل: " . $messageData->clientname;

        $queryString .= ' sellbillclientid = ' . $clientId . ' AND';
        $returnqueryString .= ' returnsellbill.returnsellbillclientid = ' . $clientId . ' AND';
    }

    if (isset($sellbillSerial) && $sellbillSerial != '') {

        showBySriral($sellbillSerial);

        $message = $message . '<br>' . "رقم الفاتورة: " . $sellbillSerial;

        $queryString .= ' sellbillSerial = "' . $sellbillSerial . '" AND';
        $returnqueryString .= ' returnsellbill.returnsellbillserial = "' . $sellbillSerial . '" AND';
    }

    if (isset($sellbillId) && $sellbillId != '') {
        showBySellbillId($sellbillId);
        $message = $message . '<br>' . "الرقم المتسلسل : " . $sellbillId;

        $queryString .= ' sellbillid = "' . $sellbillId . '" AND';
    }

    if (!empty($startDate) && !empty($endDate)) {

        $message = $message . '<br>' . 'من تاريخ : ' . $startDate . 'إلى تاريخ : ' . $endDate . '';

        $queryString .= ' sellbilldate >= "' . $startDate . '" AND sellbilldate <= "' . $endDate . '" AND';
    } elseif (empty($startDate) && empty($endDate) && empty($sellbillSerial) && empty($sellbillid) && !isset($clientId)) {
        //$today = date("Y-m-d");
        $startDate = date("Y-m-d") . " 00:00:00";
        $endDate = date("Y-m-d") . " 23:59:59";
        $message = $message . '<br>' . "من تاريخ : " . $startDate . " إلى تاريخ : " . $endDate . "";

        $queryString .= ' sellbilldate >= "' . $startDate . '" AND sellbilldate <= "' . $endDate . '" AND';
    }
    $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>");
    }






    $totalBills = 0;
    $totalQTY = 0;
    $totaltax = 0;
    $totaldiscount = 0;

    $sellbillData = $mySellbillEx->querybyqueryString($queryString);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
                $totalQTY += $sell->sellQuantity;
                $sell->type = "sell";


                //getalldiscount
                $sellbilldiscount = $sell->sellbilldiscount;
                $sellbilldiscounttype = $sell->sellbilldiscounttype; //1 مباشر
                $sellbilltotalbill = $sell->sellbilltotalbill;
                $sellbillaftertotalbill = $sell->sellbillaftertotalbill;
                $tax = $sell->tax;

                $detaildiscount = $mySellbilldetailEx->getsumdiscount($sell->sellbillid);
                if ($sellbilldiscounttype == 1) {


                    //discount
                    $totaldiscount = $totaldiscount + $sellbilldiscount + $detaildiscount;
                    $sell->sellbilldiscount = ($sellbilldiscount + $detaildiscount);




                    //tax
                    $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                } else {
                    //discount
                    $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
                    $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
                    $sell->sellbilldiscount = ($discountvalue + $detaildiscount);

                    //tax
                    $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                }
            }
        }
    }

    //get sell bills from sellbillandrutern table
    $sellbillandruternData = $mySellbillandruternEx->GetSellBillAndReturnUsingQueryString($queryString);

    if (count($sellbillandruternData) > 0) {
        foreach ($sellbillandruternData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
                $totalQTY += $sell->sellQuantity;
                $sell->type = "sellAndReturn";




                //getalldiscount
                $sellbilldiscount = $sell->sellbilldiscount;
                $sellbilldiscounttype = $sell->sellbilldiscounttype; //1 مباشر
                $sellbilltotalbill = $sell->sellbilltotalbill;
                $sellbillaftertotalbill = $sell->sellbillaftertotalbill;
                $tax = $sell->tax;

                $detaildiscount = $mySellandruternbilldetailEx->getsumdiscount($sell->sellbillid, 0);
                if ($sellbilldiscounttype == 1) {
                    //discount
                    $totaldiscount = $totaldiscount + $sellbilldiscount + $detaildiscount;
                    $sell->sellbilldiscount = ($sellbilldiscount + $detaildiscount);


                    //tax
                    $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                } else {
                    //discount
                    $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
                    $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
                    $sell->sellbilldiscount = ($discountvalue + $detaildiscount);
                    //tax
                    $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                }
            }
        }
    }

    $sellbillData = array_merge($sellbillData, $sellbillandruternData);

    $countSell = count($sellbillData);
    $smarty->assign('countSell', $countSell);

    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
    $smarty->assign('totalQTY', $totalQTY);
    $smarty->assign('totaldiscount', $totaldiscount);
    $smarty->assign('totaltax', $totaltax);
}

//# مردودات المبيعات
function returnshowAll($startDate, $endDate) {
    global $myReturnsellbillEx;
    global $myReturnsellbilldetailEX;
    global $myReturnsellbillEx;

    global $mySellbillandruternEx;
    global $mySellandruternbilldetailEx;
    global $mySellbilldetailEx;
    global $myClientRecord;

    global $smarty;


    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['sellbillid'];
    $clientId = $_REQUEST['clientid'];


    $message = '';
    $queryString = ' WHERE';
    $returnqueryString = ' WHERE';


    if (isset($clientId) && $clientId != '-1') {
        $messageData = $myClientRecord->load($clientId);
        $message = $message . '<br>' . "إسم العميل: " . $messageData->clientname;

        $queryString .= ' sellbillandrutern.sellbillclientid = ' . $clientId . ' AND';
        $returnqueryString .= ' returnsellbill.returnsellbillclientid = ' . $clientId . ' AND';
    }

    if (isset($sellbillSerial) && $sellbillSerial != '') {

        //showBySriral($sellbillSerial);

        $message = $message . '<br>' . "رقم الفاتورة: " . $sellbillSerial;

        $queryString .= ' sellbillandrutern.sellbillSerial = "' . $sellbillSerial . '" AND';
        $returnqueryString .= ' returnsellbill.returnsellbillserial = "' . $sellbillSerial . '" AND';
    }

    if (isset($sellbillId) && $sellbillId != '') {
        //	showBySellbillId($sellbillId);
        $message = $message . '<br>' . "الرقم المتسلسل : " . $sellbillId;

        $queryString .= ' sellbillandrutern.sellbillid = "' . $sellbillId . '" AND';
        $returnqueryString .= ' returnsellbill.returnsellbillid = ' . $sellbillId . ' AND';
    }

    if (!empty($startDate) && !empty($endDate)) {

        $message = $message . '<br>' . 'من تاريخ : ' . $startDate . 'إلى تاريخ : ' . $endDate . '';

        $queryString .= ' sellbillandrutern.sellbilldate >= "' . $startDate . '" AND sellbillandrutern.sellbilldate <= "' . $endDate . '" AND';
        $returnqueryString .= ' returnsellbill.returnsellbilldate >= "' . $startDate . '" AND returnsellbill.returnsellbilldate <= "' . $endDate . '" AND';
    } elseif (empty($startDate) && empty($endDate) && empty($sellbillSerial) && empty($sellbillid) && !isset($clientId)) {
        //$today = date("Y-m-d");
        $startDate = date("Y-m-d") . " 00:00:00";
        $endDate = date("Y-m-d") . " 23:59:59";
        $message = $message . '<br>' . "من تاريخ : " . $startDate . " إلى تاريخ : " . $endDate . "";

        $queryString .= ' sellbillandrutern.sellbilldate >= "' . $startDate . '" AND sellbillandrutern.sellbilldate <= "' . $endDate . '" AND';
        $returnqueryString .= ' returnsellbill.returnsellbilldate >= "' . $startDate . '" AND returnsellbill.returnsellbilldate <= "' . $endDate . '" AND';
        //	print_r($returnqueryString);
    }
    $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>");
    }



    $arr = explode(' ', $returnqueryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $returnqueryString = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            $returnqueryString = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }




    $totalBills = 0;
    $totalQTY = 0;
    $totaltax = 0;
    $totaldiscount = 0;


    $returnsellbillData = $myReturnsellbillEx->queryallWithqueryString2($returnqueryString);
    if (count($returnsellbillData) > 0) {
        foreach ($returnsellbillData as $sell) {

            if ($sell->conditions == 0) {
                $totalBills += $sell->returnsellbillaftertotalbill;
                $totalQTY += $sell->returnsellQuantity;
                $sell->type = "returnSell";



                //getalldiscount
                $sellbilldiscount = $sell->returnsellbilldiscount;
                $sellbilldiscounttype = $sell->returnsellbilldiscounttype; //1 مباشر
                $sellbilltotalbill = $sell->returnsellbilltotalbill;
                $sellbillaftertotalbill = $sell->returnsellbillaftertotalbill;
                $tax = $sell->tax;

                $detaildiscount = $myReturnsellbilldetailEX->getsumdiscount($sell->returnsellbillid);
                if ($sellbilldiscounttype == 1) {


                    //discount
                    $totaldiscount = $totaldiscount + $sellbilldiscount + $detaildiscount;
                    $sell->returnsellbilldiscount = ($sellbilldiscount + $detaildiscount);




                    //tax
                    $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                } else {
                    //discount
                    $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
                    $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
                    $sell->returnsellbilldiscount = ($discountvalue + $detaildiscount);

                    //tax
                    $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                }
            }
        }
    }

    //get return sell bills from sellbillandrutern table
    $sellbillandruternData = $mySellbillandruternEx->GetSellBillAndReturnUsingQueryString($queryString);
    //print_r($sellbillandruternData);

    if (count($sellbillandruternData) > 0) {
        foreach ($sellbillandruternData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
                $sell->returnsellbillid = $sell->sellbillid;
                $sell->returnsellbillaftertotalbill = $sell->sellbillaftertotalbill;
                $sell->returnsellbilldate = $sell->sellbilldate;
                $totalQTY += $sell->returnsellQuantity;
                $sell->type = "sellAndReturn";



                //getalldiscount
                $sellbilldiscount = $sell->sellbilldiscount;
                $sellbilldiscounttype = $sell->sellbilldiscounttype; //1 مباشر
                $sellbilltotalbill = $sell->sellbilltotalbill;
                $sellbillaftertotalbill = $sell->sellbillaftertotalbill;
                $tax = $sell->tax;

                $detaildiscount = $mySellandruternbilldetailEx->getsumdiscount($sell->sellbillid, 1);
                if ($sellbilldiscounttype == 1) {
                    //discount
                    $totaldiscount = $totaldiscount + $detaildiscount;
                    $sell->sellbilldiscount = $detaildiscount;


                    //tax
                    $taxvalue = 0; //$sellbillaftertotalbill-($sellbilltotalbill-($sellbilldiscount));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                } else {
                    //discount
                    //$discountvalue=($sellbilltotalbill/100)*$sellbilldiscount;
                    $totaldiscount = $totaldiscount + $detaildiscount;
                    $sell->sellbilldiscount = $detaildiscount;
                    //tax
                    $taxvalue = 0; //$sellbillaftertotalbill-($sellbilltotalbill-($discountvalue));
                    $totaltax = $totaltax + $taxvalue;
                    $sell->tax = $taxvalue;
                }
            }
        }
    }

    $returnsellbillData = array_merge($returnsellbillData, $sellbillandruternData);


    $countRetunSell = count($returnsellbillData);
    $smarty->assign('countRetunSell', $countRetunSell);

    // assign your db results to the template
    $smarty->assign('returnsellbillData', $returnsellbillData);
    $smarty->assign('returntotalBills', $totalBills);
    $smarty->assign('returntotalQTY', $totalQTY);
    $smarty->assign('returntotaltax', $totaltax);
    $smarty->assign('returntotaldiscount', $totaldiscount);
}

//# المشتريات
function showBuyBill($from, $to) {
    global $buyBillExt;
    global $buyAndReturnBillExt;
    global $buyAndReturnBillDetailExt;
    global $buyBillDetailExt;


    global $smarty;

    $queryString = ' WHERE';

    $serial = $_REQUEST["serial"];
    $supplierId = $_REQUEST["supplierId"];
    $buybillid = $_REQUEST["buybillid"];
    if (!empty($supplierId) && $supplierId != "-1") {
        $queryString .= '  buybillsupplierid = "' . $supplierId . '" AND';
    }

    if (!empty($serial) && $serial != "-1") {
        $queryString .= '  buybillSerial = "' . $serial . '" AND';
    }

    if (!empty($buybillid) && $buybillid != "-1") {
        $queryString .= '  buybillid = "' . $buybillid . '" AND';
    }


    if (!empty($from) && $from != "" && !empty($to) && $to != "") {
        $queryString .= '  buybilldate >= "' . $from . '" AND buybilldate <= "' . $to . '"  AND';
    }

    if (empty($from) && empty($to) && empty($buybillid) && empty($serial) && !isset($supplierId)) {
        //$today = date("Y-m-d");
        $from = date("Y-m-d") . " 00:00:00";
        $to = date("Y-m-d") . " 23:59:59";
        $queryString .= '  buybilldate >= "' . $from . '" AND buybilldate <= "' . $to . '"  AND';
    }

    $arr = explode(' ', $queryString);

    $arr = explode(' ', $queryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        // print_r('lastWord'.$lastWord.'<br>');
        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>");
    }

    $totalBills = 0;
    $totalqty = 0;
    $totaltax = 0;
    $totaldiscount = 0;

    $buyBillData1 = $buyBillExt->queryBystring($queryString);


    foreach ($buyBillData1 as $myBillData) {

        $buybillid = $myBillData->buybillid;
        $totalBills = $totalBills + $myBillData->buybillaftertotalbill;
        $buybilldetailes = $buyBillDetailExt->queryByBuybillidExt($buybillid);


        //getalldiscount
        $buybilldiscount = $myBillData->buybilldiscount;
        $buybilldiscountrype = $myBillData->buybilldiscountrype; //1 مباشر
        $buybilltotalbill = $myBillData->buybilltotalbill;
        $buybillaftertotalbill = $myBillData->buybillaftertotalbill;
        $tax = $myBillData->tax;

        $detaildiscount = $buyBillDetailExt->getsumdiscount($myBillData->buybillid);
        if ($buybilldiscountrype == 0) {
            //discount
            $totaldiscount = $totaldiscount + $buybilldiscount + $detaildiscount;
            $myBillData->buybilldiscount = ($buybilldiscount + $detaildiscount);

            //tax
            $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($buybilldiscount));
            $totaltax = $totaltax + $taxvalue;
            $myBillData->tax = $taxvalue;
        } else {

            //discount
            $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;


            $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
            $myBillData->buybilldiscount = ($discountvalue + $detaildiscount);
            //tax
            $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($discountvalue));
            $totaltax = $totaltax + $taxvalue;
            $myBillData->tax = $taxvalue;
        }

        if ($myBillData->conditions == 0) {
            $myBillData->controlname = "buybill";
            foreach ($buybilldetailes as $mybuybilldetailes) {
                $productnumber = $mybuybilldetailes->productnumber;
                $buybilldetailquantity = $mybuybilldetailes->buybilldetailquantity;
                $totalqty = $totalqty + ($productnumber * $buybilldetailquantity);
            }
        }
    }


    $returnbuyBillData = $buyAndReturnBillExt->queryBystring($queryString);

    foreach ($returnbuyBillData as $remyBillData) {


        //getalldiscount
        $buybilldiscount = $remyBillData->buybilldiscount;
        $buybilldiscountrype = $remyBillData->buybilldiscountrype; //1 مباشر
        $buybilltotalbill = $remyBillData->buybilltotalbill;
        $buybillaftertotalbill = $remyBillData->buybillaftertotalbill;
        $tax = $remyBillData->tax;


        $buybillid = $remyBillData->buybillid;
        $totalBills = $totalBills + $remyBillData->buybillaftertotalbill;
        $buybilldetailes = $buyAndReturnBillDetailExt->queryByBuybillidExt($buybillid);

        $detaildiscount = $buyAndReturnBillDetailExt->getsumdiscount($remyBillData->buybillid, 0);

        if ($buybilldiscountrype == 0) {
            //discount
            $totaldiscount = $totaldiscount + $buybilldiscount + $detaildiscount;
            $remyBillData->buybilldiscount = ($buybilldiscount + $detaildiscount);

            //tax
            $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($buybilldiscount));
            $totaltax = $totaltax + $taxvalue;
            $remyBillData->tax = $taxvalue;
        } else {

            //discount
            $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;


            $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
            $remyBillData->buybilldiscount = ($discountvalue + $detaildiscount);
            //tax
            $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($discountvalue));
            $totaltax = $totaltax + $taxvalue;
            $remyBillData->tax = $taxvalue;
        }

        //print_r($buybilldetailes);
        //print_r('<br><br>');
        if ($myBillData->conditions == 0) {
            $myBillData->controlname = "returnbuybill";
            foreach ($buybilldetailes as $mybuybilldetailes) {
                if ($mybuybilldetailes->billtype == 0) {
                    $productnumber = $mybuybilldetailes->productnumber;
                    $buybilldetailquantity = $mybuybilldetailes->buybilldetailquantity;

                    $totalqty = $totalqty + ($productnumber * $buybilldetailquantity);
                }
            }
        }
    }

    $buyBillData = array_merge($buyBillData1, $returnbuyBillData);


    $countbuyBillData = count($buyBillData);
    $smarty->assign('countbuyBillData', $countbuyBillData);


    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('buytotalBills', $totalBills);
    $smarty->assign('buytotalqty', $totalqty);
    $smarty->assign('totaldiscount', $totaldiscount);
    $smarty->assign('totaltax', $totaltax);
}

//# مردودات المشتريات
function showBuyReturn($from, $to) {

    global $buyAndReturnBillExt;
    global $buyAndReturnBillDetailExt;
    global $returnBuyBill;
    global $returnBuyBillDAO;
    global $returnBuyBillExt;
    global $returnBuyBillDetailExt;


    global $smarty;

    $queryString = ' WHERE';
    $queryString1 = ' WHERE';

    $serial = $_REQUEST["serial"];
    $supplierId = $_REQUEST["supplierId"];
    $buybillid = $_REQUEST["buybillid"];

    if (!empty($supplierId) && $supplierId != "-1") {
        $queryString .= '  returnbuybill.returnbuybillsupplierid = ' . $supplierId . ' AND';
        $queryString1 .= '  buybillsupplierid = ' . $supplierId . ' AND';
    }

    if (!empty($serial) && $serial != "-1") {
        $queryString .= '  returnbuybill.returnbuybillSerial = "' . $serial . '" AND';
        $queryString1 .= '  buybillSerial = "' . $serial . '" AND';
    }

    if (!empty($buybillid) && $buybillid != "-1") {
        $queryString .= '  returnbuybill.returnbuybillid = "' . $buybillid . '" AND';
        $queryString1 .= '  buybillid = "' . $buybillid . '" AND';
    }


    if (!empty($from) && $from != "" && !empty($to) && $to != "") {
        $queryString .= '  returnbuybill.returnbuybilldate >= "' . $from . '" AND returnbuybill.returnbuybilldate <= "' . $to . '"  AND';
        $queryString1 .= '  buybilldate >= "' . $from . '" AND buybilldate <= "' . $to . '"  AND';
    }


    if (empty($from) && empty($to) && empty($buybillid) && empty($serial) && !isset($supplierId)) {
        //$today = date("Y-m-d");
        $from = date("Y-m-d") . " 00:00:00";
        $to = date("Y-m-d") . " 23:59:59";
        $queryString1 .= '  buybilldate >= "' . $from . '" AND buybilldate <= "' . $to . '"  AND';
        $queryString .= '  returnbuybill.returnbuybilldate >= "' . $from . '" AND returnbuybill.returnbuybilldate <= "' . $to . '"  AND';
    }
    $arr = explode(' ', $queryString);

    $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 = ' ';
        }
    }


    $arr = explode(' ', $queryString1);
    $arr = explode(' ', $queryString1);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        // print_r('lastWord'.$lastWord.'<br>');
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString1 = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            $queryString1 = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }


    $totalBills = 0;
    $totalqty = 0;
    $totaltax = 0;
    $totaldiscount = 0;

    $returnBuyBillData1 = $returnBuyBillExt->queryBystring($queryString);

    foreach ($returnBuyBillData1 as $myreturnData) {

        $returnbuybillid = $myreturnData->returnbuybillid;
        $totalBills = $totalBills + $myreturnData->returnbuybillaftertotalbill;
        $returnbuybilldetailes = $returnBuyBillDetailExt->queryByBuybillidExt($returnbuybillid);

        if ($myreturnData->conditions == 0) {

            //getalldiscount
            $buybilldiscount = $myreturnData->returnbuybilldiscount;
            $buybilldiscountrype = $myreturnData->returnbuybilldiscountrype; //1 مباشر
            $buybilltotalbill = $myreturnData->returnbuybilltotalbill;
            $buybillaftertotalbill = $myreturnData->returnbuybillaftertotalbill;
            $tax = $myBillData->tax;

            $detaildiscount = $returnBuyBillDetailExt->getsumdiscount($myreturnData->returnbuybillid);
            if ($buybilldiscountrype == 0) {
                //discount
                $totaldiscount = $totaldiscount + $buybilldiscount + $detaildiscount;
                $myreturnData->returnbuybilldiscount = ($buybilldiscount + $detaildiscount);

                //tax
                $taxvalue = (-1 * $buybillaftertotalbill) - (number_format(($buybilltotalbill * -1) - $buybilldiscount));

                /* print_r('<br>sssssssssssssssssssssss'.$buybillaftertotalbill);
                  print_r('<br>sssssssssssssssssssssss'.number_format(($buybilltotalbill*-1)-$buybilldiscount));
                  print_r('<br>sssssssssssssssssssssss'.$buybilldiscount);
                 */
                $totaltax = $totaltax + $taxvalue;
                $myreturnData->tax = $taxvalue;
            } else {

                //discount
                $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;


                $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
                $myreturnData->returnbuybilldiscount = ($discountvalue + $detaildiscount);
                //tax
                $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($discountvalue));
                $totaltax = $totaltax + $taxvalue;
                $myreturnData->tax = $taxvalue;
            }



            $myreturnData->controlname = "returnbuybill";
            foreach ($returnbuybilldetailes as $myreturnbuybilldetailes) {
                $productnumber = $myreturnbuybilldetailes->productnumber;
                $returnbuybilldetailquantity = $myreturnbuybilldetailes->returnbuybilldetailquantity;

                $totalqty = $totalqty + ($productnumber * $returnbuybilldetailquantity);
            }
        }
    }














//    $returnbuyBillData = $buyAndReturnBillExt->queryBystring($queryString1);
//
//    foreach ($returnbuyBillData as $remyBillData) {
//
//        $buybillid = $remyBillData->buybillid;
//        $totalBills = $totalBills + $remyBillData->buybillaftertotalbill;
//        $buybilldetailes = $buyAndReturnBillDetailExt->queryByBuybillidExt($buybillid);
//
//        if ($remyBillData->conditions == 0) {
//
//
//            //getalldiscount
//            $buybilldiscount = 0; //$remyBillData->buybilldiscount;
//            $buybilldiscountrype = $remyBillData->buybilldiscountrype; //1 مباشر
//            $buybilltotalbill = $remyBillData->buybilltotalbill;
//            $buybillaftertotalbill = $remyBillData->buybillaftertotalbill;
//            $tax = $remyBillData->tax;
//
//            $detaildiscount = $buyAndReturnBillDetailExt->getsumdiscount($remyBillData->buybillid, 1);
//
//            if ($buybilldiscountrype == 0) {
//                //discount
//                $totaldiscount = $totaldiscount + $buybilldiscount + $detaildiscount;
//                $remyBillData->buybilldiscount = ($buybilldiscount + $detaildiscount);
//
//                //tax
//                $taxvalue = 0; //$buybillaftertotalbill-($buybilltotalbill-($buybilldiscount));
//                $totaltax = $totaltax + $taxvalue;
//                $remyBillData->tax = $taxvalue;
//            } else {
//
//                //discount
//                $discountvalue = 0; //($buybilltotalbill/100)*$buybilldiscount;
//
//
//                $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
//                $remyBillData->buybilldiscount = ($discountvalue + $detaildiscount);
//                //tax
//                $taxvalue = 0; //$buybillaftertotalbill-($buybilltotalbill-($discountvalue));
//                $totaltax = $totaltax + $taxvalue;
//                $remyBillData->tax = $taxvalue;
//            }
//
//
//            $remyBillData->controlname = "returnbuybill";
//            foreach ($buybilldetailes as $mybuybilldetailes) {
//                if ($mybuybilldetailes->billtype == 1) {
//                    $productnumber = $mybuybilldetailes->productnumber;
//                    $buybilldetailquantity = $mybuybilldetailes->buybilldetailquantity;
//
//                    $totalqty = $totalqty + ($productnumber * $buybilldetailquantity);
//                }
//            }
//        }
//    }




    $countreturnBuyBillData1 = count($returnBuyBillData1);
    $smarty->assign('countreturnBuyBillData1', $countreturnBuyBillData1);
    $smarty->assign('returnBuyBillData1', $returnBuyBillData1);
    $smarty->assign('returnbuyBillData', $returnbuyBillData);
    $smarty->assign('buyRetruntotalBills', $totalBills);
    $smarty->assign('buyRetruntotalqty', $totalqty);
    $smarty->assign('totaldiscount', $totaldiscount);
    $smarty->assign('totaltax', $totaltax);
}

//# اجمالى التحصيل
function showx($clientid, $clientdebtchangemodelid, $startDate, $endDate) {
    global $clientDeptChangeExt;
    global $clientDAO;
    global $clientDeptChangeDAO;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';



    if (isset($clientid) && $clientid != '-1' && $clientid != "-2") {
        $clientnamedata = $clientDAO->load($clientid);
        $message = " اسم العميل " . $clientnamedata->clientname;
        $smarty->assign('message', $message);

        $queryString .= ' clientdebtchange.clientid =' . $clientid . ' AND';
    }
    if (isset($clientid) && $clientid != "-1" && $clientid == "-2") {
        $message = " كل العملاء";
        $smarty->assign('message', $message);
        $queryString .= ' clientdebtchange.clientid > 0 AND';
    }
    if (isset($clientdebtchangemodelid) && $clientdebtchangemodelid != '-1') {
        //$mydataprocess=$clientDeptChangeDAO->load($processid);
        $message = "تقرير  عميل لعمليه   " . $processid;
        $smarty->assign('message', $message);


        $queryString .= ' clientdebtchange.clientdebtchangemodelid = ' . $clientdebtchangemodelid . ' AND';
    }
    if (!empty($startDate) && !empty($endDate)) {


        $message = " تقرير عميل من تاريخ  " . $startDate . "  الى تاريخ" . $endDate;
        $smarty->assign('message', $message);


        //clientdebtchange.clientdebtchangedate is date not datetime
        $queryString .= ' clientdebtchange.clientdebtchangedate >= date("' . $startDate . '") AND clientdebtchange.clientdebtchangedate <= date("' . $endDate . '") AND';
    }




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

    $shownData = $clientDeptChangeExt->searchforDeptOnly2($queryString);
    $sum = 0;
    foreach ($shownData as $data) {
        $sum += $data->clientdebtchangeamount;
    }

    $smarty->assign('sum', $sum);


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

//# اجمالى الدفعات
function showxDofat($supplierId, $startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $supplierdebtchange;
    global $supplierDAO;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';

    if (isset($supplierId) && $supplierId != "-1" && $supplierId != "-2") {
        $messageData = $supplierDAO->load($supplierId);
        $message = "إسم المورد: " . $messageData->suppliername;
        $smarty->assign("message", $message);

        $queryString .= ' supplierdebtchange.supplierid =' . $supplierId . ' AND';
    }

    if (isset($supplierId) && $supplierId != "-1" && $supplierId == "-2") {

        $message = " كل الموردين ";
        $smarty->assign("message", $message);

        $queryString .= ' supplierdebtchange.supplierid > 0 AND';
    }


    if (!empty($startDate) && !empty($endDate)) {



        $message = " تقرير عجز مورد من تاريخ " . $startDate . "  الى تاريخ" . $endDate;
        $smarty->assign('message', $message);

        //supplierdebtchangedate is date not datetime
        $queryString .= ' supplierdebtchange.supplierdebtchangedate >= date("' . $startDate . '") AND supplierdebtchange.supplierdebtchangedate <= date("' . $endDate . '") AND';
    }

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

    $shownData = $supplierDeptChangeExt->searchPayedDeptOnly($queryString);

    $sum = 0;
    foreach ($shownData as $data) {
        if ($data->del == 0) {
            $sum += $data->supplierdebtchangeamount;
        }
    }
    $smarty->assign('sumDofaat', $sum);

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

// مديونية العملاء
function clientdebt() {
    global $myClientRecord;

    $allclientdata = $myClientRecord->queryByCondition(0);
    $totalclientdebt;
    foreach ($allclientdata as $clientdata) {
        $totalclientdebt += $clientdata->clientdebt;
    }
    return $totalclientdebt;
}

// مديونية الموردين
function supplierdebt() {
    global $mySupplierRecord;

    $allsupplierdata = $mySupplierRecord->queryByCondition(0);
    $totalsupplierdebt;
    foreach ($allsupplierdata as $supplierdata) {
        $totalsupplierdebt += $supplierdata->suppliercurrentDebt;
    }
    return $totalsupplierdebt;
}

// المخزون
function totalproduct() {
    global $myStoredetailDAO;
    global $myStoredetailEx;
    global $myProductRecord;
    global $ProductDAO;
    global $ProgramsettingDAO;
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $priceColumnName = '';
    switch ($Programsettingdata->Inventoryevaluation) {
        case "first":
            $priceColumnName = 'productBuyPrice';
            break;
        case "last":
            $priceColumnName = 'lastbuyprice';
            break;
        case "mean":
            $priceColumnName = 'meanbuyprice';
            break;
        case "last_discount":
            $priceColumnName = 'lastbuyprice_withDiscount';
            break;
        case "mean_discount":
            $priceColumnName = 'meanbuyprice_withDiscount';
            break;
        case "tax":
            $priceColumnName = 'lastbuyprice_withTax';
            break;
        case "mean_tax":
            $priceColumnName = 'meanbuyprice_withTax';
            break;
        default:
            $priceColumnName = 'lastbuyprice';
            break;
    }




    $totalprice = (float) $myStoredetailEx->getM5zonPrice($priceColumnName);



    return $totalprice;
}

?>