<?php

//header('Location: /newstorex/controllers/generalSearch.php?do=all');
//header('Location: '.$newURL);
//the global file operation
include("../public/impOpreation.php");
require_once('../library/http_call.php');
include_once("initiateStaticSessionCommingWithCurl.php");

// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");

include_once("dailyentryfun.php");
## check if EXEC allowed on server linux #######################################
//if (@exec('echo EXEC') == 'EXEC') {
//    echo 'exec works';
//}
//if (function_exists('exec')) {
//    echo "exec is enabled";
//}
//var_dump('disable_functions');
//var_dump(explode(',', ini_get('disable_functions')));
################################################################################
//Capital
require_once('../models/dao/CapitalDAO.class.php');
require_once('../models/dto/Capital.class.php');
require_once('../models/mysql/CapitalMySqlDAO.class.php');
require_once('../models/mysql/ext/CapitalMySqlExtDAO.class.php');

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

require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
//Sparepartstore
require_once('../models/dao/SparepartstoreDAO.class.php');
require_once('../models/dto/Sparepartstore.class.php');
require_once('../models/mysql/SparepartstoreMySqlDAO.class.php');
require_once('../models/mysql/ext/SparepartstoreMySqlExtDAO.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');
//Newdbname
require_once('../models/dao/NewdbnameDAO.class.php');
require_once('../models/dto/Newdbname.class.php');
require_once('../models/mysql/NewdbnameMySqlDAO.class.php');
require_once('../models/mysql/ext/NewdbnameMySqlExtDAO.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');
//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');
//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');


require_once('../models/dao/NewdbbackupDAO.class.php');
require_once('../models/dto/Newdbbackup.class.php');
require_once('../models/mysql/NewdbbackupMySqlDAO.class.php');
require_once('../models/mysql/ext/NewdbbackupMySqlExtDAO.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');

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

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

//// ################### بداية المبيعات
//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');
//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');
//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');
//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');
//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');
//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');
//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');
//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');
//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');
//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');
//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');
//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');

//Simplemanufacturesetting
require_once('../models/dao/SimplemanufacturesettingDAO.class.php');
require_once('../models/dto/Simplemanufacturesetting.class.php');
require_once('../models/mysql/SimplemanufacturesettingMySqlDAO.class.php');
require_once('../models/mysql/ext/SimplemanufacturesettingMySqlExtDAO.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');
//Availableparcode
require_once('../models/dao/AvailableparcodeDAO.class.php');
require_once('../models/dto/Availableparcode.class.php');
require_once('../models/mysql/AvailableparcodeMySqlDAO.class.php');
require_once('../models/mysql/ext/AvailableparcodeMySqlExtDAO.class.php');
//Storemovement
require_once('../models/dao/StoremovementDAO.class.php');
require_once('../models/dto/Storemovement.class.php');
require_once('../models/mysql/StoremovementMySqlDAO.class.php');
require_once('../models/mysql/ext/StoremovementMySqlExtDAO.class.php');



//get the do the action
$do = "";
if (isset($_GET['do'])) {
    $do = $_GET['do'];
}

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

  Controller Name :- clientTypeCTRL

  OPERTATION in Controller

  1-
  2-
  3-
  4-

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

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign('Programsettingdata', $Programsettingdata);
//here the global templates
$smarty->display("header.html");

//here goes the instances and general variables
//Capital
$capital = new Capital();
$capitalDAO = new CapitalMySqlDAO();
$capitalExt = new CapitalMySqlExtDAO();
//Product
$proo = new ProductMySqlDAO();
$product = new Product();
//Store
$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeExt = new StoreMySqlExtDAO();
//Sparepartstore
$sparePartStore = new Sparepartstore();
$sparePartStoreDAO = new SparepartstoreMySqlDAO();
$sparePartStoreExt = new SparepartstoreMySqlExtDAO();
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
$Expense = new Expense();
$ExpenseExt = new ExpensesMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Newdbname
$newDbName = new Newdbname();
$newDbNameDAO = new NewdbnameMySqlDAO();
$newDbNameExt = new NewdbnameMySqlExtDAO();
//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();


//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

//paymentnetworks
$paymentNetworks = new Paymentnetwork();
$paymentNetworksDAO = new PaymentnetworksMySqlDAO();

//Dailyentry
$dailyEntry = new Dailyentry();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();

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

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

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

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

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


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

//// ################### بداية المبيعات
//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();
//Store
$myStoreRecord = new StoreMySqlDAO();
//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();
//Store
$storeDAO = new StoreMySqlDAO();
$storeExt = new StoreMySqlExtDAO();
//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();

//Simplemanufacturesetting
$simplesetting = new Simplemanufacturesetting();
$simplesettingDao = new SimplemanufacturesettingMySqlDAO();
$simplesettingExt = new SimplemanufacturesettingMySqlExtDAO();
//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();
//Availableparcode
$availableParcode = new Availableparcode();
$availableParcodeDAO = new AvailableparcodeMySqlDAO();
$availableParcodeEX = new AvailableparcodeMySqlExtDAO();

//Storemovement
$myStoremovement = new Storemovement();
$myStoremovementRecord = new StoremovementMySqlDAO();
$myStoremovementEx = new StoremovementMySqlExtDAO();

$dbhostc = ConnectionProperty::getHost();
$dbuserc = ConnectionProperty::getUser();
$dbpasswordc = ConnectionProperty::getPassword();
$dbnamec = ConnectionProperty::getDatabase();
$pSetting = $ProgramsettingDAO->load(1);
if ($pSetting->qrerp > 1) {
    $cqrerseilbil = R::count('qrerseilbil');
    if ($cqrerseilbil > 0) {
        $qrerseilbil = R::findAll('qrerseilbil', 'order by id desc limit 100');
        foreach ($qrerseilbil as $qrerseil) {
            $responsedata = CURL_IT(json_decode($qrerseil->senddata), 'http://shop.gt4host.com/qrerp/full/api/erpinsert');
            $receivedata = json_decode($responsedata);
            if ($receivedata->status == 1) {
                R::exec("DELETE FROM `qrerseilbil` WHERE id = $qrerseil->id ");
            }
        }
    }
}

function CURL_IT($data_arr, $url) {
    // set post fields
    $post = [
        'data_arr' => json_encode($data_arr), //encode it as it is array
    ];
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // execute!
    $response = curl_exec($ch);
    // print_r($response);
    // die();
    if ($response === false) {
        echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    return $response;
    // do anything you want with your response
    //print_r($response);
}

//Keep total stock elemam
$date = date('Y-m-d', strtotime("-1 day"));
$savestockc = R::count('savestock', "savestockdate = '$date' ");
if ($savestockc == 0) {
    $totalstock = R::getCell("SELECT sum(((buybilldetailprice * don) + (buybilldetailprice * don * payedtax) / 100)) as total FROM productserial left join product on product.productid = productserial.productid left join productcat on product.productCatId = productcat.productCatId left join buybilldetail on buybilldetail.buybilldetailid = productserial.buybilldetailid left join buybill on buybilldetail.buybillid = buybill.buybillid WHERE productserial.don > 0 and productserial.del = 0");
    $savestock = R::dispense('savestock');
    $savestock->savestockdate = $date;
    $savestock->savestocktotal = ceil($totalstock);
    R::store($savestock);
}
//Keep  qrerp user pass elemam
if ($pSetting->qrerp > 0) {
    $qrerpuserpass = R::findOne('qrerpuserpass');
    if ($qrerpuserpass->id > 0) {
        $_SESSION["qrusername"] = $qrerpuserpass->username;
        $_SESSION["qrpassword"] = $qrerpuserpass->password;
        $_SESSION["auserqrid"] = $qrerpuserpass->auser_id;
    } else {
        $qrerpuserpass = R::dispense('qrerpuserpass');
        $qrerpuserpass->username = 'erp' . date("YmdHis");
        $qrerpuserpass->password = time();
        R::store($qrerpuserpass);
        $send_data = array();
        $send_data['username'] = $qrerpuserpass->username;
        $send_data['password'] = $qrerpuserpass->password;
        $send_data['qrerpuserpassid'] = $qrerpuserpass->id;
        $response_data = HTTPRequester::HTTPPost('http://shop.gt4host.com/qrerp/full/api/ausererp', $send_data);
        $pro_receive_data = json_decode($response_data);
        $qrerpuserpassu = R::findOne('qrerpuserpass');
        $qrerpuserpassu->auser_id = $pro_receive_data->auser_id;
        R::store($qrerpuserpassu);
        $_SESSION["qrusername"] = $qrerpuserpassu->username;
        $_SESSION["qrpassword"] = $qrerpuserpassu->password;
        $_SESSION["auserqrid"] = $qrerpuserpassu->auser_id;
    }
}
#######  prepare sql file to send it to offline programs
if ($pSetting->updatefiledate != date('Y-m-d')) {
    prepareSqlFile($dbhostc, $dbuserc, $dbpasswordc, $dbnamec);
    $pSetting->updatefiledate = date('Y-m-d');
    $ProgramsettingDAO->update($pSetting);
}

$ManufacuresettingData = $simplesettingDao->load(1);
if (empty($ManufacuresettingData)) {
    $simplesetting->storeid = 1;
    $simplesetting->reducestoreamount = 1;
    $simplesetting->productsproductionequation = 0;
    $simplesetting->orderclient = 0;
    $simplesetting->taskOrderName = 0;
    $simplesetting->lowOutPriceAlert = 0;

    $simplesettingDao->insert($simplesetting);
}
$currency = $currencyDAO->load(1);
if (empty($currency)) {
    $currency = new stdClass();
    $currency->name = 'جنيه';
    $currency->symbol = 'EGP';
    $currency->conversionFactor = 1;
    $currency->otherconversionFactor = 1;
    $currency->conditions = 0;
    $currency->userid = $_SESSION['userid'];
    $currency->sysDate = date('Y-m-d H:i:s');

    $currencyDAO->insert($currency);
}

//Newdbbackup
$myNewdbbackup = new Newdbbackup();
$myNewdbbackupRecord = new NewdbbackupMySqlDAO();
$file = "../public/libs/plugins/fileget.nrd";
$alreadynumber = file($file);
$alreadynumber = explode("-", $alreadynumber[0]);
$alreadynumber1 = $alreadynumber[0];
$alreadynumber = $alreadynumber[1];

if (base64_decode($alreadynumber) > 0) {
    $newnumber = base64_decode($alreadynumber) - 1;
    $newnumber = base64_encode($newnumber);
    $filenew = fopen($file, "w+");
    fwrite($filenew, $alreadynumber1 . "-" . $newnumber);
    fclose($filenew);
    // echo base64_decode($alreadynumber);
} elseif (base64_decode($alreadynumber) == "-1") {

} else {
    header("location:../exper.html");
}
//check and use the condetion that suite this action
if (empty($do)) {
    //check if showPreviousPrice column exists in programsettings tbl
    $generalSettings = $ProgramsettingDAO->load(1);


    try {
        $programData = $ProgramsettingEX->getPreviousPriceStatus();
    } catch (Exception $e) {
        if (!isset($programData)) {
            //truncate table
            $ProgramsettingEX->truncateTable();

            //add column
            $ProgramsettingEX->alterTable();

            //insert old data
            $Programsetting->address = $generalSettings->address;
            $Programsetting->companyname = $generalSettings->companyname;
            $Programsetting->deptprinting = $generalSettings->deptprinting;
            $Programsetting->email = $generalSettings->email;
            $Programsetting->faxnumber = $generalSettings->faxnumber;
            $Programsetting->logo = $generalSettings->image;
            $Programsetting->phone = $generalSettings->phone;
            $Programsetting->printingpapersize = $generalSettings->printingpapersize;
            $Programsetting->roundnumbers = $generalSettings->roundnumbers;
            $Programsetting->saveprinting = $generalSettings->saveprinting;
            $Programsetting->specializtion = $generalSettings->specializtion;
            $Programsetting->website = $generalSettings->website;
            $Programsetting->userid = $generalSettings->userid;
            $Programsetting->showPreviousPrice = 1;
            $Programsetting->programsettingsid = 1;

            $ProgramsettingEX->insertExt($Programsetting);
        }
    }


    //yesterdayNetworkDailyEntry($generalSettings);
    //check if there is a save with id = 1
    $saveData = $saveDAO->load(1);
    if (!isset($saveData)) {
        try {
            insertSave();
        } catch (Exception $e) {

        }
    }
    //check if there is a unit with id = 1
    $unitData = $unitDAO->load(1);
    if (!isset($unitData)) {
        try {
            insertUnit();
        } catch (Exception $e) {

        }
    }


    //check if there is any rows in capital table
    $capitalData = getCapital(); // رأس المال
    if (!isset($capitalData)) {
        try {
            insertInitialCapitalValue();
        } catch (Exception $e) {

        }
    }

    //check if there is a store with id = 1
    $storeData = $storeDAO->load(1);
    if (!isset($storeData)) {
        try {
            insertFirstStore();
        } catch (Exception $e) {

        }
    }


    //check if there is a spare parts store with id = 1
    $partStoreData = $sparePartStoreDAO->load(1);
    if (!isset($partStoreData)) {
        try {
            insertFirstSparePartsStore();
        } catch (Exception $e) {

        }
    }

    //check if there is a supplier with id = 1 ==> مباشر
    $supplierData = $supplierDAO->load(1);
    if (!isset($supplierData)) {
        try {
            addSupplier();
        } catch (Exception $e) {

        }
    }

    //check if there is a supplier with id = 1 ==> نقدي
    $clientData = $clientDAO->load(1);
    if (!isset($clientData)) {
        try {
            addClient();
        } catch (Exception $e) {
            //print_r($e);
        }
    }


    $productExt->updateNullPricesToBuyPrice();

    ##recreate stored procedures for any update, make sure they exist
    $availableParcodeEX->createGenerateParcodesSP();
    $clientExt->createClientInUseSP();
    $saveExt->createSaveInUseSP();
    $myStoremovementEx->createInsertUniqueOptNumSP();
    $supplierExt->createSupplierInUseSP();
    $myStoredetailEx->createStoredetailInUseSP();
    $myStoredetailEx->createSizeColorStoredetailInUseSP();

    firstlogin();
    ##fatma updateCollectiveProductsPricesAsSumOfIngridientsCost
    $rowsAffected = $productExt->updateCollectiveProductsPricesAsSumOfIngridientsCost();
    if ($rowsAffected > 0) {
        echo '<div class="row">'
        . '<div class="container">'
        . '<div class="mainindex well well-sm">'
        . ' update collective products prices done (' . $rowsAffected . ')'
        . '</div></div>'
        . '</div>';
    }




    //check if there is database name in dbNames.txt
    $file_path = "../views/default/archiveview/dbNames.txt";
    if (filesize($file_path) == 0) {

        // file is empty
        //put new database name into file
        file_put_contents("../views/default/archiveview/dbNames.txt", "storesdb", FILE_APPEND | LOCK_EX);

        //insert into newdbname table
        $newDbName->dbname = "storesdb";
        $newDbNameDAO->insert($newDbName);
    }


    //handleExpiredCards
    CURL_IT2(array('clientId' => 0), 'playStationCardController.php?do=handleExpiredCards');




    $userGroupData = $userGroupDAO->load($_SESSION['usergroupid']);
    if ($userGroupData->showsIndexProductBelowLimitReport == 1)
        $smarty->display("indexReport/productBelowLimitInStoreReport.html");
    ///////////////////// ######################### start m7md report ########################## //////////////////////
    if ($userGroupData->showsIndexStatistics == 0) {
        $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 = '" . $today . "' ");
        $smarty->assign("totalExpense", $totalExpense);

        $expensesData = R::getAll('select * from expenses where expenses.conditions = 0 and expenses.expensesdate ="' . $today . '"');
        $expensesTypesArr = [];
        foreach ($expensesData as $data) {
            if (!array_key_exists($data['expensestypeid'], $expensesTypesArr)) {
                $typeName = R::getCell('select expensestypename from expensestype where expensestypeid = ' . $data['expensestypeid']);
                $expensesTypesArr[$data['expensestypeid']] = ['name' => $typeName, 'total' => $data['expensesValue']];
            } else
                $expensesTypesArr[$data['expensestypeid']]['total'] += $data['expensesValue'];
        }

        $smarty->assign('expensesTypesArr', $expensesTypesArr);
        $smarty->display("indexReport/show.html");
    }

    if ($userGroupData->showsIndexCharts == 0) {
        $smarty->display("indexReport/showCharts.html");
        $smarty->assign("story_az", 1);
    }



    ///////////////////// ######################### end m7md report ########################## //////////////////////
    if (isset($_SESSION['userid']) && $_SESSION['userid'] != "") {
        $sessionUserId = $_SESSION['userid'];
        $sessionUsergroupId = $_SESSION['usergroupid'];

        $userGroupData = $myUserGroupRecord->load($sessionUsergroupId);
        $startPage = $userGroupData->startpage;

        //echo $startPage;
        //send the user to the start page
        if ($startPage != 'index.php') {
            header("location:" . $startPage . "");
        }

        /* $myURL=curPageURL();
          $myURL=explode("controllers",$myURL);

          echo '<script type="text/javascript">
          window.location = $myURL[0].'controllers/'.$startPage;
          </script>'; */
    } else {
        header("location:login.php");
    }
}
##########################################################################################################################################################
elseif ($do == 'bill') { //testing the program
    $smarty->display("bill.html");
}
##########################################################################################################################################################
elseif ($do == 'compo') { //testing the program
    $smarty->display("compo.html");
}

##########################################################################################################################################################
elseif ($do == 'godo') { //testing the program
    $rows2[] = array(
        array("rose", 1.25, 15),
        array("daisy", 0.75, 25),
        array("orchid", 1.15, 7)
    );


    print json_encode($rows2);
} elseif ($do == 'change_lang') { //testing the program
    changelang();
}
##########################################################################################################################################################
elseif ($do == 'run') { //testing the program
    for ($i = 1; $i < 500; $i++) {
        $product->conditions = 0;
        $product->limitamount = 0;
        $product->parcode = 152;
        $product->productBuyPrice = 55;
        $product->productCatId = 1;
        $product->productDate = "0000-00-00";
        $product->productName = "name of the product" . $i;
        $product->productSellAllPrice = 15;
        $product->productSellHalfPrice = 15;
        $product->productSellUnitPrice = 15;
        $product->userId = 1;

        try {
            $proo->insert($product);
        } catch (Exception $ex) {

        }
    }
}

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

////****************************  Functions  ********************///
##########################################################  prepare sql file to send it to offline programs###############################################
function prepareSqlFile($host, $user, $pass, $name) {
    $tables = array(
        "client",
        'insurancecompanies',
        'paymentnetworks',
        'store',
        'user',
        'product',
        'productcat',
        'unit',
        'doctorkashf',
        'storedetail',
        'usergroup',
        'clientarea',
        'kashf'
    );

    EXPORT_TABLES($host, $user, $pass, $name, $tables);
}

function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false) {
    $mysqli = new mysqli($host, $user, $pass, $name);

    $mysqli->select_db($name);

    $mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES');
    while ($row = $queryTables->fetch_row()) {
        $target_tables[] = $row[0];
    }
    if ($tables !== false) {
        $target_tables = array_intersect($target_tables, $tables);
    }

    foreach ($target_tables as $table) {
        $result = $mysqli->query('SELECT * FROM ' . $table);
        $fields_amount = $result->field_count;
        $rows_num = $mysqli->affected_rows;
        $res = $mysqli->query('SHOW CREATE TABLE ' . $table);
        $TableMLine = $res->fetch_row();

        //   $content = (!isset($content) ? '' : $content) . "\n\n DROP TABLE " . $table . " ;\n\n" . $TableMLine[1] . ";\n\n";
        $content = (!isset($content) ? '' : $content) . "\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0) {
            while ($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
                if ($st_counter % 100 == 0 || $st_counter == 0) {
                    $content .= "\nREPLACE INTO " . $table . " VALUES";
                }
                $content .= "\n(";
                for ($j = 0; $j < $fields_amount; $j++) {
                    $row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
                    if (isset($row[$j])) {
                        $content .= '"' . $row[$j] . '"';
                    } else {
                        $content .= '""';
                    }
                    if ($j < ($fields_amount - 1)) {
                        $content .= ',';
                    }
                }
                $content .= ")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num) {
                    $content .= ";";
                } else {
                    $content .= ",";
                }
                $st_counter = $st_counter + 1;
            }
        }
        $content .= "\n\n\n";
        $content .= "#########delimiter########";
        $content .= "\n";
    }

    #######################################################################
    #############################   save file
    $handle = fopen('backup/tables_updates.sql', 'w+');
    fwrite($handle, $content);
    fclose($handle);

    echo '<div class="row">'
    . '<div class="container">'
    . '<div class="mainindex well well-sm">'
    . 'update file created '
    . '</div></div>'
    . '</div>';

    updateOffline();

    #######################################################################
    //    $backup_name = $backup_name ? $backup_name : $name . "_tables_updates.sql";
    //    header('Content-Type: application/octet-stream');
    //    header("Content-Transfer-Encoding: Binary");
    //    header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
    //    echo $content;
    //    exit;
}

function updateOffline() {
    $jsScript = '';
    $jsScript .= '$.post("http://localhost/erp2016_offline/controllers/billsajax.php?do=updatedbfromonline",  function (rsltC1) {';
    //$jsScript .= 'alert(222222);';
    $jsScript .= 'if (Number(rsltC1) == 111){';
    $jsScript .= 'console.log(rsltC1);';
    $jsScript .= '} else {';
    $jsScript .= 'console.log(rsltC1);';
    $jsScript .= '}';
    $jsScript .= '});';


    print_r('<script>');
    print_r($jsScript);
    print_r('</script>');
}

#######################################################################################################################################################################################################
## mda network daily entry
/*
  function yesterdayNetworkDailyEntry($generalSettings) {
  global $ProgramsettingDAO;
  global $billsEX;
  ################################################################################################
  if (empty($generalSettings->dailyentrydate)) {
  $generalSettings->dailyentrydate = date('Y-m-d', strtotime("-1 days"));
  $ProgramsettingDAO->update($generalSettings);
  }
  ################################################################################################
  if (date('Y-m-d', strtotime("-1 days")) > $generalSettings->dailyentrydate) {
  $lastDailyEntryDate = new DateTime($generalSettings->dailyentrydate);
  $yesterday = new DateTime(date('Y-m-d', strtotime("-1 days")));

  $interval = $yesterday->diff($lastDailyEntryDate);




  for ($i = 1; $i <= $interval->days; $i++) {
  $cardValue = 0;
  $date = date('Y-m-d', strtotime($generalSettings->dailyentrydate . '+ ' . $i . 'day'));
  $bills = $billsEX->queryByBilldateAndNetwork($date, 4);     ## mda network
  if (count($bills) > 0) {
  foreach ($bills as $bill) {
  $cardValue = $cardValue + $bill->cardvalue;
  }
  saveDailyEntry(4, $cardValue, $date);
  }
  }
  }
  ################################################################################################
  else {
  $generalSettings->dailyentrydate = date('Y-m-d', strtotime("-1 days"));
  $ProgramsettingDAO->update($generalSettings);
  }
  ################################################################################################
  }

  function saveDailyEntry($networkId, $cardValue, $date) {
  global $dailyEntry;      ## Dailyentry
  global $accountsTreeDAO;
  global $paymentNetworksDAO;
  global $ProgramsettingEX;

  $mytransactions = new Transaction();

  $dailyEntryDebtorArray = array();
  $dailyEntryCreditorArray = array();

  $dailyEntry->dDateTime = date('Y-m-d h:i:s', strtotime($date));
  $dailyEntry->entryComment = '';

  $entryValue = calcEntryValue($cardValue);

  #############################################  من خصومات الشبكة الى حساب الشبكة    ############################################
  #############################################  Debtor  ############################################
  $paymentNetworks = $paymentNetworksDAO->load($networkId);
  $accountsTree = $accountsTreeDAO->queryByName('رسوم ' . $paymentNetworks->name);

  if (count($accountsTree) > 0) {
  $treeId = $accountsTree[0]->id;
  } else {
  $treeId = addTreeElement('رسوم ' . $paymentNetworks->name, 37, 0, 0, 1, '', 0, 0);
  }

  $dailyEntryDebtor->value = $entryValue;
  $dailyEntryDebtor->accountstreeid = $treeId;
  array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

  #############################################  Creditor  ############################################
  $accountsTree2 = $accountsTreeDAO->queryByName($paymentNetworks->name);
  if (count($accountsTree2) > 0) {
  $treeId2 = $accountsTree2[0]->id;
  } else {
  $treeId2 = addTreeElement($paymentNetworks->name, 41, 3, 0, 1, '', 0, 0);
  }
  $dailyEntryCreditor->value = $entryValue;
  $dailyEntryCreditor->accountstreeid = $treeId2;
  array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

  #############################################  save daily entry  ############################################

  try {
  $data = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
  //        $dailyEntryId = $data[1];
  //
  //        $bills->dailyentryid = $dailyEntryId;
  //        $billsDAO->update($bills);
  ## save last date of recording daily entry in setting table
  $ProgramsettingEX->updateObj('programsettings', 'dailyentrydate', $date, 'programsettingsid', 1);

  $mytransactions->commit();

  $message = 'تمت العملية بنجاح';
  } catch (Exception $ex) {
  $mytransactions->rollback();
  $message = 'عفوا لقد حدث خطأ';
  }
  }

  function calcEntryValue($cardValue) {
  $entryValue = 0;
  $discount = 0;


  ## discount =  .7%  of total card value
  if ($cardValue < 5000) {
  $discount = (7 * $cardValue ) / 1000;
  $entryValue = $cardValue - $discount;
  }

  ## discount = 40 Rs
  else {
  $discount = 40;
  $entryValue = $cardValue - $discount;
  }

  return $entryValue;
  }
 */
####################################################################################################################################################################################

function firstlogin() {
    global $dbhostc;
    global $dbuserc;
    global $dbpasswordc;
    global $dbnamec;


    ##make long time stop it now
    ##also CHECK and repair work with myissam not inno db
    //    $CHECKdata = CHECKdatabase($dbhostc, $dbuserc, $dbpasswordc);
    //    if ($CHECKdata == 1) {
    //        echo '<div class="row">'
    //        . '<div class="container">'
    //        . '<div class="mainindex well well-sm">'
    //        . 'Check databsae done '
    //        . '</div></div>'
    //        . '</div>';
    //    } else {
    //        echo '<div class="row">'
    //        . '<div class="container">'
    //        . '<div class="mainindex well well-sm">'
    //        . 'check error '
    //        . '</div></div>'
    //        . '</div>';
    //    }
    //    $repardata = repardatabase($dbhostc, $dbuserc, $dbpasswordc);
    //    if ($repardata == 1) {
    //        echo '<div class="row">'
    //        . '<div class="container">'
    //        . '<div class="mainindex well well-sm">'
    //        . 'Repair  databsae  done  '
    //        . '</div></div>'
    //        . '</div>';
    //    } else {
    //        echo '<div class="row">'
    //        . '<div class="container">'
    //        . '<div class="mainindex well well-sm">'
    //        . 'Repair error '
    //        . '</div></div>'
    //        . '</div>';
    //    }
    avalableParcodes();
    $newdbname = $_SESSION['dbname'] . '_' . date('Y-m-d');
    $filename = '../db_backups/' . $newdbname . '.sql';


    if (file_exists($filename) || file_exists($filename . ".gz")) {

        return;
    } else {


        @$done = backup_tables('*', '../db_backups/', $_SESSION['dbname'], $dbhostc, $dbuserc, $dbpasswordc);

        if ($done == 1) {
            echo '<div class="row">'
            . '<div class="container">'
            . '<div class="mainindex well well-sm">'
            . 'First backup  databsae  done   '
            . '</div></div>'
            . '</div>';
        } else {
            echo '<div class="row">'
            . '<div class="container">'
            . '<div class="mainindex well well-sm">'
            . 'Backup error  '
            . '</div></div>'
            . '</div>';
        }
    }
}

function avalableParcodes() {
    global $ProgramsettingDAO;
    global $productExt;
    global $availableParcodeEX;


    $Programsettingdata = $ProgramsettingDAO->load(1);
    if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
        $Programsettingdata->parcodeDigits = 5;
    }



    $dbname = ConnectionProperty::getDatabase();
    if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
        $dbname = $_SESSION['dbname'];
    }

    //check if it has rows
    $result = $availableParcodeEX->getFirstRow();
    //if no rows create parcodes
    if (!isset($result) || empty($result)) {
        ##write all parcodes possibilities
        $availableParcodeEX->callGenerateParcodesSP($Programsettingdata->parcodeDigits);
        ##remove used parcodes from possibilities ##edit line is also like this
        $availableParcodeEX->deleteUsedParcodesInproductTable();
        echo '<div class="row">'
        . '<div class="container">'
        . '<div class="mainindex well well-sm">'
        . 'Avalable parcodes created   '
        . '</div></div>'
        . '</div>';
    }


    /*
      $biggestParcode = '';
      for ($i = 1; $i <= (int) $Programsettingdata->parcodeDigits; $i++) {
      $biggestParcode .= '9';
      }
      $biggestParcode = (int) $biggestParcode;


      if (file_exists('../avalableParcodes/' . $dbname . '.txt')) {

      return 0;
      } else {

      ##collect used parcodes
      $count = 0;
      $start = 0;
      $limit = 30;
      $end = $start + $limit;
      $usedParcodesArr = array();
      $all_products_count = $productExt->getProductsCount();
      for ($i = $start; $i <= $all_products_count->productId; $i += $limit) {
      $allproduct = $productExt->queryAllOrderedLimitedSimple($start, $limit);
      foreach ($allproduct as $value) {
      array_push($usedParcodesArr, $value->parcode);
      $count++;
      }
      //
      $start += $limit;
      $end += $limit;
      }

      ##write all parcodes possibilities
      $file = fopen('../avalableParcodes/' . $dbname . '.txt', 'w') or exit("Unable to open avalable parcodes file!");
      flock($file, LOCK_EX);
      for ($i = 0; $i <= $biggestParcode; $i++) {
      //fixed length of five
      $number = (string) $i;
      $numlength = strlen($number);
      if ($numlength != $Programsettingdata->parcodeDigits) {
      $noDigitsLeft = $Programsettingdata->parcodeDigits - $numlength;
      $preDigits = '';
      for ($j = 0; $j < $noDigitsLeft; $j++) {
      $preDigits .= '0';
      }
      $number = $preDigits . $number;
      }

      if ($i != $biggestParcode)
      $number = $number . PHP_EOL;

      fwrite($file, $number);
      }
      flock($file, LOCK_UN);
      fclose($file);
      ##remove used parcodes from possibilities ##edit line is also like this
      $file = fopen('../avalableParcodes/' . $dbname . '.txt', "r") or exit("Unable to open avalable parcodes file!");
      flock($file, LOCK_EX);
      $text = '';
      while (!feof($file)) {
      $lineTxt = trim(fgets($file));
      //if (in_array($lineTxt, $usedParcodesArr)) {
      $key = array_search($lineTxt, $usedParcodesArr);
      if ($key > -1 && $key !== FALSE) {
      ##in the array dont use it in $text.this means that this value will be removed from txt file
      //remove this index from array of used parcodes to make array smaller
      unset($usedParcodesArr[$key]);
      //echo $lineTxt;
      } else {
      //lastLine will have biggest parcode as file is created now and we are workig on remove parcode
      //no changes yet
      $text .= $lineTxt;
      if ($lineTxt != $biggestParcode)
      $text .= PHP_EOL;
      }
      }
      flock($file, LOCK_UN);
      fclose($file);
      $file = fopen('../avalableParcodes/' . $dbname . '.txt', "w") or exit("Unable to open avalable parcodes file!");
      flock($file, LOCK_EX);
      fwrite($file, $text);
      flock($file, LOCK_UN);
      fclose($file);





      echo '<div class="row">'
      . '<div class="container">'
      . '<div class="mainindex well well-sm">'
      . 'Avalable parcodes created   '
      . '</div></div>'
      . '</div>';
      } */
}

function insertUserGroup() {
    global $userGroup;
    global $userGroupDAO;

    $userGroup->conditions = 0;
    $userGroup->currentdate = date("Y-m-d");
    $userGroup->level = 1;
    $userGroup->startpage = "index.php";
    $userGroup->usergroupdescription = "admin";
    $userGroup->usergroupname = "admin";
    //
    $myUserGroup->savedailydate = date("Y-m-d");
    $myUserGroup->hidemenu = 1; //1 to show menu
    $myUserGroup->hidecat = 0;
    $myUserGroup->clientnegative = 1;
    $myUserGroup->suplliernegative = 1;
    $myUserGroup->storenegative = 1;
    $myUserGroup->directDiscount = 0;
    $myUserGroup->percentageDiscount = 0;
    $myUserGroup->priceupdate = 0;
    $myUserGroup->allowEditDelInBills = 0;
    $myUserGroup->allowEditDelInBuyBills = 0;
    $myUserGroup->showsStorerQuantity = 0;
    $myUserGroup->showSellAllPrice = 0;
    $myUserGroup->showSellHalfPrice = 0;
    $myUserGroup->showSellUnitPrice = 0;
    $myUserGroup->showBuyPrice = 0;
    $myUserGroup->productno = 0;
    $myUserGroup->kempilano = 0;
    $myUserGroup->productnotsellno = 0;
    $myUserGroup->clientcheckno = 0;
    $myUserGroup->suppliercheckno = 0;
    $myUserGroup->productRequist = 0;
    $myUserGroup->otherRequist = 0;
    $myUserGroup->toWorkShopOrder = 0;
    $myUserGroup->insuranceBill = 0;
    $myUserGroup->sellreportpricetype = 0;
    $myUserGroup->netprofit = 0;
    $myUserGroup->hideproductcatid = 0;
    $myUserGroup->directSaveBills = 0;
    $myUserGroup->seeAllHalls = 0;
    $myUserGroup->homePageIcon = 0;
    $myUserGroup->sendKitchen = 1;
    $myUserGroup->printKitchen = $printKitchen;
    $myUserGroup->endBill = 1;
    $myUserGroup->endPrintBill = 1;
    $myUserGroup->showManualBackup = 1;
    $myUserGroup->autoKitchenPrint = 0;
    $myUserGroup->takeAway = 0;
    $myUserGroup->delivery = 0;
    $myUserGroup->hall = 0;
    $myUserGroup->deleteMovementManage = 0;
    $myUserGroup->allowBillDelete = 0;
    $myUserGroup->billDeletePassword = '111';
    $myUserGroup->reviewBillsAllowedTables = '1,2,3,4,5';
    $myUserGroup->downloadClientPhones = 0;
    $myUserGroup->showstoredetailprice = 0;
    $myUserGroup->stopDiscountOfTotalControl = 0;
    $myUserGroup->discountOfTotalControlEditable = 0;
    $myUserGroup->discountOfTotalControlMTGDA = 0;
    $myUserGroup->kitchenPayedVal = 0;
    $myUserGroup->kitchenPayedChange = 0;
    $myUserGroup->showsIndexStatistics = 1;

    $userGroupDAO->insert($userGroup);
}

function insertUser() {
    global $user;
    global $userDAO;

    $user->conditions = 0;
    $user->currentdate = date("Y-m-d");
    $user->employeename = "admin";
    $user->password = "manager";
    $user->saveid = 1;
    $user->usergroupid = 1;
    $user->username = "admin";

    $userDAO->insert($user);
}

function insertSave() {
    global $save;
    global $saveExt;

    $save->conditions = 0;
    $save->savecurrentvalue = 0;
    $save->savedate = date("Y-m-d");
    $save->savedetails = "";
    $save->savename = "الخزنة الرئيسية";
    $save->userid = 1;
    $save->saveid = 1;
    $save->treeId = 383;

    $saveExt->insertFirstSave($save, "");
}

function insertUnit() {
    global $unit;
    global $unitDAO;

    $unit->unitName = "قطعة";
    $unit->unitDate = date("Y-m-d");
    $unit->conditions = 0;
    $unit->userId = 1;

    $unitDAO->insert($unit);
}

function getCapital() {
    global $capitalDAO;
    $capitalData = $capitalDAO->queryAll();
    return $capitalData;
}

function insertInitialCapitalValue() {
    global $capitalDAO;
    global $capital;

    $capital->capitalamount = 0;
    $capital->treeId = 50;

    $capitalDAO->insert($capital);
}

function insertFirstStore() {
    global $store;
    global $storeExt;

    $store->conditions = 0;
    $store->storeDate = date("Y-m-d");
    $storeDescription = "المخزن الرئيسي";
    $store->storeId = 1;
    $store->storeName = "المخزن الرئيسي"; //"مخزن1";
    $store->userId = 1;
    $store->treeId = 382;
    $store->treeIdBetween = 51;

    $storeExt->insertFirstStore($store, $storeDescription);
}

function insertFirstSparePartsStore() {
    global $sparePartStore;
    global $sparePartStoreExt;

    $sparePartStore->conditions = 0;
    $sparePartStore->sparepartstoreId = 1;
    $sparePartStore->storeDate = date("Y-m-d");
    $sparePartStore->storeDescription = "مخزن قطع الغيار";
    $sparePartStore->storeName = "مخزن قطع الغيار";
    $sparePartStore->userId = 1;

    $sparePartStoreExt->insertFirstSparePartsStore($sparePartStore);
}

// add in supplier tbl
function addSupplier() {
    global $supplierExt;
    global $supplier;

    $supplier->suppliername = "مباشر";
    $supplier->supplieraddress = "";
    $supplier->supplierphone = "";
    $supplier->supplierdetails = "مباشر";
    $supplier->suppliercurrentDebt = 0;
    $supplier->userid = $_SESSION['userid'];
    $supplier->conditions = 0;
    $supplier->supplierdate = date("Y-m-d");
    $supplier->supplierid = 1;
    $supplier->treeId = 385;

    //Insert
    $supplierExt->insertFirstSupplier($supplier);
}

// add in client tbl
function addClient() {
    global $clientExt;
    global $clientDAO;
    global $client;

    $client->clientaddress = "";
    $client->clientdate = date("Y-m-d");
    $client->clientdebt = 0;
    $client->clientdetails = "نقدي";
    $client->clientid = 1;
    $client->clientmobile = "";
    $client->clientname = "نقدي";
    $client->clientphone = "";
    $client->conditions = 0;
    $client->clientStoreIds = -10; //have all stores in sell bill
    $client->userid = $_SESSION['userid'];
    $client->clientareaid = 1;
    //$client->clientcode = null;
    $client->dailyentryid = 0;
    $client->treeId = 384;

    //Insert
    $clientDAO->insert($client);
}

function CHECKdatabase($db_host, $db_user, $db_password) {

    $newDatabaseLink = mysqli_connect($db_host, $db_user, $db_password, $_SESSION['dbname']) or die("Unable to select database: " . $rs['Database']);
    try {
        ###########
        #The CHECK TABLE method is only applicable to MyISAM, ARCHIVE, and CSV tables.
        //insert in billsettings tbl
        mysqli_query(
                        $newDatabaseLink,
                        "CHECK TABLE  `accountmovement` ,  `assets` ,  `assetscat` ,  `bank` ,  `bankaccount` ,  `billname` ,  `billproperty` ,  `billsettings` ,  `buyandruternbill` ,  `buyandruternbilldetail` , `buybill` ,  `buybilldetail` ,  `capital` ,  `checkcontroller` ,  `checkdeposit` ,  `checkwithdrawal` , `cashtransfer`, `client` ,  `clientdebtchange` ,  `expenses` ,  `expensestype` ,  `kempiala` ,  `menuurl` , `movementmanage` ,  `newdbbackup` ,  `newdbname` ,  `partner` ,  `partnerwithdrawal` ,  `policy` ,  `product` ,  `productcat` ,  `productcatunit` ,  `productrecieve` ,  `productserial` , `productsetting` ,  `producttemp` ,  `producttempunit` ,  `productunit` ,  `programsettings` ,  `properties` ,  `relusergroupproperties` ,  `representativecompany` ,  `returnbuybill` , `returnbuybilldetail` ,  `returnsellbill` ,  `returnsellbilldetail` ,  `save` ,  `savedaily` ,  `sellandruternbilldetail` ,  `sellbill` ,  `sellbillandrutern` ,  `sellbilldetail` ,  `shippercompanies` , `sparepart` ,  `sparepartstore` ,  `sparepartstoredetails` ,  `sparepartstorereport` ,  `store` ,  `storedetail` ,  `storemovement` ,  `storereport` ,  `supplier` ,  `supplierdebtchange` , `transfermoney` ,  `unit` ,  `user` ,  `usergroup`, `storemovement_main`, `storemovement_details`"
                ) or die(mysql_error());

        return 1;
    } catch (Exception $e) {
        return 0;
    }
}

function repardatabase($db_host, $db_user, $db_password) {
    /* $db_host ="localhost"; //$_POST['db_host'];
      $db_user = "root";//$_POST['db_user'];
      $db_password = "123456";//$_POST['db_password'];
     */
    //print_r($_SESSION['dbname'].'l1111111111');
    $newDatabaseLink = mysqli_connect($db_host, $db_user, $db_password, $_SESSION['dbname']) or die("Unable to select database: " . $rs['Database']);

    try {
        ###########
        #The REPAIR TABLE method is only applicable to MyISAM, ARCHIVE, and CSV tables.
        //insert in billsettings tbl
        mysqli_query(
                        $newDatabaseLink,
                        "REPAIR TABLE  `accountmovement` ,  `assets` ,  `assetscat` ,  `bank` ,  `bankaccount` ,  `billname` ,  `billproperty` ,  `billsettings` ,  `buyandruternbill` ,  `buyandruternbilldetail` , `buybill` ,  `buybilldetail` ,  `capital` ,  `checkcontroller` ,  `checkdeposit` ,  `checkwithdrawal` , `cashtransfer`  ,   `client` ,  `clientdebtchange` ,  `expenses` ,  `expensestype` ,  `kempiala` ,  `menuurl` , `movementmanage` ,  `newdbbackup` ,  `newdbname` ,  `partner` ,  `partnerwithdrawal` ,  `policy` ,  `product` ,  `productcat` ,  `productcatunit` ,  `productrecieve` ,  `productserial` , `productsetting` ,  `producttemp` ,  `producttempunit` ,  `productunit` ,  `programsettings` ,  `properties` ,  `relusergroupproperties` ,  `representativecompany` ,  `returnbuybill` , `returnbuybilldetail` ,  `returnsellbill` ,  `returnsellbilldetail` ,  `save` ,  `savedaily` ,  `sellandruternbilldetail` ,  `sellbill` ,  `sellbillandrutern` ,  `sellbilldetail` ,  `shippercompanies` , `sparepart` ,  `sparepartstore` ,  `sparepartstoredetails` ,  `sparepartstorereport` ,  `store` ,  `storedetail` ,  `storemovement` ,  `storereport` ,  `supplier` ,  `supplierdebtchange` , `transfermoney` ,  `unit` ,  `user` ,  `usergroup`, `storemovement_main`, `storemovement_details`"
                ) or die(mysql_error());

        mysqli_close($newDatabaseLink);
        return 1;
    } catch (Exception $e) {
        mysqli_close($newDatabaseLink);
        return 0;
    }
}

function backup_tables($tables, $backupdir, $dbname, $db_host, $db_user, $db_password) {
    global $ProgramsettingDAO;

    // Check if session has dbname
if (!isset($_SESSION['dbname']) || empty($_SESSION['dbname'])) {
    // http_response_code(400);
    // die("Database name not found in session. Please login again.");
    return 0;
}

    $generalSettings = $ProgramsettingDAO->load(1);
    //getcwd() is to Gets the current working directory
    $partition = explode(":", getcwd())[0]; //$generalSettings->partition;
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        //do nothing
    } else { //if (!empty(exec("ip link"))) {// unix, linux, mac
        $partition = 0;
    }
    /* if (DIRECTORY_SEPARATOR === '/') {
      // unix, linux, mac
      }
      if (DIRECTORY_SEPARATOR === '\\') {
      // windows
      } */

    if ($partition !== $generalSettings->partition) {
        $generalSettings->partition = $partition;
        $ProgramsettingDAO->update($generalSettings);
    } else {
        $partition = $generalSettings->partition;
    }
    #######################################
    ## apply backup setting
    if (!file_exists('../backupset.json')) {
        $data = array('daily' => 5, 'compressed' => 1);
        $json_data = json_encode($data);
        file_put_contents('../backupset.json', $json_data);
    }
    $json_data = file_get_contents('../backupset.json');
    $data = json_decode($json_data, true);
    $noOfBackups = (isset($data['daily']) ? $data['daily'] : 100) - 1; //-1 as iam taking backup now so remove one more backup
    $compressed = isset($data['compressed']) ? $data['compressed'] : 1;
    //// remove oldbackups
    $files = array_filter(scandir($backupdir), function($file) {
        return (strpos($file, '.sql') !== false || strpos($file, '.sql.gz') !== false)  //to handle only sql , sql.gz files only , not week or month backup files
                && $file !== 'weeklybackup.sql' && $file !== 'weeklybackup.sql.gz' && $file !== 'monthlybackup.sql' && $file !== 'monthlybackup.sql.gz';
    });
    rsort($files); // sort by name (newest first)
    $filesToRemove = array_slice($files, $noOfBackups); // remove all but the last $noOfBackups like 5 files
    foreach ($filesToRemove as $file) {
        $filePath = $backupdir . '/' . $file;
        if (is_file($filePath))
            unlink($filePath);
    }
    ##################################
    if (empty($partition) || $partition == "0") { //linux
        if ($compressed == 1) {
            $inrtoi = "../db_backups//" . $_SESSION['dbname'] . "_" . date("Y-m-d") . ".sql.gz";
            ##compressed backup
            $command = "mysqldump --user=$db_user --password=$db_password --host=$db_host --opt --single-transaction $dbname | gzip > $inrtoi";
        } else {
            $inrtoi = "../db_backups//" . $_SESSION['dbname'] . "_" . date("Y-m-d") . ".sql";
            $command = "mysqldump --user=$db_user --password=$db_password --host=$db_host --opt $dbname > $inrtoi";
        }
        exec($command, $output, $result);
        $output = implode(PHP_EOL, $output);
    } else { //localhost
        ## to handle diffrent path for diffrent wamp version

        function find_mysqldump($baseDirs) {
            foreach ($baseDirs as $baseDir) {
                $mysqlPath = $baseDir . '\\bin\\mysql';
                if (!is_dir($mysqlPath))
                    continue;

                $versions = scandir($mysqlPath);
                foreach ($versions as $version) {
                    if ($version === '.' || $version === '..')
                        continue;

                    $dumpPath = $mysqlPath . '\\' . $version . '\\bin\\mysqldump.exe';
                    if (file_exists($dumpPath)) {
                        return $dumpPath;
                    }
                }
            }
        }

        $pathToWampMysqldump = find_mysqldump([$partition . ':\\wamp', $partition . ':\\wamp64']);
        if (!isset($pathToWampMysqldump) || empty($pathToWampMysqldump)) {
            $pathToWampMysqldump = "$partition:\\wamp\bin\mysql\mysql5.6.17\bin\mysqldump";
        }


        if ($compressed == 1 && file_exists("C:\gzip\bin\gzip.exe")) {
            $inrtoi = "..\db_backups\\" . $_SESSION['dbname'] . "_" . date("Y-m-d") . ".sql.gz";
            ##compressed backup
            //$command = "$partition:\\wamp\bin\mysql\mysql5.6.17\bin\mysqldump --user=$db_user --password=$db_password --host=$db_host --opt --single-transaction $dbname | gzip > $inrtoi";
            $command = "$pathToWampMysqldump --user=$db_user --password=$db_password --host=$db_host --opt --single-transaction $dbname | C:\\gzip\\bin\\gzip.exe > $inrtoi";
        } else {
            $inrtoi = "..\db_backups\\" . $_SESSION['dbname'] . "_" . date("Y-m-d") . ".sql";
            $command = "$pathToWampMysqldump --user=$db_user --password=$db_password --host=$db_host --opt $dbname > $inrtoi";
        }
        //i prefer  passthru() like system()
        //passthru($command . " 2>&1",$vvv);//" 2>&1" is important as if there is error it writes it to the file and you can see it in the output which is $vvv
        $output = passthru($command); //remove " 2>&1" as it writes warning to backup file
    }
    #######################
    //weekly , monthly backyup
    $source_file = $inrtoi;
    $weekly_filename = dirname($inrtoi) . DIRECTORY_SEPARATOR . 'weeklybackup.sql';
    $monthly_filename = dirname($inrtoi) . DIRECTORY_SEPARATOR . 'monthlybackup.sql';
    if (substr($source_file, -3) === '.gz') {
        $weekly_filename = dirname($inrtoi) . DIRECTORY_SEPARATOR . 'weeklybackup.sql.gz';
        $monthly_filename = dirname($inrtoi) . DIRECTORY_SEPARATOR . 'monthlybackup.sql.gz';
    }
    // Check if the weekly file exists and is older than 7 days
    if (!file_exists($weekly_filename) || (file_exists($weekly_filename) && filemtime($weekly_filename) < strtotime('-7 days'))) {
        if (file_exists($weekly_filename)) {
            unlink($weekly_filename);
        }
        if (file_exists($weekly_filename . ".gz")) {
            unlink($weekly_filename . ".gz");
        }
        copy($source_file, $weekly_filename);
    }
    // Check if the monthly file exists and is older than 30 days
    if (!file_exists($monthly_filename) || (file_exists($monthly_filename) && filemtime($monthly_filename) < strtotime('-30 days'))) {
        if (file_exists($monthly_filename)) {
            unlink($monthly_filename);
        }
        if (file_exists($monthly_filename . ".gz")) {
            unlink($monthly_filename . ".gz");
        }
        copy($source_file, $monthly_filename);
    }
    #######################



    return 1;
}

/* function curPageURL() {
  $pageURL = 'http';
  if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
  $pageURL .= "://";
  if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  }
  return $pageURL;
  } */

//// ##################################### start m7md functions ######################### ////
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;
    $saveChanges = [];
    foreach ($savedailyData as $data) {
        if (!array_key_exists($data->saveid, $saveChanges)) {
            $saveName = R::getCell('select savename from save where saveid = ' . $data->saveid);
            $saveChanges[$data->saveid] = ['name' => $saveName];
        }
        //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;
                $saveChanges[$data->saveid]['total'] += $data->savedailychangeamount;
            } else if ($data->savedailychangetype == 1) { //minus
                $changeAmountSum -= $data->savedailychangeamount;
                $saveChanges[$data->saveid]['total'] -= $data->savedailychangeamount;
            }
        } else {
            if ($data->savedailychangetype == 0) { //plus
                if ($data->savedailychangeamount > 0) {
                    $changeAmountSum += $data->savedailychangeamount;
                    $saveChanges[$data->saveid]['total'] += $data->savedailychangeamount;
                } else {
                    $changeAmountSum += ($data->savedailychangeamount) * -1;
                    $saveChanges[$data->saveid]['total'] += ($data->savedailychangeamount) * -1;
                    $data->savedailychangeamount = $data->savedailychangeamount * -1;
                }
            } else if ($data->savedailychangetype == 1) { //minus
                if ($data->savedailychangeamount > 0) {
                    $changeAmountSum -= $data->savedailychangeamount;
                    $saveChanges[$data->saveid]['total'] -= $data->savedailychangeamount;
                } else {
                    $changeAmountSum -= ($data->savedailychangeamount) * -1;
                    $saveChanges[$data->saveid]['total'] -= ($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('saveChanges', $saveChanges);
        $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 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 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;

    $payedSell = [];
    $totalPayed = 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";

                if ($sell->sellbilltotalpayed > 0) {
                    $totalPayed += $sell->sellbilltotalpayed;
                    if (!array_key_exists($sell->sellbillsaveid, $payedSell)) {
                        $saveName = R::getCell('select savename from save where saveid = ' . $sell->sellbillsaveid);
                        $payedSell[$sell->sellbillsaveid] = ['name' => $saveName, 'payed' => $sell->sellbilltotalpayed];
                    } else
                        $payedSell[$sell->sellbillsaveid]['payed'] += $sell->sellbilltotalpayed;
                }

                /* //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;

                if ($sell->sellbilltotalpayed > 0) {
                    $totalPayed += $sell->sellbilltotalpayed;
                    if (!array_key_exists($sell->sellbillsaveid, $payedSell)) {
                        $saveName = R::getCell('select savename from save where saveid = ' . $sell->sellbillsaveid);
                        $payedSell[$sell->sellbillsaveid] = ['name' => $saveName, 'payed' => $sell->sellbilltotalpayed];
                    } else
                        $payedSell[$sell->sellbillsaveid]['payed'] += $sell->sellbilltotalpayed;
                }

                /* $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);

    $smarty->assign('payedSell', $payedSell);
    $smarty->assign('totalPayed', $totalPayed);

    // 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) {
        $buybillid = $remyBillData->buybillid;
        $buybilldetailes = $buyAndReturnBillDetailExt->queryByBuybillidExt($buybillid);

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



          $totalBills = $totalBills + $remyBillData->buybillaftertotalbill;


          $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 ($remyBillData->conditions == 0) {
            $remyBillData->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));

              $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;
    $clientPayed = [];
    foreach ($shownData as $data) {
        if (!array_key_exists($data->clientid, $clientPayed)) {
            $clientName = R::getCell('select clientname from client where clientid = ' . $data->clientid);
            $clientPayed[$data->clientid] = ['name' => $clientName, 'payed' => $data->clientdebtchangeamount];
        } else
            $clientPayed[$data->clientid]['payed'] += $data->clientdebtchangeamount;

        $sum += $data->clientdebtchangeamount;
    }

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


    // 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;
    $supplierPayed = [];

    foreach ($shownData as $data) {
        if ($data->del == 0) {
            if (!array_key_exists($data->supplierid, $supplierPayed)) {
                $supplierName = R::getCell('select suppliername from supplier where supplierid = ' . $data->supplierid);
                $supplierPayed[$data->supplierid] = ['name' => $supplierName, 'payed' => $data->supplierdebtchangeamount];
            } else
                $supplierPayed[$data->supplierid]['payed'] += $data->supplierdebtchangeamount;

            $sum += $data->supplierdebtchangeamount;
        }
    }

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

    // 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 "generalPrice":
            $priceColumnName = 'overAllAveragePrice';
            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;
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
    //    $post = [
    //        'data_arr' => json_encode($data_arr), //encode it as it is array
    //    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}

function changelang() {
    global $userDAO;

    $newlang = filter_input(INPUT_POST, 'newlang');
    $_SESSION['erp_lang'] = $newlang;
    setcookie("lang_code", $newlang, time() + 1209600);

    if (!isset($_SESSION['erp_lang'])) {
        $_SESSION['erp_lang'] = "ar";
        setcookie("lang_code", "ar", time() + 1209600);
    }

    $user = $userDAO->load($_SESSION['userid']);
    $user->lang = $_SESSION['erp_lang'];
    $userDAO->update($user);
    //        define('default_lang_interface', $_SESSION['erp_lang']);
}

function run_sql_file($location) {
    $conn = mysqli_connect(ConnectionProperty::getHost(), ConnectionProperty::getUser(), ConnectionProperty::getPassword(), ConnectionProperty::getDatabase());
    if (!$conn) {
        throw new Exception('could not connect to database');
    }

    //$charset = mysql_client_encoding($conn);
    mysqli_query($conn, "SET NAMES 'utf8'");
    mysqli_query($conn, 'SET CHARACTER SET utf8');

    //load file
    $commands = file_get_contents($location);

    //delete comments
    $lines = explode("\n", $commands);
    $commands = '';
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line && !strpos($line, '--')) {
            $commands .= $line . "\n";
        }
    }

    //convert to array
    $commands = explode(";", $commands);
    /* 	print_r("<pre>");
      print_r($commands);
      print_r("<pre>"); */
    //run commands
    $total = $success = 0;
    foreach ($commands as $command) {

        if (trim($command)) {
            if (mysqli_query($conn, $command)) {
                $success += 1;
                $total += 1;
            }
            //            if (!empty($error = mysql_error())) {
            //                echo 'Mysql error ' . $error . "<br />\n";
            //            }
            // $success += (@mysql_query($command)==false ? 0 : 1);
            // $total += 1;
        }
    }

    //return number of successful queries and total number of queries found
    return array(
        "success" => $success,
        "total" => $total
    );
}
