<?php

ob_start();
$do = isset($_GET['do']) ? $_GET['do'] : "";
//the global file operation
if ($do != "addObgyVisit" && $do != "delObgyVisit" && $do != "updateObgyVisit" && $do != "showallajax" && $do != "billToExcel" && $do != "billToPDF") {
    include("../public/impOpreation.php");
    include("../library/regenerateSession.php");
}
include_once("initiateStaticSessionCommingWithCurl.php");
//global varable
global $showoutside;

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

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

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

//Sellbilldetailorder
require_once('../models/dao/SellbilldetailorderDAO.class.php');
require_once('../models/dto/Sellbilldetailorder.class.php');
require_once('../models/mysql/SellbilldetailorderMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailorderMySqlExtDAO.class.php');

//Sellbillorder
require_once('../models/dao/SellbillorderDAO.class.php');
require_once('../models/dto/Sellbillorder.class.php');
require_once('../models/mysql/SellbillorderMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillorderMySqlExtDAO.class.php');

//Temsellbill
require_once('../models/dao/TemsellbillDAO.class.php');
require_once('../models/dto/Temsellbill.class.php');
require_once('../models/mysql/TemsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellbillMySqlExtDAO.class.php');
//Temsellbilldetail
require_once('../models/dao/TemsellbilldetailDAO.class.php');
require_once('../models/dto/Temsellbilldetail.class.php');
require_once('../models/mysql/TemsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellbilldetailMySqlExtDAO.class.php');

//Temreturnsellbill
require_once('../models/dao/TemreturnsellbillDAO.class.php');
require_once('../models/dto/Temreturnsellbill.class.php');
require_once('../models/mysql/TemreturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/TemreturnsellbillMySqlExtDAO.class.php');
//Temreturnsellbilldetail
require_once('../models/dao/TemreturnsellbilldetailDAO.class.php');
require_once('../models/dto/Temreturnsellbilldetail.class.php');
require_once('../models/mysql/TemreturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/TemreturnsellbilldetailMySqlExtDAO.class.php');

//Temsellbillandrutern
require_once('../models/dao/TemsellbillandruternDAO.class.php');
require_once('../models/dto/Temsellbillandrutern.class.php');
require_once('../models/mysql/TemsellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellbillandruternMySqlExtDAO.class.php');
//Temsellandruternbilldetail
require_once('../models/dao/TemsellandruternbilldetailDAO.class.php');
require_once('../models/dto/Temsellandruternbilldetail.class.php');
require_once('../models/mysql/TemsellandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellandruternbilldetailMySqlExtDAO.class.php');

require_once('../models/dao/CostcenterDAO.class.php');
require_once('../models/dto/Costcenter.class.php');
require_once('../models/mysql/CostcenterMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterMySqlExtDAO.class.php');

require_once('../models/dao/CostcenterdetailDAO.class.php');
require_once('../models/dto/Costcenterdetail.class.php');
require_once('../models/mysql/CostcenterdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterdetailMySqlExtDAO.class.php');
////////////////////////////////////////////////////////////////////////////////
//Restauranttable
require_once('../models/dao/RestauranttableDAO.class.php');
require_once('../models/dto/Restauranttable.class.php');
require_once('../models/mysql/RestauranttableMySqlDAO.class.php');
require_once('../models/mysql/ext/RestauranttableMySqlExtDAO.class.php');
//Restauranthall
require_once('../models/dao/RestauranthallDAO.class.php');
require_once('../models/dto/Restauranthall.class.php');
require_once('../models/mysql/RestauranthallMySqlDAO.class.php');
require_once('../models/mysql/ext/RestauranthallMySqlExtDAO.class.php');
//Restaurantorder
require_once('../models/dao/RestaurantorderDAO.class.php');
require_once('../models/dto/Restaurantorder.class.php');
require_once('../models/mysql/RestaurantorderMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantorderMySqlExtDAO.class.php');
//Restaurantorderdetail
require_once('../models/dao/RestaurantorderdetailsDAO.class.php');
require_once('../models/dto/Restaurantorderdetail.class.php');
require_once('../models/mysql/RestaurantorderdetailsMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantorderdetailsMySqlExtDAO.class.php');
////
require_once('../models/dao/QuickprofitclientDAO.class.php');
require_once('../models/dto/Quickprofitclient.class.php');
require_once('../models/mysql/QuickprofitclientMySqlDAO.class.php');
require_once('../models/mysql/ext/QuickprofitclientMySqlExtDAO.class.php');

require_once('../models/dao/QuickprofitdayDAO.class.php');
require_once('../models/dto/Quickprofitday.class.php');
require_once('../models/mysql/QuickprofitdayMySqlDAO.class.php');
require_once('../models/mysql/ext/QuickprofitdayMySqlExtDAO.class.php');

require_once('../models/dao/QuickprofitgeneralDAO.class.php');
require_once('../models/dto/Quickprofitgeneral.class.php');
require_once('../models/mysql/QuickprofitgeneralMySqlDAO.class.php');
require_once('../models/mysql/ext/QuickprofitgeneralMySqlExtDAO.class.php');

require_once('../models/dao/QuickprofitproductDAO.class.php');
require_once('../models/dto/Quickprofitproduct.class.php');
require_once('../models/mysql/QuickprofitproductMySqlDAO.class.php');
require_once('../models/mysql/ext/QuickprofitproductMySqlExtDAO.class.php');

require_once('../models/dao/QuickprofitstoreDAO.class.php');
require_once('../models/dto/Quickprofitstore.class.php');
require_once('../models/mysql/QuickprofitstoreMySqlDAO.class.php');
require_once('../models/mysql/ext/QuickprofitstoreMySqlExtDAO.class.php');
//
require_once('../models/dao/ProductingredientsDAO.class.php');
require_once('../models/dto/Productingredient.class.php');
require_once('../models/mysql/ProductingredientsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductingredientsMySqlExtDAO.class.php');
//
require_once('../models/dao/SizecolorDAO.class.php');
require_once('../models/dto/Sizecolor.class.php');
require_once('../models/mysql/SizecolorMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorMySqlExtDAO.class.php');
//
require_once('../models/dao/SizecolorstoredetailDAO.class.php');
require_once('../models/dto/Sizecolorstoredetail.class.php');
require_once('../models/mysql/SizecolorstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorstoredetailMySqlExtDAO.class.php');
//Onlinestoresetting
require_once('../models/dao/OnlinestoresettingDAO.class.php');
require_once('../models/dto/Onlinestoresetting.class.php');
require_once('../models/mysql/OnlinestoresettingMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinestoresettingMySqlExtDAO.class.php');
//Onlinetemporder
require_once('../models/dao/OnlinetemporderDAO.class.php');
require_once('../models/dto/Onlinetemporder.class.php');
require_once('../models/mysql/OnlinetemporderMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderMySqlExtDAO.class.php');
//Onlinetemporderclient
require_once('../models/dao/OnlinetemporderclientDAO.class.php');
require_once('../models/dto/Onlinetemporderclient.class.php');
require_once('../models/mysql/OnlinetemporderclientMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderclientMySqlExtDAO.class.php');
//Onlinetemporderproduct
require_once('../models/dao/OnlinetemporderproductDAO.class.php');
require_once('../models/dto/Onlinetemporderproduct.class.php');
require_once('../models/mysql/OnlinetemporderproductMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderproductMySqlExtDAO.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');

//
require_once('../models/dao/AccountmovementDAO.class.php');
require_once('../models/dto/Accountmovement.class.php');
require_once('../models/mysql/AccountmovementMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountmovementMySqlExtDAO.class.php');
//
require_once('../models/dao/BankaccountDAO.class.php');
require_once('../models/dto/Bankaccount.class.php');
require_once('../models/mysql/BankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/BankaccountMySqlExtDAO.class.php');

//typeClient
require_once('../models/dao/TypeClientDAO.class.php');
require_once('../models/dto/TypeClient.class.php');
require_once('../models/mysql/TypeClientMySqlDAO.class.php');
require_once('../models/mysql/ext/TypeClientMySqlExtDAO.class.php');

//Sellbilldetailoffer
require_once('../models/dao/SellbilldetailofferDAO.class.php');
require_once('../models/dto/Sellbilldetailoffer.class.php');
require_once('../models/mysql/SellbilldetailofferMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailofferMySqlExtDAO.class.php');
//Sellbilloffer
require_once('../models/dao/SellbillofferDAO.class.php');
require_once('../models/dto/Sellbilloffer.class.php');
require_once('../models/mysql/SellbillofferMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillofferMySqlExtDAO.class.php');
//Collectedparcodestemp
require_once('../models/dao/CollectedparcodestempDAO.class.php');
require_once('../models/dto/Collectedparcodestemp.class.php');
require_once('../models/mysql/CollectedparcodestempMySqlDAO.class.php');
require_once('../models/mysql/ext/CollectedparcodestempMySqlExtDAO.class.php');
//
require_once('../models/dao/DiscountcontrolDAO.class.php');
require_once('../models/dto/Discountcontrol.class.php');
require_once('../models/mysql/DiscountcontrolMySqlDAO.class.php');
require_once('../models/mysql/ext/DiscountcontrolMySqlExtDAO.class.php');
//
require_once('../models/dao/BuypriceshistorybookDAO.class.php');
require_once('../models/dto/Buypriceshistorybook.class.php');
require_once('../models/mysql/BuypriceshistorybookMySqlDAO.class.php');
require_once('../models/mysql/ext/BuypriceshistorybookMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');
//Billtemplate
require_once('../models/dao/BilltemplateDAO.class.php');
require_once('../models/dto/Billtemplate.class.php');
require_once('../models/mysql/BilltemplateMySqlDAO.class.php');
require_once('../models/mysql/ext/BilltemplateMySqlExtDAO.class.php');
//Billtemplatedetail
require_once('../models/dao/BilltemplatedetailDAO.class.php');
require_once('../models/dto/Billtemplatedetail.class.php');
require_once('../models/mysql/BilltemplatedetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BilltemplatedetailMySqlExtDAO.class.php');
//Billoperation
require_once('../models/dao/BilloperationDAO.class.php');
require_once('../models/dto/Billoperation.class.php');
require_once('../models/mysql/BilloperationMySqlDAO.class.php');
require_once('../models/mysql/ext/BilloperationMySqlExtDAO.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');
//Returnsellbillcurr
require_once('../models/dao/ReturnsellbillcurrDAO.class.php');
require_once('../models/dto/Returnsellbillcurr.class.php');
require_once('../models/mysql/ReturnsellbillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillcurrMySqlExtDAO.class.php');
//Sellbillandruterncurr
require_once('../models/dao/SellbillandruterncurrDAO.class.php');
require_once('../models/dto/Sellbillandruterncurr.class.php');
require_once('../models/mysql/SellbillandruterncurrMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruterncurrMySqlExtDAO.class.php');
//Sellbillcurr
require_once('../models/dao/SellbillcurrDAO.class.php');
require_once('../models/dto/Sellbillcurr.class.php');
require_once('../models/mysql/SellbillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillcurrMySqlExtDAO.class.php');
//Known ways
require_once('../models/dao/KnownwaysDAO.class.php');
require_once('../models/dto/Knownway.class.php');
require_once('../models/mysql/KnownwaysMySqlDAO.class.php');
require_once('../models/mysql/ext/KnownwaysMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];

//lang
$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/sellbill/sellbill.php");
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");
include_once("../views/languages/$langs/note.php");



$lang = "";
if (isset($_GET['lang']))
    $lang = $_GET['lang'];

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

  Controller Name :- sellbillController

  OPERTATION in Controller

  1-display add form
  2- add in sellbill, sellbilldetail, sellbillandrutern, sellandruternbilldetail, returnsellbill, returnsellbilldetail tbl
  3- display sucess or error

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

//handling saveid session
/* if(!isset($_SESSION['saveid']))
  {
  $_SESSION['saveid'] = 1;
  }
 */

//here the global templates
//$smarty->display("headbeil.html");
if ($do == "addObgyVisit" || $do == "delObgyVisit" || $do == "updateObgyVisit")
    $_SESSION['dbname'] = (isset($_POST["erpDB"]) && !empty($_POST["erpDB"])) ? $_POST["erpDB"] : ConnectionProperty::getDatabase();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$Programsettingdatabill = $ProgramsettingDAO->load(1);

if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} elseif ($do != "addObgyVisit" && $do != "delObgyVisit" && $do != "updateObgyVisit" && $do != "showallajax" && $do != "billToExcel" && $do != "billToPDF") {
    if ($do == "addresBill") {
        if ($Programsettingdatabill->billRest == 1) {
            //dont call bill-new.js
            $smarty->assign('billnew_js', 0);
            $smarty->display("header-bill.html");
        } elseif ($Programsettingdatabill->billRest == 2) {
            //dont call bills.js
            $smarty->assign('billjs', 0);
            $smarty->display("header-bill-new.html");
        }
    } else {
        $smarty->display("header.html");
    }
}

//here goes the instances and general variables
//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//Accountstree
$accountsTree2 = new Accountstree();
$accountsTreeDAO2 = new AccountstreeMySqlDAO();
$accountsTreeEX2 = new AccountstreeMySqlExtDAO();

//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor2 = new Dailyentrydebtor();
$dailyEntryDebtorDAO2 = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX2 = new DailyentrydebtorMySqlExtDAO();

//Sellbilldetailorder
$Sellbilldetailorder = new Sellbilldetailorder();
$SellbilldetailorderDAO = new SellbilldetailorderMySqlDAO();
$SellbilldetailorderEX = new SellbilldetailorderMySqlExtDAO();

//Sellbillorder
$Sellbillorder = new Sellbillorder();
$SellbillorderDAO = new SellbillorderMySqlDAO();
$SellbillorderEX = new SellbillorderMySqlExtDAO();
//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 = $StoredetailEX = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();
//Store
$myStoreRecord = new StoreMySqlDAO();
$myStoreEx = new StoreMySqlExtDAO();

//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 = $clientDAO = new ClientMySqlDAO();
$myClient = $client = new Client();
$myClientEx = $clientEX = new ClientMySqlExtDAO();
//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = $clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();
//Billname
$myBillnameRecord = new BillnameMySqlDAO();
$myBillnameEx = new BillnameMySqlExtDAO();
//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();
//User
$myUserEx = new UserMySqlExtDAO();

//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//$Productunit= new Productunit();
//$ProductunitDAO= new ProductunitDAO();
//Productcat
$myProductcatRecord = new ProductcatMySqlDAO();
$myProductcatEx = new ProductcatMySqlExtDAO();
//Unit
$myUnitRecord = new UnitMySqlDAO();
//Productserial
$myProductserial = new Productserial();
$myProductserialDAO = new ProductserialMySqlDAO();
$myProductserialEx = new ProductserialMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Soldserialproduct
$soldSerialProduct = new Soldserialproduct();
$soldSerialProductDAO = new SoldserialproductMySqlDAO();
$soldSerialProductExt = new SoldserialproductMySqlExtDAO();

$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();

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

//Temsellbill
$Temsellbill = new Temsellbill();
$TemsellbillDAO = new TemsellbillMySqlDAO();
$TemsellbillEX = new TemsellbillMySqlExtDAO();
//Temsellbilldetail
$Temsellbilldetail = new Temsellbilldetail();
$TemsellbilldetailDAO = new TemsellbilldetailMySqlDAO();
$TemsellbilldetailEX = new TemsellbilldetailMySqlExtDAO();

//Temreturnsellbill
$Temreturnsellbill = new Temreturnsellbill();
$TemreturnsellbillDAO = new TemreturnsellbillMySqlDAO();
$TemreturnsellbillEX = new TemreturnsellbillMySqlExtDAO();
//Temreturnsellbilldetail
$Temreturnsellbilldetail = new Temreturnsellbilldetail();
$TemreturnsellbilldetailDAO = new TemreturnsellbilldetailMySqlDAO();
$TemreturnsellbilldetailEX = new TemreturnsellbilldetailMySqlExtDAO();

//Temsellbillandrutern
$Temsellbillandrutern = new Temsellbillandrutern();
$TemsellbillandruternDAO = new TemsellbillandruternMySqlDAO();
$TemsellbillandruternEX = new TemsellbillandruternMySqlExtDAO();
//Temsellandruternbilldetail
$Temsellandruternbilldetail = new Temsellandruternbilldetail();
$TemsellandruternbilldetailDAO = new TemsellandruternbilldetailMySqlDAO();
$TemsellandruternbilldetailEX = new TemsellandruternbilldetailMySqlExtDAO();

require_once('../models/dao/ClientareaDAO.class.php');
require_once('../models/dto/Clientarea.class.php');
require_once('../models/mysql/ClientareaMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientareaMySqlExtDAO.class.php');

$Clientarea = new Clientarea();
$ClientareaDAO = new ClientareaMySqlDAO();
$ClientareaEX = new ClientareaMySqlExtDAO();

$Costcenterdetail = new Costcenterdetail();
$CostcenterdetailDAO = new CostcenterdetailMySqlDAO();
$CostcenterdetailEX = new CostcenterdetailMySqlExtDAO();

//Costcenter
$Costcenter = new Costcenter();
$CostcenterDAO = new CostcenterMySqlDAO();
$CostcenterEX = new CostcenterMySqlExtDAO();

////////////////////////////////////////////////////////////////////////////////
//Restauranttable
$restaurantTable = new Restauranttable();
$restaurantTableDAO = new RestauranttableMySqlDAO();
$restaurantTableEX = new RestauranttableMySqlExtDAO();
//Restauranthall
$restaurantHall = new Restauranthall();
$restaurantHallDAO = new RestauranthallMySqlDAO();
$restaurantHallEX = new RestauranthallMySqlExtDAO();
//Restaurantorder
$restaurantOrder = new Restaurantorder();
$restaurantOrderDAO = new RestaurantorderMySqlDAO();
$restaurantOrderEX = new RestaurantorderMySqlExtDAO();
//Restaurantorderdetail
$restaurantOrderDetails = new Restaurantorderdetail();
$restaurantOrderDetailsDAO = new RestaurantorderdetailsMySqlDAO();
$restaurantOrderDetailsEX = new RestaurantorderdetailsMySqlExtDAO();
//Restaurantkitchenprint
$restaurantkitchenprint = new Restaurantkitchenprint();
$restaurantkitchenprintDAO = new RestaurantkitchenprintMySqlDAO();
$restaurantkitchenprintEX = new RestaurantkitchenprintMySqlExtDAO();

//Restaurantorderdeliverydetail
$restaurantOrderDeliveryDetail = new Restaurantorderdeliverydetail();
$restaurantOrderDeliveryDetailDAO = new RestaurantorderdeliverydetailsMySqlDAO();
$restaurantOrderDeliveryDetailEX = new RestaurantorderdeliverydetailsMySqlExtDAO();
//Relusergrouppropertie
$myRelusergrouppropertie = new Relusergrouppropertie();
$myRelusergrouppropertieRecord = new RelusergrouppropertiesMySqlDAO();
$myRelusergrouppropertieExt = new RelusergrouppropertiesMySqlExtDAO();

//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
////
$quickProfitClient = new Quickprofitclient();
$quickProfitClientDAO = new QuickprofitclientMySqlDAO();
$quickProfitClientEX = new QuickprofitclientMySqlExtDAO();
//
$quickProfitDay = new Quickprofitday();
$quickProfitDayDAO = new QuickprofitdayMySqlDAO();
$quickProfitDayEX = new QuickprofitdayMySqlExtDAO();
//
$quickProfitGeneral = new Quickprofitgeneral();
$quickProfitGeneralDAO = new QuickprofitgeneralMySqlDAO();
$quickProfitGeneralEX = new QuickprofitgeneralMySqlExtDAO();
//
$quickProfitProduct = new Quickprofitproduct();
$quickProfitProductDAO = new QuickprofitproductMySqlDAO();
$quickProfitProductEX = new QuickprofitproductMySqlExtDAO();
//
$quickProfitStore = new Quickprofitstore();
$quickProfitStoreDAO = new QuickprofitstoreMySqlDAO();
$quickProfitStoreEX = new QuickprofitstoreMySqlExtDAO();

//Productingredient
$productIngredients = new Productingredient();
$productIngredientsDAO = new ProductingredientsMySqlDAO();
$productIngredientsEX = new ProductingredientsMySqlExtDAO();

//
$sizeColor = new Sizecolor();
$sizeColorDAO = new SizecolorMySqlDAO();
$sizeColorEX = new SizecolorMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
////
$onlineStoreSetting = new Onlinestoresetting();
$onlineStoreSettingDAO = new OnlinestoresettingMySqlDAO();
$onlineStoreSettingEX = new OnlinestoresettingMySqlExtDAO();
//Onlinetemporder
$onlineTempOrder = new Onlinetemporder();
$onlineTempOrderDAO = new OnlinetemporderMySqlDAO();
$onlineTempOrderEX = new OnlinetemporderMySqlExtDAO();
//Onlinetemporderclient
$onlineTempOrderClient = new Onlinetemporderclient();
$onlineTempOrderClientDAO = new OnlinetemporderclientMySqlDAO();
$onlineTempOrderClientEX = new OnlinetemporderclientMySqlExtDAO();
//Onlinetemporderproduct
$onlineTempOrderProduct = new Onlinetemporderproduct();
$onlineTempOrderProductDAO = new OnlinetemporderproductMySqlDAO();
$onlineTempOrderProductEX = new OnlinetemporderproductMySqlExtDAO();
//Storemovement
$myStoremovement = new Storemovement();
$myStoremovementRecord = new StoremovementMySqlDAO();
$myStoremovementEx = new StoremovementMySqlExtDAO();

$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;
//
$bankAccount = new Bankaccount();
$bankAccountDAO = new BankaccountMySqlDAO();
$bankAccountEX = new BankaccountMySqlExtDAO();

//typeClient
$type = new TypeClient();
$TypeClientDAO = new TypeClientMySqlDAO();
$TypeClientEX = new TypeClientMySqlExtDAO();
//Sellbilldetailoffer
$sellBillDetailOffer = new Sellbilldetailoffer();
$sellBillDetailOfferDAO = new SellbilldetailofferMySqlDAO();
$sellBillDetailOfferEX = new SellbilldetailofferMySqlExtDAO();
//Sellbilloffer
$sellBillOffer = new Sellbilloffer();
$sellBillOfferDAO = new SellbillofferMySqlDAO();
$sellBillOfferEX = new SellbillofferMySqlExtDAO();

$collectedParcodesTemp = new Collectedparcodestemp();
$collectedParcodesTempDAO = new CollectedparcodestempMySqlDAO();
$collectedParcodesTempEX = new CollectedparcodestempMySqlExtDAO();
//Discountcontrol
$discountControl = new Discountcontrol();
$discountControlDAO = new DiscountcontrolMySqlDAO();
$discountControlEX = new DiscountcontrolMySqlExtDAO();
//Buypriceshistorybook
$buyPricesHistoryBook = new Buypriceshistorybook();
$buyPricesHistoryBookDAO = new BuypriceshistorybookMySqlDAO();
$buyPricesHistoryBookEX = new BuypriceshistorybookMySqlExtDAO();
//Billtemplate
$billTemplate = new Billtemplate();
$billTemplateDAO = new BilltemplateMySqlDAO();
$billTemplateEX = new BilltemplateMySqlExtDAO();
//Billtemplatedetail
$billTemplateDetail = new Billtemplatedetail();
$billTemplateDetailDAO = new BilltemplatedetailMySqlDAO();
$billTemplateDetailEX = new BilltemplatedetailMySqlExtDAO();

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

//Billoperation
$billOperation = new Billoperation();
$billOperationDAO = new BilloperationMySqlDAO();
$billOperationEX = new BilloperationMySqlExtDAO();
//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();
//Returnsellbillcurr
$returnSellBillCurr = new Returnsellbillcurr();
$returnSellBillCurrDAO = new ReturnsellbillcurrMySqlDAO();
$returnSellBillCurrEX = new ReturnsellbillcurrMySqlExtDAO();
//Sellbillandruterncurr
$sellBillAndRuternCurr = new Sellbillandruterncurr();
$sellBillAndRuternCurrDAO = new SellbillandruterncurrMySqlDAO();
$sellBillAndRuternCurrEX = new SellbillandruterncurrMySqlExtDAO();
//Sellbillcurr
$sellBillCurr = new Sellbillcurr();
$sellBillCurrDAO = new SellbillcurrMySqlDAO();
$sellBillCurrEX = new SellbillcurrMySqlExtDAO();

//KnownWays
$knownWays = new Knownway();
$knownWaysDAO = new KnownwaysMySqlDAO();

//
$Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
$smarty->assign("Usergroupdata", $Usergroupdata);

$userdata = $userDAO->load($_SESSION['userid']);
$smarty->assign("userdata", $userdata);


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

$Programsettingdata = $prog = $ProgramsettingDAO->load(1);
$Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
$smarty->assign("Programsettingdata", $Programsettingdata);

$noOfDecimalPlaces = ($Programsettingdata->roundnumbers == 0) ? 0 : (int) $Programsettingdata->noOfDecimalPlaces;
$smarty->assign("noOfDecimalPlaces", $noOfDecimalPlaces);

$smarty->assign("storenegative", $_SESSION['storenegative']);

$sellbillDate = '';
include_once("selllfunction.php");

//used for quick profit
$sellCostsArray = array();
//nedded for collective product##fatma
$sellbillId = 0;
## needed for royal
$firstProductId = 0;
$ordertype = 0;
//check and use the condition that suites this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");

    $billnameData = loadBillname();
    $smarty->assign("billnameData", $billnameData);

    //here the smarty te
    //mplates
    $smarty->display("sellbillview/billname.html");
} elseif ($do == "addsellBill") {

    //here the permission check
    include_once("../public/authentication.php");
    $billnameId = $_GET['billnameid'];
    $billnameData = $myBillnameRecord->load($billnameId);
    $smarty->assign("billnameData", $billnameData);

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);


    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);

    $userSaveData = $mySaveEx->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);

    $allDelegate = R::getAll('SELECT user.* FROM `user`
         WHERE usergroupid = 2');
    $smarty->assign("allDelegate", $allDelegate);

    $billtoret = (int) $_GET['billtoret']; //sell bill to return products from

    $queryString = '';
    if ($userdata->viewbills == 0) {
        $queryString = ' and sellbill.userid =' . $_SESSION['userid'];
    } else if ($userdata->viewbills == 2) {
        $queryString = ' and user2.usergroupid =' . $_SESSION['usergroupid'];
    } else if ($userdata->viewbills == 3) {
        if ($_SESSION['searchinonestore'] == 0) {
            if ($_SESSION['storeids'] != 0) {
                $queryString = ' and sellbill.sellbillstoreid in (' . $_SESSION['storeids'] . ') ';
            }
        } else {
            $queryString = ' and sellbill.sellbillstoreid = ' . $_SESSION['storeid'] . ' ';
        }
    }

    $mylastbill = $mySellbillEx->loadlast($queryString);
    $smarty->assign("mylastbill", $mylastbill);

    if ($billnameId != "") {
        $billsettingsData = loadBillProperty($billnameId);


        if ($billsettingsData[45]->billsettingsvalue == 0) {
            $allCostcenter = $CostcenterEX->queryAllnotdel();
            $smarty->assign("allCostcenter", $allCostcenter);
        }

        if ($billsettingsData[99]->billsettingsvalue == 1) {
            $allBillTemplates = $billTemplateDAO->queryAll();
            $smarty->assign("allBillTemplates", $allBillTemplates);
        }

        if ($billsettingsData[101]->billsettingsvalue == 0) {
            $billOperations = $billOperationDAO->queryAll();
            $smarty->assign("billOperations", $billOperations);
        }

        if ($billsettingsData[109]->billsettingsvalue == 0) {
            $knownWays = $knownWaysDAO->queryAll();
            $smarty->assign("knownWays", $knownWays);
        }
        /*  print_r('<pre>');
          print_r($billsettingsData);
          print_r('<pre>'); */
        ##get client serial
        $DBName = ConnectionProperty::getDatabase();
        if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
            $DBName = $_SESSION['dbname'];
        }

        //check if bill sell or sell and return
        ##settingsvalue14 is sell
        ##settingsvalue0 is return
        ##1 off ,0 on
        $offerId = (int) $_GET['offerId'];
        $autoSaveFlag = 0;
        $defaultClientId = 1;
        if ((int) $billnameData->ordertype == 0) { //bill
            //            if (isset($_GET["client"]) && (int) $_GET["client"] > 0) {
            //                $defaultClientId = (int) $_GET["client"];
            //            }
            if (isset($_COOKIE["clientId" . $_SESSION['userid']]) && (int) $_COOKIE["clientId" . $_SESSION['userid']] > 0) {
                $defaultClientId = (int) $_COOKIE["clientId" . $_SESSION['userid']];
                // set the expiration date to one hour ago "del cookie"
                setcookie("clientId" . $_SESSION['userid'], "", time() - 3600);
            }

            $userId = $_SESSION['userid'];

            if ($billsettingsData[14]->billsettingsvalue == 0 && $billsettingsData[0]->billsettingsvalue == 1) {
                //sell only
                $nextId = 0;
                if ($billsettingsData[98]->billsettingsvalue == 1) { //autosave is enabled
                    $bill_is = 'sell';
                    $result = $mySellbillEx->runSelectQuery("select sellbillid from sellbill where autoSaveFlag=1 and conditions=1 and sellbillclientid=$defaultClientId and userid=$userId order by sellbillid desc limit 1");
                    $nextId = (int) $result[0]->sellbillid; //last bill with auto save not completed
                }
                if (empty($nextId)) {
                    $nextId = $mySellbillEx->getAutoIncrementValue($DBName);
                } else {
                    $autoSaveFlag = 1;
                }
            } elseif ($billsettingsData[14]->billsettingsvalue == 0 && $billsettingsData[0]->billsettingsvalue == 0) {
                //sell and return
                $nextId = 0;
                if ($billsettingsData[98]->billsettingsvalue == 1) { //autosave is enabled
                    $bill_is = 'sellAndRet';
                    $result = $mySellbillEx->runSelectQuery("select sellbillid from sellbillandrutern where autoSaveFlag=1 and conditions=1 and sellbillclientid=$defaultClientId and userid=$userId order by sellbillid desc limit 1");
                    $nextId = (int) $result[0]->sellbillid; //last bill with auto save not completed
                }
                if (empty($nextId)) {
                    $nextId = $mySellbillandruternEx->getAutoIncrementValue($DBName);
                } else {
                    $autoSaveFlag = 1;
                }
            } else if ($billsettingsData[14]->billsettingsvalue == 1 && $billsettingsData[0]->billsettingsvalue == 0) {
                //return sell bill
                $nextId = 0;
                if ($billsettingsData[98]->billsettingsvalue == 1) { //autosave is enabled
                    $bill_is = 'ret';
                    $result = $mySellbillEx->runSelectQuery("select returnsellbillid as sellbillid from returnsellbill where autoSaveFlag=1 and conditions=1 and returnsellbillclientid=$defaultClientId and userid=$userId order by returnsellbillid desc limit 1");
                    $nextId = (int) $result[0]->sellbillid; //last bill with auto save not completed
                }
                if (empty($nextId)) {
                    $nextId = $myReturnsellbillEx->getAutoIncrementValue($DBName);
                } else {
                    $autoSaveFlag = 1;
                }
            }
            if ($autoSaveFlag == 1 && $nextId > 0) { //adding offer as bill
                ################################################################
                $sellbillstoreid = 0;
                $sellbillclientid = 0;
                switch ($bill_is) {
                    case 'sellAndRet':
                        $mysellbilldata = $mySellbillandruternRecord->load($nextId);
                        $sellbillstoreid = $mysellbilldata->sellbillstoreid;
                        $sellbillclientid = $mysellbilldata->sellbillclientid;
                        break;
                    case 'sell':
                        $mysellbilldata = $mySellbillRecord->load($nextId);
                        $sellbillstoreid = $mysellbilldata->sellbillstoreid;
                        $sellbillclientid = $mysellbilldata->sellbillclientid;
                        break;
                    case 'ret':
                        $mysellbilldata = $myReturnsellbillRecord->load($nextId);
                        $sellbillstoreid = $mysellbilldata->returnsellbillstoreid;
                        $sellbillclientid = $mysellbilldata->returnsellbillclientid;
                        break;
                }


                $smarty->assign("tempSaveBillId", $nextId);
                $smarty->assign("manyParcodes", 1);
                //$smarty->assign("manyParcodesSupplier", $mysellbilldata->sellbillclientid);
                $smarty->assign("manyParcodesPriceType", 0);
                $smarty->assign("manyParcodesStoreid", $sellbillstoreid);
                $smarty->assign("manyParcodesSellerid", $mysellbilldata->sellerid);

                $myclientdata = $myClientRecord->load($sellbillclientid);
                $smarty->assign("myclientdata", $myclientdata);

                //                if ($userdata->userstoreid > 0) {
                //                    $userdata->userstoreid = $mysellbilldata->sellbillstoreid;
                //                }
                ################################################################
                //get  sell bill detales data
                $i = 1;
                switch ($bill_is) {
                    case 'sellAndRet':
                        $mysellbildetales = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($nextId, 0);
                        foreach ($mysellbildetales as $mydetales) {
                            $smarty->assign("manyParcodesPriceType", $mydetales->pricetype);

                            $parentId = $mydetales->sellbilldetailcatid;
                            //names of product's parents
                            $pathArr = getProductPath_recursive($parentId, $categories);

                            //new product name with all path
                            $mydetales->productName = $mydetales->productName . '/' . $pathArr;

                            $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->sellbilldetailproductid);
                            $smarty->assign("myunitdata" . $i, $myunitdata);
                            //
                            $soldSerialsInDetailsArr = array();
                            if (!empty($mydetales->soldSerialsInDetails)) {
                                foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                                    //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                                    $issold = $myProductserialDAO->load($productserailid);
                                    array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
                                }
                                $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
                            }
                            $i++;
                        }
                        $smarty->assign("mysellbildetales", $mysellbildetales);
                        $smarty->assign("detalesitr", count($mysellbildetales));
                        //ret part
                        $returnmysellbildetales = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($nextId, 1);
                        foreach ($returnmysellbildetales as $mydetales) {
                            $smarty->assign("manyParcodesPriceType", $mydetales->pricetype);

                            $parentId = $mydetales->returnsellbilldetailcatid;
                            //names of product's parents
                            $pathArr = getProductPath_recursive($parentId, $categories);

                            //new product name with all path
                            $mydetales->productName = $mydetales->productName . '/' . $pathArr;

                            $myreunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->returnsellbilldetailproductid);
                            $smarty->assign("myreunitdata" . $i, $myreunitdata);
                            //
                            $soldSerialsInDetailsArr = array();
                            if (!empty($mydetales->soldSerialsInDetails)) {
                                foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                                    //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                                    $issold = $myProductserialDAO->load($productserailid);
                                    array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
                                }
                                $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
                            }
                            $i++;
                        }
                        $smarty->assign("returnmysellbildetales", $returnmysellbildetales);
                        $smarty->assign("returndetalesitr", count($returnmysellbildetales));
                        break;
                    case 'sell':
                        $mysellbildetales = $mySellbilldetailEx->queryWithSellBillId($nextId);
                        foreach ($mysellbildetales as $mydetales) {
                            $smarty->assign("manyParcodesPriceType", $mydetales->pricetype);

                            $parentId = $mydetales->sellbilldetailcatid;
                            //names of product's parents
                            $pathArr = getProductPath_recursive($parentId, $categories);

                            //new product name with all path
                            $mydetales->productName = $mydetales->productName . '/' . $pathArr;
                            $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->sellbilldetailproductid);
                            $smarty->assign("myunitdata" . $i, $myunitdata);

                            if ($offerId > 0) { //adding offer as bill
                                $mydetales->sellbilldetailtax = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and is_offer =1', [$mydetales->sellbilldetailid]);
                            } elseif ($ordertype == 1) { //bill
                                //$mydetales->sellbilldetailtax = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and (is_offer is null or is_offer !=1)', [$mydetales->sellbilldetailid]);
                            }

                            //
                            $soldSerialsInDetailsArr = array();
                            if (!empty($mydetales->soldSerialsInDetails)) {
                                foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                                    //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                                    $issold = $myProductserialDAO->load($productserailid);
                                    array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
                                }
                                $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
                            }
                            $i++;
                        }
                        $smarty->assign("mysellbildetales", $mysellbildetales);
                        $smarty->assign("detalesitr", count($mysellbildetales));
                        break;
                    case 'ret':
                        $returnmysellbildetales = $myReturnsellbilldetailEx->queryWithReturnsellbillId($nextId);
                        foreach ($returnmysellbildetales as $mydetales) {
                            $smarty->assign("manyParcodesPriceType", $mydetales->pricetype);

                            $parentId = $mydetales->returnsellbilldetailcatid;
                            //names of product's parents
                            $pathArr = getProductPath_recursive($parentId, $categories);

                            //new product name with all path
                            $mydetales->productName = $mydetales->productName . '/' . $pathArr;

                            $myreunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->returnsellbilldetailproductid);
                            $smarty->assign("myreunitdata" . $i, $myreunitdata);
                            //
                            $soldSerialsInDetailsArr = array();
                            if (!empty($mydetales->soldSerialsInDetails)) {
                                foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                                    //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                                    $issold = $myProductserialDAO->load($productserailid);
                                    array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
                                }
                                $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
                            }
                            $i++;
                        }
                        $smarty->assign("returnmysellbildetales", $returnmysellbildetales);
                        $smarty->assign("returndetalesitr", count($returnmysellbildetales));
                        break;
                }

                $smarty->assign("mysellbilldata", $mysellbilldata);
                ########################################
                $smarty->assign("customeditsellbill", 1);
            }
            if ($billtoret > 0) {
                $mysellbilldata = $mySellbillRecord->load($billtoret);
                $sellbillstoreid = $mysellbilldata->sellbillstoreid;
                $sellbillclientid = $defaultClientId = $mysellbilldata->sellbillclientid;
                $smarty->assign("billtoret", $billtoret);
                $smarty->assign("manyParcodes", 1);
                $smarty->assign("manyParcodesStoreid", $sellbillstoreid);
                $myclientdata = $myClientRecord->load($sellbillclientid);
                $smarty->assign("myclientdata", $myclientdata);

                $mysellbildetales = $mySellbilldetailEx->queryWithSellBillId($billtoret);
                foreach ($mysellbildetales as $mydetales) {
                    $smarty->assign("manyParcodesPriceType", $mydetales->pricetype);

                    $parentId = $mydetales->sellbilldetailcatid;
                    //names of product's parents
                    $pathArr = getProductPath_recursive($parentId, $categories);

                    //new product name with all path
                    $mydetales->productName = $mydetales->productName . '/' . $pathArr;
                    $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->sellbilldetailproductid);
                    $smarty->assign("myunitdata" . $i, $myunitdata);

                    if ($offerId > 0) { //adding offer as bill
                        $mydetales->sellbilldetailtax = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and is_offer =1', [$mydetales->sellbilldetailid]);
                    } elseif ($ordertype == 1) { //bill
                        //$mydetales->sellbilldetailtax = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and (is_offer is null or is_offer !=1)', [$mydetales->sellbilldetailid]);
                    }

                    //
                    $soldSerialsInDetailsArr = array();
                    if (!empty($mydetales->soldSerialsInDetails)) {
                        foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                            //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                            $issold = $myProductserialDAO->load($productserailid);
                            array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
                        }
                        $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
                    }
                    $i++;
                }
                $smarty->assign("returnmysellbildetales", $mysellbildetales);
                $smarty->assign("returndetalesitr", count($mysellbildetales));

                $smarty->assign("mysellbilldata", $mysellbilldata);
                ########################################
                $smarty->assign("customeditsellbill", 1);
                $smarty->assign("customsellbill", 1);
                $smarty->assign("customreturnsellbill", 1);
                $smarty->assign("customeditsellbill", 1);
                $smarty->assign("customsellbillModel", 1);
            }
            if ($offerId > 0) { //adding offer as bill
                ################################################################
                $mysellbilldata = $sellBillOfferDAO->load($offerId);

                $smarty->assign("offerId", $offerId);
                $smarty->assign("manyParcodes", 1);
                //$smarty->assign("manyParcodesSupplier", $mysellbilldata->sellbillclientid);
                $smarty->assign("manyParcodesPriceType", 0);
                $smarty->assign("manyParcodesStoreid", $mysellbilldata->sellbillstoreid);
                $smarty->assign("manyParcodesSellerid", $mysellbilldata->sellerid);

                $smarty->assign("addManyParcodebilloperationid", $mysellbilldata->billoperationid);
                $smarty->assign("addManyParcodeobgyBillType", $mysellbilldata->obgyBillType);

                $myclientdata = $myClientRecord->load($mysellbilldata->sellbillclientid);
                $smarty->assign("myclientdata", $myclientdata);

                if ($userdata->userstoreid > 0) {
                    $userdata->userstoreid = $mysellbilldata->sellbillstoreid;
                }

                ################################################################
                //get  sell bill detales data
                $mysellbildetales = $sellBillDetailOfferEX->queryWithSellBillId($offerId);
                $i = 1;
                foreach ($mysellbildetales as $mydetales) {
                    $smarty->assign("manyParcodesPriceType", $mydetales->pricetype);

                    $parentId = $mydetales->sellbilldetailcatid;
                    //names of product's parents
                    $pathArr = getProductPath_recursive($parentId, $categories);

                    $mydetales->sellbilldetailtax = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and is_offer =1', [$mydetales->sellbilldetailid]);

                    //new product name with all path
                    $mydetales->productName = $mydetales->productName . '/' . $pathArr;

                    $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->sellbilldetailproductid);
                    $smarty->assign("myunitdata" . $i, $myunitdata);
                    $i++;
                }
                $smarty->assign("mysellbildetales", $mysellbildetales);
                $smarty->assign("detalesitr", count($mysellbildetales));
                $smarty->assign("mysellbilldata", $mysellbilldata);
                ########################################
                $smarty->assign("customeditsellbill", 1);
            }
        } elseif ((int) $billnameData->ordertype == 1) { //offer
            $nextId = $sellBillOfferEX->getAutoIncrementValue($DBName);
        }

        if ($billsettingsData[92]->billsettingsvalue == 1) { //get tax bill auto increament
            $nextId = (int) $mySellbillEx->getNextTaxBillNumber($DBName) + 1;
        }

        //visa payment
        if ($billsettingsData[86] == 1) {
            $bankAccounts = $bankAccountEX->queryWithOrder2ForVisaPayment();
            $smarty->assign('bankAccounts', $bankAccounts);
        }
        //saves are dropdown list
        $smarty->assign('sessionSave', $_SESSION['saveid']);
        if ($billsettingsData[87] == 1) {
            $allSaves = $mySaveRecord->queryByConditions(0);
            $smarty->assign('allSaves', $allSaves);
        }

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

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

        $allclientarea = $ClientareaDAO->queryAll();
        $smarty->assign("allclientarea", $allclientarea);

        $unique = uniqid("0");
        $smarty->assign("unique", $unique);

        //        $clientData = loadClient();
        //        $smarty->assign("clientData", $clientData);
        if (((int) $billnameData->ordertype == 0 && $offerId > 0) || $defaultClientId > 1) { //adding offer as bill
            //data is loader before
        } else {
            $myclientdata = array();
            if (empty($Usergroupdata->showClientAndSupplierOne)) {
                if ($billsettingsData[122]->billsettingsvalue == 0) {
                    $myclientdata = $myClientRecord->load(1);
                } else {
                    $myclientdata = $myClientRecord->load($Programsettingdatabill->laterNakdiClientId);
                }
            }
            $smarty->assign("myclientdata", $myclientdata);
        }

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

        $typeClient = $TypeClientDAO->queryAll();
        $smarty->assign("typeClient", $typeClient);

        $sellerData = loadseller();
        $smarty->assign("sellerData", $sellerData);

        $smarty->assign("billnameid", $billnameId);

        $billnameAddData = $myBillnameRecord->load($billnameId);
        $smarty->assign("billnameAddData", $billnameAddData);

        //get product categories
        // $categoriesData = loadProductCat();
        //$smarty->assign("categoriesData", $categoriesData);
        ##التصنيفات
        $catDataReport = getCategoryChilds();
        $smarty->assign("catDataReport", $catDataReport[1]);

        //get units
        $unitsData = loadUnit();
        $smarty->assign("unitsData", $unitsData);

        $smarty->assign("today", date("Y-m-d H:i:s"));

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $previousPriceStatus = checkPreviousPrice();
        $smarty->assign("previousPriceStatus", $previousPriceStatus);

        $Programsettingdata = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        $smarty->assign("Programsettingdata", $Programsettingdata);

        $allDiscounts = $discountControlDAO->queryAll();
        $smarty->assign("allDiscounts", json_encode($allDiscounts));

        if (isset($_SESSION["printURL"])) {
            $smarty->assign("printURL", $_SESSION["printURL"]);
        } else {
            $smarty->assign("printURL", "");
        }

        unset($_SESSION["printURL"]);
        //here the smarty templates
        if ($lang == "en")
            $smarty->display("sellbillview/bill-ltr.html");
        else
            $smarty->display("sellbillview/bill.html");

        $smarty->assign("customsellbill", 1);
        $smarty->assign("customreturnsellbill", 1);
        $smarty->assign("customsellbillModel", 1);
        $smarty->assign("customSellProductModel", 1);
    } else {
        header("location:sellbillController.php");
    }
} elseif ($do == "updateReservation") {
    if (isset($_GET["reservation"]) && (int) $_GET["reservation"] == 3 && isset($_GET["sellbillid"]) && (int) $_GET["sellbillid"] > 0) {
        $sellbillid = (int) $_GET["sellbillid"];
        $bill = $mySellbillRecord->load($sellbillid);
        $bill->billReservation = 3;
        $mySellbillRecord->update($bill);
    }
    header('Location:' . $hosturl . '/controllers/salesreportbills.php?do=billReservation');
}
##
elseif ($do == "addsellBillManyParcodes") {
    //here the permission check
    //include_once("../public/authentication.php");
    $manyParcodes = $_POST['manyParcodes'];
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        $manyParcodes = str_replace('ه', 'i', $manyParcodes);
        $manyParcodes = str_replace('÷', 'i', $manyParcodes);
        $manyParcodes = str_replace('/', 'i', $manyParcodes);
        $manyParcodes = str_replace('I', 'i', $manyParcodes);
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
    }

    $manyParcodesSupplier = (int) $_POST['manyParcodesSupplier'];
    $manyParcodesPriceType = (int) $_POST['manyParcodesPriceType'];
    $manyParcodesStoreid = (int) $_POST['manyParcodesStoreid'];
    $manyParcodesSellerid = (int) $_POST['manyParcodesSellerid'];
    $manyParcodesSaveid = (int) $_POST['manyParcodesSaveid'];
    $addManyParcodesType = $_POST['addManyParcodesType'];
    $addManyParcodebilloperationid = (int) $_POST['addManyParcodebilloperationid'];
    $addManyParcodebillCurrencyId = (int) $_POST['addManyParcodebillCurrencyId'];
    $addManyParcodebillCFactor = (float) $_POST['addManyParcodebillCFactor'];
    $addManyParcodebillOtherCFactor = (float) $_POST['addManyParcodebillOtherCFactor'];
    $addManyParcodeobgyBillType = (int) $_POST['addManyParcodeobgyBillType'];
    $addManyParcodeknownwayId = (int) $_POST['addManyParcodeknownwayId'];
    $smarty->assign("manyParcodes", 1);
    $smarty->assign("manyParcodesSupplier", $manyParcodesSupplier);
    $smarty->assign("manyParcodesPriceType", $manyParcodesPriceType);
    $smarty->assign("manyParcodesStoreid", $manyParcodesStoreid);
    $smarty->assign("manyParcodesSellerid", $manyParcodesSellerid);
    $smarty->assign("manyParcodesSaveid", $manyParcodesSaveid);
    $smarty->assign("addManyParcodebilloperationid", $addManyParcodebilloperationid);
    $smarty->assign("addManyParcodeknownwayId", $addManyParcodeknownwayId);

    if ($userdata->userstoreid > 0) {
        $userdata->userstoreid = $manyParcodesStoreid;
    }
    $_GET['billnameid'] = (int) $_POST['addManyParcodebillnameid'];
    if (empty($_GET['billnameid'])) {
        if ($addManyParcodesType == "ret") {
            $_GET['billnameid'] = 5;
        } else {
            $_GET['billnameid'] = 3;
        }
    }
    if ($manyParcodes == "") {
        //no parcodes or ids passed
        header("location:sellbillController.php?do=addsellBill&billnameid=" . $_GET['billnameid']);
        exit();
    }
    //1-remove enter from string
    $manyParcodes = str_replace("\n", ",", $manyParcodes);
    $manyParcodes = rtrim($manyParcodes, ',');
    ##also clean by allow only 0-9, i , ',' , '.'  =>. are for quantity part it might exist or no like 00001   or 00001.10.5 then quantity is 10.5
    $manyParcodes = preg_replace('/[^0-9,i.]+/', '', $manyParcodes);
    //2-remove mess come with enter
    $temp = '';
    $idsStringDistinct = '';
    $parcodeSKVArr = array();
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        foreach (explode(',', $manyParcodes) as $value) {
            $value = trim($value); //trim is a must for enter separated
            if ($value[0] == 'i') {
                $value = 'i' . (int) str_replace('i', '', $value);
                $idsStringDistinct .= str_replace('i', '', $value) . ',';
            }
            $t = explode('.', $value, 2);
            $value = $t[0];
            $repeat = (float) $t[1];
            if (empty($repeat))
                $repeat = 1;

            if (!isset($parcodeSKVArr[$value])) {
                $parcodeSKVArr[$value] = 0;
                $temp .= $value . ',';
            }
            $parcodeSKVArr[$value] += $repeat;

            //            if ($repeat > 0) {//use repeat to represent quantity
            //                for ($i = 0; $i < $repeat; $i++) {
            //                    $temp .= $value . ',';
            //                }
            //            } else {
            //                $temp .= $value . ',';
            //            }
        }
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
        foreach (explode(',', $manyParcodes) as $value) {
            $value = trim($value); //trim is a must for enter separated
            $t = explode('.', $value, 2);
            $value = $t[0];
            $repeat = (float) $t[1];
            if (empty($repeat))
                $repeat = 1;

            if (!isset($parcodeSKVArr[$value])) {
                $parcodeSKVArr[$value] = 0;
                $temp .= $value . ',';
            }
            $parcodeSKVArr[$value] += $repeat;
            //            if ($repeat > 0) {
            //                for ($i = 0; $i < $repeat; $i++) {//use repeat to represent quantity
            //                    $temp .= $value . ',';
            //                }
            //            } else {
            //                $temp .= $value . ',';
            //            }
        }
    }

    $manyParcodes = rtrim($temp, ',');
    //get distinct parcodes only"not ids" out of recieved string
    $manyParcodesArranged = array_count_values(explode(',', $manyParcodes));
    $parcodesString = '';
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        foreach ($manyParcodesArranged as $key => $value) {
            if ($key[0] != 'i') {
                $parcodesString .= $key . ',';
            }
        }
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
        foreach ($manyParcodesArranged as $key => $value) {
            $parcodesString .= '"' . $key . '",';
        }
    }

    $parcodesString = rtrim($parcodesString, ',');
    //replace parcodes with ids
    if ($parcodesString != '') {
        $productsData = $productExt->getProductIdByParcode($parcodesString);
        $productsDataSizeColor = $sizeColorStoreDetailEX->queryByParcodeInSimple($parcodesString);
        //if i have 2 parcodes same and after each other ex",00003,00003," str replace will replace first occurance only
        $manyParcodes = str_replace(',', ',,', $manyParcodes);
        $manyParcodes = ',' . $manyParcodes . ',';

        ## replace prcode with productid in the string
        foreach ($productsData as $value) {
            $idsStringDistinct .= $value->productId . ",";
            $manyParcodes = str_replace(',' . $value->parcode . ',', ',i' . $value->productId . ',', $manyParcodes);
            $parcodeSKVArr[$value->productId] = $parcodeSKVArr[$value->parcode];
            if ($value->parcode != $value->productId) {
                unset($parcodeSKVArr[$value->parcode]);
            }
        }
        ##make parcodes of size color
        $manyParcodesSizeColor = '';
        $manyParcodesSizeColorDistinct = '';
        foreach ($productsDataSizeColor as $value) {
            $manyParcodes = str_replace(',' . $value->parcode . ',', ',,', $manyParcodes);
            $manyParcodesSizeColorDistinct .= "'" . $value->parcode . "',";
            for ($i = 0; $i < $manyParcodesArranged["$value->parcode"]; $i++) {
                $manyParcodesSizeColor .= $value->parcode . ",";
            }
        }

        $manyParcodes = rtrim(ltrim($manyParcodes, ","), ","); //remove first and last comma s
        $manyParcodes = str_replace(',,', ',', $manyParcodes);
        $manyParcodesSizeColor = rtrim(ltrim($manyParcodesSizeColor, ","), ","); //remove first and last comma s
    }
    $manyParcodes = str_replace('i', '', $manyParcodes);

    $idsStringDistinct = rtrim($idsStringDistinct, ',');
    $manyParcodesSizeColorDistinct = rtrim($manyParcodesSizeColorDistinct, ',');
    //count repeats of each value
    $allparcodes = $manyParcodes . ',' . $manyParcodesSizeColor;
    $manyParcodesArranged = array_count_values(explode(',', $allparcodes));

    ##make sure to change barcodes that start with i to just product id
    $parcodeSKVArrTemp = array();
    foreach ($parcodeSKVArr as $key => $value) {
        if ($key[0] != 'i') {
            $parcodeSKVArrTemp[$key] = $parcodeSKVArr[$key];
        } else {
            $newKey = $key;
            $newKey = (int) str_replace("i", "", $newKey);
            if (isset($parcodeSKVArr[$newKey])) {
                $parcodeSKVArrTemp[$newKey] = $parcodeSKVArr[$newKey] + $parcodeSKVArr[$key];
            } else {
                $parcodeSKVArrTemp[$newKey] = $parcodeSKVArr[$key];
            }
        }
    }
    $parcodeSKVArr = $parcodeSKVArrTemp;
    //##order $parcodeSKVArr to be like the order coming from user , not ordered by product id
    $parcodeSKVArrTemp = array();
    foreach (explode(',', $allparcodes) as $proId) {
        $parcodeSKVArrTemp[$proId] = $parcodeSKVArr[$proId];
    }
    $parcodeSKVArr = $parcodeSKVArrTemp;
    ############################################################################

    if (empty($idsStringDistinct))
        $idsStringDistinct = 0;
    if (empty($manyParcodesSizeColorDistinct))
        $manyParcodesSizeColorDistinct = "'-1-1'";
    //get  sell bill detales data
    //$mysellbildetales = $mySellbilldetailEx->queryWithSellBillId($sellbillid);
    $products = $productExt->queryAllDistinctWithQueryStringUnion(" and productId in ($idsStringDistinct) ", " and sizecolorstoredetail.parcode in ($manyParcodesSizeColorDistinct) ");
    $i = 1;
    $products_ordered = array();
    //$manyParcodesArranged
    foreach ($parcodeSKVArr as $key => $value) {
        foreach ($products as $pro) {
            if (!empty($key) && ((int) $pro->productId === $key || $pro->sizeColorParcode == $key)) {
                //$pro->parcode = $pro->parcode;
                $pro->sellbilldetailcatid = $pro->productCatId;
                $pro->sellbilldetailproductid = $pro->productId;
                if ((int) $pro->sizeid > 0 && (int) $pro->colorid > 0) {
                    $pro->parcode = $pro->sizeColorParcode;
                }

                $pro->otherdetailquantity = 0;
                $pro->bouns = 0;
                $pro->discounttype = 0;
                $pro->discountvalue = 0;
                $pro->sellbilldetailquantity = $parcodeSKVArr[$key]; //use no of repeats of productId
                switch ($manyParcodesPriceType) {
                    case 0: //productSellAllPrice
                        $pro->sellbilldetailprice = $pro->productSellAllPrice;
                        break;
                    case 1: //productSellUnitPrice
                        $pro->sellbilldetailprice = $pro->productSellUnitPrice;
                        break;
                    case 2: //productSellHalfPrice
                        $pro->sellbilldetailprice = $pro->productSellHalfPrice;
                        break;

                    default:
                        $pro->sellbilldetailprice = $pro->productSellUnitPrice;
                        break;
                }
                $pro->discountvalue = 0;
                $pro->storeid = $manyParcodesStoreid;
                $pro->note = '';
                $pro->pricetype = $pro->parcode; //later
                ##########
                $parentId = $pro->sellbilldetailcatid;
                //names of product's parents
                $pathArr = getProductPath_recursive($parentId, $categories);

                //new product name with all path
                $pro->productName = $pro->productName . '/' . $pathArr;

                if (!is_null($pro->sizeName) && !empty($pro->sizeName) && (int) $pro->sizeid > 0) {
                    $pro->productName .= '/' . $pro->sizeName;
                }
                if (!is_null($pro->colorName) && !empty($pro->colorName) && (int) $pro->colorid > 0) {
                    $pro->productName .= '/' . $pro->colorName;
                }
                $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($pro->sellbilldetailproductid);
                $pro->productunitid = $myunitdata[0]->productunitid;
                if ($addManyParcodesType == "ret") {
                    $smarty->assign("myreunitdata" . $i, $myunitdata);
                } else {
                    $smarty->assign("myunitdata" . $i, $myunitdata);
                }


                #######
                $sellbilldetailData = getProductPriceFromSellBill($pro->sellbilldetailproductid, $manyParcodesSupplier, $pro->productunitid);
                $pro->background = '';
                if (count($sellbilldetailData[0]) > 0 && $Programsettingdata->showPrevPrices == 0) {
                    $pro->sellbilldetailprice = $sellbilldetailData[1];
                    $pro->background = '#b7dfa4';
                } else {
                    //get category discounts
                    $catData = $productCatDAO->load($pro->sellbilldetailcatid);
                    if ($catData->selldiscount > 0 && $catData->discounttype == 0) {
                        $productPrice = $pro->sellbilldetailprice - $catData->selldiscount;
                    } elseif ($catData->selldiscount > 0 && $catData->discounttype == 1) {
                        $productPrice = $pro->sellbilldetailprice - ((($catData->selldiscount) / 100) * ($pro->sellbilldetailprice));
                    } else {
                        $productPrice = $pro->sellbilldetailprice;
                    }
                    $pro->sellbilldetailprice = $productPrice;
                }

                $pro->sellbilldetailtotalprice = $pro->sellbilldetailquantity * $pro->sellbilldetailprice;
                #############


                $i++;
                array_push($products_ordered, $pro);
            }
        }
    }

    if ($addManyParcodesType == "ret") {
        $smarty->assign("returnmysellbildetales", $products_ordered);
        $smarty->assign("returndetalesitr", count($products_ordered));
    } else {
        $smarty->assign("mysellbildetales", $products_ordered);
        $smarty->assign("detalesitr", count($products_ordered));
    }
    ////////////////////////////////////////////////////
    $mylastbill = $mySellbillEx->loadlast();
    $smarty->assign("mylastbill", $mylastbill);

    $knownWays = $knownWaysDAO->queryAll();
    $smarty->assign("knownWays", $knownWays);

    ##bill currency Data
    $billCurrData = new stdClass();
    $billCurrData->currencyId = $addManyParcodebillCurrencyId;
    $billCurrData->conversionFactor = $addManyParcodebillCFactor;
    $billCurrData->otherconversionFactor = $addManyParcodebillOtherCFactor;
    $smarty->assign("billCurrData", $billCurrData);

    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);
    $userSaveData = $mySaveEx->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);

    $billOperations = $billOperationDAO->queryAll();
    $smarty->assign("billOperations", $billOperations);

    $billnameId = $_GET['billnameid'];
    $billnameData = $myBillnameRecord->load($billnameId);
    $smarty->assign("billnameData", $billnameData);

    if ($billnameId != "") {
        $billsettingsData = loadBillProperty($billnameId);

        /*  print_r('<pre>');
          print_r($billsettingsData);
          print_r('<pre>'); */
        ##get client serial
        $DBName = ConnectionProperty::getDatabase();
        if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
            $DBName = $_SESSION['dbname'];
        }

        //check if bill sell or sell and return
        ##settingsvalue14 is sell
        ##settingsvalue0 is return
        ##1 off ,0 on
        if ($billsettingsData[14]->billsettingsvalue == 0 && $billsettingsData[0]->billsettingsvalue == 1) {
            //sell only
            $nextId = $mySellbillEx->getAutoIncrementValue($DBName);
        } elseif ($billsettingsData[14]->billsettingsvalue == 0 && $billsettingsData[0]->billsettingsvalue == 0) {
            //sell and return
            $nextId = $mySellbillandruternEx->getAutoIncrementValue($DBName);
        } else if ($billsettingsData[14]->billsettingsvalue == 1 && $billsettingsData[0]->billsettingsvalue == 0) {
            //return sell bill
            $nextId = $myReturnsellbillEx->getAutoIncrementValue($DBName);
        }
        $smarty->assign("nextId", $nextId);

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

        //saves are dropdown list
        //$smarty->assign('sessionSave', $_SESSION['saveid']);
        $smarty->assign('sessionSave', $manyParcodesSaveid);
        if ($billsettingsData[87] == 1) {
            $allSaves = $mySaveRecord->queryByConditions(0);
            $smarty->assign('allSaves', $allSaves);
        }

        $allclientarea = $ClientareaDAO->queryAll();
        $smarty->assign("allclientarea", $allclientarea);

        $unique = uniqid("0");
        $smarty->assign("unique", $unique);

        //        $clientData = loadClient();
        //        $smarty->assign("clientData", $clientData);
        $myclientdata = $myClientRecord->load($manyParcodesSupplier);
        $smarty->assign("myclientdata", $myclientdata);

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

        $sellerData = loadseller();
        $smarty->assign("sellerData", $sellerData);

        $smarty->assign("billnameid", $billnameId);

        $billnameAddData = $myBillnameRecord->load($billnameId);
        $smarty->assign("billnameAddData", $billnameAddData);

        //get product categories
        // $categoriesData = loadProductCat();
        //$smarty->assign("categoriesData", $categoriesData);
        ##التصنيفات
        $catDataReport = getCategoryChilds();
        $smarty->assign("catDataReport", $catDataReport[1]);

        //get units
        $unitsData = loadUnit();
        $smarty->assign("unitsData", $unitsData);

        $smarty->assign("today", date("Y-m-d H:i:s"));

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $previousPriceStatus = checkPreviousPrice();
        $smarty->assign("previousPriceStatus", $previousPriceStatus);

        $Programsettingdata = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        $smarty->assign("Programsettingdata", $Programsettingdata);

        $allDiscounts = $discountControlDAO->queryAll();
        $smarty->assign("allDiscounts", json_encode($allDiscounts));

        if (isset($_SESSION["printURL"])) {
            $smarty->assign("printURL", $_SESSION["printURL"]);
        } else {
            $smarty->assign("printURL", "");
        }

        unset($_SESSION["printURL"]);
        //here the smarty templates
        if ($lang == "en")
            $smarty->display("sellbillview/bill-ltr.html");
        else
            $smarty->display("sellbillview/bill.html");

        $smarty->assign("customeditsellbill", 1);
        $smarty->assign("customsellbill", 1);
        $smarty->assign("customreturnsellbill", 1);
        $smarty->assign("customsellbillModel", 1);
        $smarty->assign("customSellProductModel", 1);
    } else {
        header("location:sellbillController.php");
    }
}
## restaurant Part
elseif ($do == "addresBill") {
    $restaurantorderlast20 = R::getAll("SELECT * FROM `restaurantorder` order by id desc limit 20");
    $smarty->assign("restaurantorderlast20", $restaurantorderlast20);
    $OrdereditId = (int) filter_input(INPUT_GET, "id");
    $tableId = (int) filter_input(INPUT_GET, "tableId");
    $smarty->assign("tableId", $tableId);
    if ($OrdereditId) {
        $restaurantOrder = $restaurantOrderDAO->load($OrdereditId);
        $sellBilldata = $mySellbillRecord->load($restaurantOrder->sellBillId);
        $Clientdata = $myClientRecord->load($sellBilldata->sellbillclientid);
        $smarty->assign("Clientdata", $Clientdata);
        $restaurantOrder->finished = 0;
        $restaurantOrderDAO->update($restaurantOrder);
        $smarty->assign("sellBillId", $restaurantOrder->sellBillId);
        $smarty->assign("OrdereditId", $OrdereditId);
        R::exec("UPDATE `restaurantorder` SET `finished`= 1 WHERE id != '" . $OrdereditId . "'
            and tableId = '" . $tableId . "'");
    }

    $usergroupid = $_SESSION['usergroupid'];
    $usergroup = R::getRow("SELECT usergroup.* FROM `usergroup` WHERE usergroupid = $usergroupid ");
    $_SESSION['passworduse'] = $usergroup['billDeletePassword'];
    $smarty->assign("usergroup", $usergroup);

    $time = date("Y-m-d H:i:s");
    $GetDate = date("c", strtotime($time));
    list($Date) = explode('+', $GetDate);
    $GetDate = $Date;
    $smarty->assign("today", $GetDate);

    if (isset($_SESSION["printOrder"]) && !empty($_SESSION["printOrder"])) {
        $smarty->assign("printOrder", $_SESSION['printOrder']);
        unset($_SESSION["printOrder"]);
    } else {
        $smarty->assign("printOrder", 0);
    }
    //show tables that not del and (user is allowed to see table   or   usergroup can see all tables )
    if ($Usergroupdata->seeAllHalls) {

        $queryString = '';
    } else if ($Usergroupdata->takeAway == 1 && $Usergroupdata->delivery == 1 && $Usergroupdata->hall == 1) {
        $queryString = '';
    } else if ($Usergroupdata->takeAway == 0 && $Usergroupdata->delivery == 0 && $Usergroupdata->hall == 0) {
        $queryString = ' and restauranttable.id = -1000 ';
    } else {
        $queryString = ' and ( ';
        if ($Usergroupdata->hall == 1) {
            $queryString .= ' restauranttable.id > 0 ';
        }
        if ($Usergroupdata->takeAway == 1) {
            if ($Usergroupdata->hall == 1) {
                $queryString .= ' or ';
            }
            $queryString .= ' restauranttable.id = -1  ';
        }
        if ($Usergroupdata->delivery == 1) {
            if ($Usergroupdata->hall == 1 || $Usergroupdata->takeAway == 1) {
                $queryString .= ' or ';
            }
            $queryString .= ' restauranttable.id = -2 ';
        }
        $queryString .= ' ) ';
    }

    $restaurantTables = $restaurantTableEX->queryAllEX($queryString);
    foreach ($restaurantTables as $value) {
        $value->hallUsers = explode(',', $value->hallUsers);
    }
    $smarty->assign("restaurantTables", $restaurantTables);
    $smarty->assign("employeename", $_SESSION['employeename']);

    $clientarea = $ClientareaDAO->queryAll();
    $smarty->assign('clientarea', $clientarea);

    if ($Programsettingdata->billRest == 1) {
        $smarty->display("resturant/bill.html");
    } else {
        $startDate = $endDate = date('Y-m-d');
        $startDate = $startDate . " 00:00:00";
        $endDate = $endDate . ' 23:59:59';

        $rules = $myRelusergrouppropertieExt->loadWithUsergroupidAndPropertyid($Usergroupdata->usergroupid, 303);
        $smarty->assign('rules', $rules);

        $sumSaveDaly = $mySavedailyEx->queryWithUserIdAndDate($startDate, $endDate, $_SESSION['userid']);
        $sum = 0;
        $min = 0;
        foreach ($sumSaveDaly as $item) {
            if ($item->savedailychangetype == 0) {
                $sum += $item->savedailychangeamount;
            } else {
                $min += $item->savedailychangeamount;
            }
        }

        $totalDay = $sum - $min;

        $totalBillBydate = $restaurantOrderEX->sumTotalBill($startDate, $endDate);

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

        $prod3 = $productExt->get3productsOne($startDate, $endDate);
        //        var_dump($prod3);
        $return_arr = array();
        $row_array = array();
        foreach ($prod3 as $key => $pro) {
            if ($pro->storereporttype == 1) {
                $pro->storeTotal = $pro->productbefore - $pro->productafter;
            } else {
                $pro->storeTotal = $pro->productafter - $pro->productbefore;
            }
            $row_array['productId'] = $pro->productId;
            $row_array['productName'] = $pro->productName;
            $row_array['storereporttype'] = $pro->storereporttype;
            $row_array['productbefore'] = $pro->productbefore;
            $row_array['productafter'] = $pro->productafter;
            $row_array['storeTotal'] = $pro->storeTotal;
            array_push($return_arr, $row_array);
        }

        $cates3 = $myProductcatEx->get3categoriesOne($startDate, $endDate);

        foreach ($cates3 as $key => $cates) {

            $return_arr[$key]['productCatId'] = $cates->productCatId;
            $return_arr[$key]['productCatName'] = $cates->productCatName;
            $return_arr[$key]['catExcelid'] = $cates->catExcelid;
        }

        $smarty->assign("return_arr", $return_arr);
        $smarty->assign("totalBillBydate", $totalBillBydate);
        $smarty->assign("totalDay", $totalDay);
        $smarty->assign("bill-new", 1);
        $smarty->display("resturant/bill-new.html");
    }
} elseif ($do == "endKitchenBill") {

    $tableId = (int) $_POST["tableId"];
    $printBill = (int) $_POST["printBill"];
    $sellBillIdold = (int) $_POST["sellBillIdold"];
    if ($sellBillIdold > 0) {
        delete($sellBillIdold);
    }
    $thereIsRestTax = (int) $_POST["thereIsRestTax"];
    if ($thereIsRestTax == 1) {
        $restTaxVal = (float) $_POST["restTaxVal_hidden"];
    } else {
        $restTaxVal = 0;
    }

    //Transaction
    $mytransactions = new Transaction();
    try {
        R::exec("UPDATE `restaurantorder` SET `finished`= 0 WHERE sellBillId = 0 ");
        //
        $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
        $orderId = 0;
        if (count($order) > 0) {
            $order = $order[0];
            $orderId = $order->id;
            //there is order check if there is order details
            $orderDetails = $restaurantOrderDetailsDAO->queryByOrderId($orderId);
            if (count($orderDetails) == 0) {
                //table was just opened no orders free it
                $resTable = $restaurantTableDAO->load($tableId);
                $resTable->beingUsed = 0;
                $restaurantTableDAO->update($resTable);
                //if there is order del it
                $restaurantOrderDAO->delete($orderId);
                //if it was delivery del delivery details
                $restaurantOrderDeliveryDetailDAO->deleteByOrderId($orderId);
                //dont print as tere is no orders
                $printBill = 0;
            } else {
                $restaurantOrder = $restaurantOrderDAO->load($orderId);
                $restaurantOrder->tax = $restTaxVal;
                $restaurantOrderDetails = $restaurantOrderDetailsDAO->queryByOrderId($orderId);

                $resTable = $restaurantTableDAO->load($tableId);
                $hallData = $restaurantHallDAO->load($resTable->hallid);
                $restaurantOrder->hallPrice = $hallData->hallPrice;
                $addData = addRestaurantBill($restaurantOrder, $restaurantOrderDetails);

                $restaurantOrder->totalBill = (float) $_POST['totalBill_hidden'];
                $restaurantOrder->discount = (float) $_POST['discount'];
                $restaurantOrder->netBill = (float) $_POST['netBill_hidden'];
                $restaurantOrder->rest = (float) $_POST['ba2ey_hidden'];
                //                $restaurantOrder->payed = (float) $_POST['payed']; //المدفوع
                $restaurantOrder->sellBillId = (int) $addData[0];
                $today = date('Y-m-d');
                $yesterday = date("Y-m-d", strtotime('-1 days'));
                if (isset($Programsettingdata->reportsPlusHours) && !empty($Programsettingdata->reportsPlusHours)) {
                    $reportsPlusHours = $Programsettingdata->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('+' . $Programsettingdata->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('+' . $Programsettingdata->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') < $Programsettingdata->reportsPlusHours) {
                    $sql = "and sysdate >= '" . $startYesterday . "' and sysdate <= '" . $endYesterday . "'";
                } else {
                    $sql = "and sysdate >= '" . $startToday . "' and sysdate <= '" . $endToday . "'";
                }
                $maxDay = $restaurantOrderEX->getMaxDaySreial($sql);
                if (!isset($maxDay) || empty($maxDay)) {
                    $maxDay = 0;
                }

                if ($Usergroupdata->autoKitchenPrint == 1) {
                    $restaurantOrderDAO->update($restaurantOrder);
                    printKitchen($restaurantOrder->tableId);
                }
                $restaurantOrder->finished = 1;
                $restaurantOrder->payed = (float) $_POST['payed'];
                $restaurantOrderDAO->update($restaurantOrder);

                $resTable->beingUsed = 0;
                $restaurantTableDAO->update($resTable);
            }
        } else {
            //table was just opened no orders free it
            $resTable = $restaurantTableDAO->load($tableId);
            $resTable->beingUsed = 0;
            $restaurantTableDAO->update($resTable);
            //dont print as tere is no orders
            $printBill = 0;
        }
        if ($printBill == 1) {
            $_SESSION["printOrder"] = $orderId; //sellbillprintController.php?do=printResBill&id=
        }
        $mytransactions->commit();
        if ($Programsettingdata->qrerp > 1 && $restaurantOrder->sellBillId > 0) {
            qrerp($restaurantOrder->sellBillId);
        }
        // if ($Programsettingdata->ebill == 1 && $restaurantOrder->sellBillId > 0) {
        //     etabill($restaurantOrder->sellBillId);
        // }
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $sellbillclientId = 1; //$_POST['supplier'];
        if ($restaurantOrder->tableId == -2 || $restaurantOrder->tableId == -1) {
            if (isset($_POST["client"]) && !empty($_POST["client"])) {
                $sellbillclientId = $_POST["client"];
            }
        }
        markClientAsNOTInUse($sellbillclientId);
    }
    header("location:sellbillController.php?do=addresBill");
}
##
elseif ($do == "editsellBill") {
    //here the permission check
    include_once("../public/authentication.php");

    $sellbillid = $_GET['sellbillid'];
    $ordertype = (int) $_GET['ordertype'];

    $smarty->assign('billId', $sellbillid);
    if ($ordertype == 0) { //bill
        $mysellbilldata = $mySellbillRecord->load($sellbillid);
        $billCurrData = $sellBillCurrEX->queryOneBySellbillid($sellbillid);
        if (!isset($billCurrData)) {
            $billCurrData->conversionFactor = 1;
        }
        $billCurrData->otherconversionFactor = 1 / $billCurrData->conversionFactor;
    } elseif ($ordertype == 1) { //offer
        $mysellbilldata = $sellBillOfferDAO->load($sellbillid);
    }
    $smarty->assign("mysellbilldata", $mysellbilldata);
    $smarty->assign("billCurrData", $billCurrData);

    if ($mysellbilldata->conditions == 1) {
        $smarty->assign('urldirect', 'sellbillController.php?do=show');
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يمكن تعديل الفاتورة حيث انها محذوفة";
        } else {
            $note = "The invoice cannot be modified as it has been deleted";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
        exit();
    }
    $mysupplierdata = (object) R::getRow('select supplierid,suppliername from supplier where supplierid=' . $mysellbilldata->sellToSupplier);
    $smarty->assign("mysupplierdata", $mysupplierdata);

    $billOperations = $billOperationDAO->queryAll();
    $smarty->assign("billOperations", $billOperations);

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);
    $userSaveData = $mySaveEx->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);

    $knownWays = $knownWaysDAO->queryAll();
    $smarty->assign("knownWays", $knownWays);

    //print_r($mysellbilldata);
    // for get current client dept
    $sellbillclientid = $mysellbilldata->sellbillclientid;
    $myclientdata = $myClientRecord->load($sellbillclientid);
    $smarty->assign("myclientdata", $myclientdata);

    // for get current sell bill setting
    $billnameId = $mysellbilldata->billnameid; //$_GET['billnameid'];
    $billnameData = $myBillnameRecord->load($billnameId);
    $smarty->assign("billnameData", $billnameData);

    //get  sell bill detales data
    if ($ordertype == 0) { //bill
        $mysellbildetales = $mySellbilldetailEx->queryWithSellBillId($sellbillid);
    } elseif ($ordertype == 1) { //offer
        $mysellbildetales = $sellBillDetailOfferEX->queryWithSellBillId($sellbillid);
    }
    $i = 1;
    foreach ($mysellbildetales as $mydetales) {

        $parentId = $mydetales->sellbilldetailcatid;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);
        if ($ordertype == 0) { //bill
            $mydetales->sellbilldetailtax = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and (is_offer is null or is_offer !=1)', [$mydetales->sellbilldetailid]);
        } elseif ($ordertype == 1) { //offer
            $mydetales->sellbilldetailtax = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and is_offer =1', [$mydetales->sellbilldetailid]);
        }

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;

        //isservice
        $mydetales->isService = R::getCell('select isService from product where productId=' . $mydetales->sellbilldetailproductid);

        $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->sellbilldetailproductid);
        $smarty->assign("myunitdata" . $i, $myunitdata);
        // add sold quantity to available quantity of parcode
        $productNumber = (float) $mydetales->productnumber;
        $mydetales->don += $mydetales->sellbilldetailquantity * $productNumber;

        //
        $soldSerialsInDetailsArr = array();
        if (!empty($mydetales->soldSerialsInDetails)) {
            foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                $issold = $myProductserialDAO->load($productserailid);
                array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
            }
            $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
        }
        $i++;
    }

    $smarty->assign("mysellbildetales", $mysellbildetales);
    $smarty->assign("detalesitr", count($mysellbildetales));

    //print_r($billnameId.'bbbbbbbbbbbb<br>');
    if ($billnameId != "") {
        $billsettingsData = loadBillProperty($billnameId);

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

        //visa payment
        if ($billsettingsData[86] == 1) {
            $bankAccounts = $bankAccountEX->queryWithOrder2ForVisaPayment();
            $smarty->assign('bankAccounts', $bankAccounts);
        }
        //saves are dropdown list
        $smarty->assign('sessionSave', $_SESSION['saveid']);
        if ($billsettingsData[87] == 1) {
            $allSaves = $mySaveRecord->queryByConditions(0);
            $smarty->assign('allSaves', $allSaves);
        }

        //        $clientData = loadClient();
        //        $smarty->assign("clientData", $clientData);
        $storeData = loadStore();
        $smarty->assign("storeData", $storeData);

        $sellerData = loadseller();
        $smarty->assign("sellerData", $sellerData);

        $smarty->assign("billnameid", $billnameId);

        $billnameAddData = $myBillnameRecord->load($billnameId);
        $smarty->assign("billnameAddData", $billnameAddData);

        //get product categories
        $categoriesData = loadProductCat();
        $smarty->assign("categoriesData", $categoriesData);

        //get units
        $unitsData = loadUnit();
        $smarty->assign("unitsData", $unitsData);

        $smarty->assign("today", date("Y-m-d H:i:s"));

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $previousPriceStatus = checkPreviousPrice();
        $smarty->assign("previousPriceStatus", $previousPriceStatus);

        $Programsettingdata = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        $smarty->assign("Programsettingdata", $Programsettingdata);

        $allDiscounts = $discountControlDAO->queryAll();
        $smarty->assign("allDiscounts", json_encode($allDiscounts));

        $billStatus = R::getRow('select status from sellbillstatus where sellbillid = ' . $sellbillid . ' order by id desc limit 1')['status'];
        $smarty->assign('billStatus', $billStatus);

        $smarty->assign("controlname", "sellbillController");
        //here the smarty templates
        //$smarty->display("sellbillview/billonw.html");
        $smarty->display("sellbillview/billedit.html");

        $smarty->assign("customeditsellbill", 1);
        $smarty->assign("customsellbill", 1);
        //$smarty->assign("customreturnsellbill",1);
        $smarty->assign("customsellbillModel", 1);
        $smarty->assign("customSellProductModel", 1);
    } else {
        header("location:sellbillController.php");
    }
} elseif ($do == "editreturnsellBill") {
    //here the permission check
    include_once("../public/authentication.php");

    $returnsellbillid = $_GET['returnsellbillid'];
    $smarty->assign('billId', $returnsellbillid);
    $mysellbilldata = $myReturnsellbillRecord->load($returnsellbillid);
    $billCurrData = $returnSellBillCurrEX->queryOneByReturnsellbillid($returnsellbillid);
    if (!isset($billCurrData)) {
        $billCurrData->conversionFactor = 1;
    }
    $billCurrData->otherconversionFactor = 1 / $billCurrData->conversionFactor;

    $smarty->assign("returnmysellbilldata", $mysellbilldata);
    $smarty->assign("billCurrData", $billCurrData);

    if ($mysellbilldata->conditions == 1) {
        $smarty->assign('urldirect', 'returnsellbillController.php?do=show');
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يمكن تعديل الفاتورة حيث انها محذوفة";
        } else {
            $note = "The invoice cannot be modified as it has been deleted";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
        exit();
    }

    $sellbillclientid = $mysellbilldata->returnsellbillclientid;
    $myclientdata = $myClientRecord->load($sellbillclientid);
    $smarty->assign("myclientdata", $myclientdata);

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);
    $userSaveData = $mySaveEx->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);

    $billOperations = $billOperationDAO->queryAll();
    $smarty->assign("billOperations", $billOperations);

    // for get current sell bill setting
    $billnameId = $mysellbilldata->billnameid; //$_GET['billnameid'];
    $billnameData = $myBillnameRecord->load($billnameId);
    $smarty->assign("billnameData", $billnameData);

    //get  sell bill detales data
    $mysellbildetales = $myReturnsellbilldetailEx->queryWithReturnsellbillId($returnsellbillid);
    $i = 1;
    foreach ($mysellbildetales as $mydetales) {
        if ($sellbillclientid > 1 && $Programsettingdata->checkretsellclient == 2) {
            $productsData = $myProductEx->queryByNameExtWithoutLimit2($mydetales->productName, $mydetales->storeid, ' and clientid in(0,' . $sellbillclientid . ')', " limit 1", 0);
            $productNetStat = getNetSellStatistics($sellbillclientid, $productsData);
            if ($mydetales->colorid > 0 && $mydetales->sizeid > 0) { //has size and color
                $proIdd = "hasSizeColor" . $mydetales->returnsellbilldetailproductid . "-" . $mydetales->sizeid . "-" . $mydetales->colorid;
            } else { //without size and color
                $proIdd = $mydetales->returnsellbilldetailproductid;
            }
            $mydetales->generalPrice = $productNetStat[$proIdd];
        }

        $parentId = $mydetales->returnsellbilldetailcatid;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;

        //isservice
        $mydetales->isService = R::getCell('select isService from product where productId=' . $mydetales->returnsellbilldetailproductid);

        $myreunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->returnsellbilldetailproductid);
        //print_r($myreunitdata);
        //print_r("<br><br>");
        $smarty->assign("myreunitdata" . $i, $myreunitdata);

        //
        $soldSerialsInDetailsArr = array();
        if (!empty($mydetales->soldSerialsInDetails)) {
            foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                //$issold = $myProductserialEx->queryallisdSerial($mydetales->returnsellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                $issold = $myProductserialDAO->load($productserailid);
                array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
            }
            $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
        }
        $i++;
    }
    $smarty->assign("returnmysellbildetales", $mysellbildetales);

    //print_r($mysellbildetales);
    $smarty->assign("returndetalesitr", count($mysellbildetales));

    //print_r($billnameId.'bbbbbbbbbbbb<br>');
    if ($billnameId != "") {
        $billsettingsData = loadBillProperty($billnameId);

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

        //visa payment
        if ($billsettingsData[86] == 1) {
            $bankAccounts = $bankAccountEX->queryWithOrder2ForVisaPayment();
            $smarty->assign('bankAccounts', $bankAccounts);
        }
        //saves are dropdown list
        $smarty->assign('sessionSave', $_SESSION['saveid']);
        if ($billsettingsData[87] == 1) {
            $allSaves = $mySaveRecord->queryByConditions(0);
            $smarty->assign('allSaves', $allSaves);
        }

        //        $clientData = loadClient();
        //        $smarty->assign("clientData", $clientData);
        $storeData = loadStore();
        $smarty->assign("storeData", $storeData);

        $sellerData = loadseller();
        $smarty->assign("sellerData", $sellerData);

        $smarty->assign("billnameid", $billnameId);

        $billnameAddData = $myBillnameRecord->load($billnameId);
        $smarty->assign("billnameAddData", $billnameAddData);

        //get product categories
        $categoriesData = loadProductCat();
        $smarty->assign("categoriesData", $categoriesData);

        //get units
        $unitsData = loadUnit();
        $smarty->assign("unitsData", $unitsData);

        $smarty->assign("today", date("Y-m-d H:i:s"));

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $previousPriceStatus = checkPreviousPrice();
        $smarty->assign("previousPriceStatus", $previousPriceStatus);

        $Programsettingdata = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        $smarty->assign("Programsettingdata", $Programsettingdata);

        $allDiscounts = $discountControlDAO->queryAll();
        $smarty->assign("allDiscounts", json_encode($allDiscounts));

        $smarty->assign("controlname", "returnsellbillController");
        //here the smarty templates
        //$smarty->display("sellbillview/billonw.html");
        $smarty->display("sellbillview/billedit.html");

        $smarty->assign("customeditsellbill", 1);
        $smarty->assign("customsellbill", 1);
        $smarty->assign("customreturnsellbill", 1);
        $smarty->assign("customeditsellbill", 1);
        $smarty->assign("customsellbillModel", 1);

        $smarty->assign("customSellProductModel", 1);
    } else {
        header("location:sellbillController.php");
    }
} elseif ($do == "editsellandrutrnBill") {
    //here the permission check
    include_once("../public/authentication.php");

    $sellbillid = $_GET['sellbillid'];
    $smarty->assign('billId', $sellbillid);

    //  print_r($sellbillid.'vvvvvvvvvvv<br>');
    $showDetailData = showDetailreturn($sellbillid);
    $smarty->assign('mysellbilldata', $showDetailData[0]);
    if ($showDetailData[0]->conditions == 1) {
        $smarty->assign('urldirect', 'sellbillandruternController.php?do=show');
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يمكن تعديل الفاتورة حيث انها محذوفة";
        } else {
            $note = "The invoice cannot be modified as it has been deleted";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
        exit();
    }

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);
    $userSaveData = $mySaveEx->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);

    $billOperations = $billOperationDAO->queryAll();
    $smarty->assign("billOperations", $billOperations);

    $mysellbilldata = $showDetailData[0];
    $smarty->assign("mysellbilldata", $mysellbilldata);
    $smarty->assign("billCurrData", $showDetailData[5]);

    //print_r($mysellbilldata);
    // for get current client dept
    $sellbillclientid = $mysellbilldata->sellbillclientid;
    $myclientdata = $myClientRecord->load($sellbillclientid);
    $smarty->assign("myclientdata", $myclientdata);

    // for get current sell bill setting
    $billnameId = $mysellbilldata->billnameid; //$_GET['billnameid'];
    $billnameData = $myBillnameRecord->load($billnameId);
    $smarty->assign("billnameData", $billnameData);

    //get  sell bill detales data
    $smarty->assign('ruternbilldetailData', $showDetailData[2]);
    $smarty->assign('sellQuantity', $showDetailData[3]);
    $smarty->assign('returnQuantity', $showDetailData[4]);
    $i = 1;
    foreach ($showDetailData[1] as $mydetales) {

        $parentId = $mydetales->sellbilldetailcatid;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;

        //isservice
        $mydetales->isService = R::getCell('select isService from product where productId=' . $mydetales->sellbilldetailproductid);

        $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->sellbilldetailproductid);
        $smarty->assign("myunitdata" . $i, $myunitdata);

        // add sold quantity to available quantity of parcode
        $productNumber = (float) $mydetales->productnumber;
        $mydetales->don += $mydetales->sellbilldetailquantity * $productNumber;
        //
        $soldSerialsInDetailsArr = array();
        if (!empty($mydetales->soldSerialsInDetails)) {
            foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                $issold = $myProductserialDAO->load($productserailid);
                array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
            }
            $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
        }
        $i++;
    }
    $smarty->assign("mysellbildetales", $showDetailData[1]);
    $smarty->assign("detalesitr", count($showDetailData[1]));

    $x = 1;
    foreach ($showDetailData[2] as $mydetales) {

        $myreunitdata = $myProductunitEx->queryWithProductId($mydetales->sellbilldetailproductid);

        $parentId = $mydetales->sellbilldetailcatid;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;

        //print_r($myreunitdata);
        //print_r("<br><br>");
        $smarty->assign("myreunitdata" . $x, $myreunitdata);

        //
        $soldSerialsInDetailsArr = array();
        if (!empty($mydetales->soldSerialsInDetails)) {
            foreach (explode(',', $mydetales->soldSerialsInDetails) as $productserailid) {
                //$issold = $myProductserialEx->queryallisdSerial($mydetales->sellbilldetailproductid, $parcode, " and sizeid=$mydetales->sizeid and colorid=$mydetales->colorid ");
                $issold = $myProductserialDAO->load($productserailid);
                array_push($soldSerialsInDetailsArr, array('id' => $issold->productserailid, 'text' => $issold->serialnumber, 'don' => $issold->don, 'enddate' => $issold->enddate));
            }
            $mydetales->soldSerialsInDetails = json_encode($soldSerialsInDetailsArr);
        }

        $x++;
    }
    $smarty->assign("returnmysellbildetales", $showDetailData[2]);

    //print_r($mysellbildetales);
    $smarty->assign("returndetalesitr", count($showDetailData[2]));

    //print_r($billnameId.'bbbbbbbbbbbb<br>');
    if ($billnameId != "") {
        $billsettingsData = loadBillProperty($billnameId);

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

        //visa payment
        if ($billsettingsData[86] == 1) {
            $bankAccounts = $bankAccountEX->queryWithOrder2ForVisaPayment();
            $smarty->assign('bankAccounts', $bankAccounts);
        }
        //saves are dropdown list
        $smarty->assign('sessionSave', $_SESSION['saveid']);
        if ($billsettingsData[87] == 1) {
            $allSaves = $mySaveRecord->queryByConditions(0);
            $smarty->assign('allSaves', $allSaves);
        }

        //        $clientData = loadClient();
        //        $smarty->assign("clientData", $clientData);
        $storeData = loadStore();
        $smarty->assign("storeData", $storeData);

        $sellerData = loadseller();
        $smarty->assign("sellerData", $sellerData);

        $smarty->assign("billnameid", $billnameId);

        $billnameAddData = $myBillnameRecord->load($billnameId);
        $smarty->assign("billnameAddData", $billnameAddData);

        //get product categories
        $categoriesData = loadProductCat();
        $smarty->assign("categoriesData", $categoriesData);

        //get units
        $unitsData = loadUnit();
        $smarty->assign("unitsData", $unitsData);

        $smarty->assign("today", date("Y-m-d H:i:s"));

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $previousPriceStatus = checkPreviousPrice();
        $smarty->assign("previousPriceStatus", $previousPriceStatus);

        $Programsettingdata = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        $smarty->assign("Programsettingdata", $Programsettingdata);

        $allDiscounts = $discountControlDAO->queryAll();
        $smarty->assign("allDiscounts", json_encode($allDiscounts));

        $smarty->assign("controlname", "sellbillandruternController");
        //here the smarty templates
        //$smarty->display("sellbillview/billonw.html");
        $smarty->display("sellbillview/billedit.html");

        $smarty->assign("customsellbill", 1);
        $smarty->assign("customreturnsellbill", 1);
        $smarty->assign("customeditsellbill", 1);

        $smarty->assign("customsellbillModel", 1);
        $smarty->assign("customSellProductModel", 1);
    } else {
        header("location:sellbillController.php");
    }
} elseif ($do == "add") {
    // print_r($_POST);
    include_once("../public/authentication.php");

    $ordertype = (int) $_POST["ordertype"];
    $url = "";

    if (isset($_POST['supplierX']) && !empty($_POST['supplierX'])) {
        //"multi client"$_POST['supplierX']
        $clientIDS = $_POST['supplierX'];
        $clientIDSCount = count($clientIDS);
        $clientItr = 1;
        $lastClientFlag = 0;
        $billsIDS = '';
        foreach ($clientIDS as $value) {
            if ($clientItr == $clientIDSCount) {
                $lastClientFlag = 1;
            }

            $_POST['supplier'] = $value;
            $addData = add();
            $sellbillId = $addData[0];
            $returnsellbillId = $addData[1];
            $productsBeforeValid = $addData[2];
            $saveValuebeforeValid = $addData[3];
            $billtype = $addData[4];
            $billnameId = $_POST['billnameid'];
            $billsIDS .= $sellbillId . ",";
            if ($ordertype == "1") {
                if ($lastClientFlag == 1) {
                    $url = 'sellbillController.php?do=editprint&id=' . $sellbillId;
                    $smarty->assign('urldirect', $url);
                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "تمت العملية بنجاح";
                    } else {
                        $note = "operation accomplished successfully";
                    }
                    $smarty->assign('msgnote', $note);
                    $smarty->display("notes2.html");
                } else {
                    echo "<script type='text/javascript'>window.open('sellbillController.php?do=editprint&id=" . $sellbillId . "');</script>";
                }
            }
            if ($productsBeforeValid == "1" && $saveValuebeforeValid == "1") {
                if ($billtype == "1") {
                    // header("location:sellbillController.php?do=show&id=" . $sellbillId . "");
                    if ($lastClientFlag == 1) {
                        $url = 'sellbillController.php?do=editprint&id=' . $sellbillId;
                        $smarty->assign('urldirect', $url);
                        if ($_SESSION['erp_lang'] == 'ar') {
                            $note = "تمت العملية بنجاح";
                        } else {
                            $note = "operation accomplished successfully";
                        }
                        $smarty->assign('msgnote', $note);
                        $smarty->display("notes2.html");
                    } else {
                        echo "<script type='text/javascript'>window.open('sellbillController.php?do=editprint&id=" . $sellbillId . "');</script>";
                    }
                } elseif ($billtype == "2") {
                    //header("location:returnsellbillController.php?do=show&id=" . $returnsellbillId . "");
                    if ($lastClientFlag == 1) {
                        $url = 'returnsellbillController.php?do=editprint&id=' . $returnsellbillId;
                        $smarty->assign('urldirect', $url);
                        if ($_SESSION['erp_lang'] == 'ar') {
                            $note = "تمت العملية بنجاح";
                        } else {
                            $note = "operation accomplished successfully";
                        }
                        $smarty->assign('msgnote', $note);
                        $smarty->display("notes2.html");
                    } else {
                        echo "<script type='text/javascript'>window.open('returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "');</script>";
                    }
                } elseif ($billtype == "3") {
                    if ($lastClientFlag == 1) {
                        $url = 'sellbillandruternController.php?do=editprint&id=' . $sellbillId;
                        $smarty->assign('urldirect', $url);
                        if ($_SESSION['erp_lang'] == 'ar') {
                            $note = "تمت العملية بنجاح";
                        } else {
                            $note = "operation accomplished successfully";
                        }
                        $smarty->assign('msgnote', $note);
                        $smarty->display("notes2.html");
                    } else {
                        echo "<script type='text/javascript'>window.open('sellbillandruternController.php?do=editprint&id=" . $sellbillId . "');</script>";
                    }
                }
                /* $smarty->assign('urldirect', $url);
                  $note = "تمت العملية بنجاح";
                  $smarty->assign('msgnote', $note);
                  $smarty->display("notes2.html"); */
            } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "1") {
                if ($lastClientFlag == 1) {
                    //show this message one only in last client
                    if ($billtype == "1") {
                        $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
                    } elseif ($billtype == "2") {
                        $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
                    } elseif ($billtype == "3") {
                        $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
                    }

                    $smarty->assign('urldirect', $url);
                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
                    } else {
                        $note = "There is not enough quantity in stock for the bill";
                    }
                    $smarty->assign('msgnote', $note);
                    $smarty->display("notes2.html");
                }
            } elseif ($productsBeforeValid == "1" && $saveValuebeforeValid == "0") {
                if ($lastClientFlag == 1) {
                    //show this message one only in last client
                    if ($billtype == "1") {
                        $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                    } elseif ($billtype == "2") {
                        $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                    } elseif ($billtype == "3") {
                        $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                    }

                    $smarty->assign('urldirect', $url);
                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "لا يوجد كمية بالخزنة المبلغ الكافى للفاتورة";
                    } else {
                        $note = "There is no quantity in the safe, sufficient amount for the bill";
                    }
                    $smarty->assign('msgnote', $note);
                    $smarty->display("notes2.html");
                }
            } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "0") {
                if ($lastClientFlag == 1) {
                    //show this message one only in last client
                    if ($billtype == "1") {
                        $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                    } elseif ($billtype == "2") {
                        $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                    } elseif ($billtype == "3") {
                        $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                    }

                    $smarty->assign('urldirect', $url);
                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "لا يوجد كمية بالخزنة المبلغ الكافى ولا يوجد بالمخزن الكمية الكافية للفاتورة";
                    } else {
                        $note = "There is no quantity in the safe, the sufficient amount, and there is not enough quantity in the store for the bill";
                    }
                    $smarty->assign('msgnote', $note);
                    $smarty->display("notes2.html");
                }
            }
            $clientItr++;
        }
        if ($ordertype != 1) {
            $billsIDS = rtrim($billsIDS, ',');
            header("location:sellbillprintController.php?do=printmultibills&id=" . $billsIDS . "&ordertype=" . $ordertype);
        }
    } elseif (isset($_POST['supplier']) && !empty($_POST['supplier'])) {
        //"single client"$_POST['supplier'];
        $addData = add();
        // header("location:sellbillController.php?do=editprint&id=".$sellbillId."");
        $sellbillId = $addData[0];
        $returnsellbillId = $addData[1];
        $productsBeforeValid = $addData[2];
        $saveValuebeforeValid = $addData[3];
        $billtype = $addData[4];
        $billnameId = $_POST['billnameid'];
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success', 'id' => $sellbillId);
            echo json_encode($data);
            exit();
        }

        if ($ordertype == "1") {
            header("location:sellbillController.php?do=editprint&id=" . $sellbillId . "&ordertype=" . $ordertype);
        } else {
            if ($productsBeforeValid == "1" && $saveValuebeforeValid == "1") {
                if ($billtype == "1") {
                    // header("location:sellbillController.php?do=show&id=" . $sellbillId . "");
                    header("location:sellbillController.php?do=editprint&id=" . $sellbillId . "");
                } elseif ($billtype == "2") {
                    //header("location:returnsellbillController.php?do=show&id=" . $returnsellbillId . "");
                    header("location:returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "");
                } elseif ($billtype == "3") {
                    header("location:sellbillandruternController.php?do=editprint&id=" . $sellbillId . "");
                }
            } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "1") {
                if ($billtype == "1") {
                    $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                } elseif ($billtype == "2") {
                    $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                } elseif ($billtype == "3") {
                    $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                }

                $smarty->assign('urldirect', $url);
                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
                } else {
                    $note = "There is not enough quantity in stock for the bill";
                }
                $smarty->assign('msgnote', $note);
                $smarty->display("notes2.html");
            } elseif ($productsBeforeValid == "1" && $saveValuebeforeValid == "0") {
                if ($billtype == "1") {
                    $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                } elseif ($billtype == "2") {
                    $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                } elseif ($billtype == "3") {
                    $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                }

                $smarty->assign('urldirect', $url);
                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = "لا يوجد كمية بالخزنة المبلغ الكافى للفاتورة";
                } else {
                    $note = "There is no quantity in the safe, sufficient amount for the bill";
                }
                $smarty->assign('msgnote', $note);
                $smarty->display("notes2.html");
            } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "0") {
                if ($billtype == "1") {
                    $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                } elseif ($billtype == "2") {
                    $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                } elseif ($billtype == "3") {
                    $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                }

                $smarty->assign('urldirect', $url);
                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = "لا يوجد كمية بالخزنة المبلغ الكافى ولا يوجد بالمخزن الكمية الكافية للفاتورة";
                } else {
                    $note = "There is no quantity in the safe, the sufficient amount, and there is not enough quantity in the store for the bill";
                }
                $smarty->assign('msgnote', $note);
                $smarty->display("notes2.html");
            }
        }
    }
} elseif ($do == "addapi") {
    //
    //include_once("../public/authentication.php");
    $ordertype = $_POST["ordertype"];
    $url = "";

    $addData = add();
    $sellbillId = $addData[0];
    $returnsellbillId = $addData[1];
    $productsBeforeValid = $addData[2];
    $saveValuebeforeValid = $addData[3];
    $billtype = $addData[4];

    if ($ordertype == "1") {
        header("location:sellbillController.php?do=editprint&id=" . $sellbillId . "");
    }
    if ($productsBeforeValid == "1" && $saveValuebeforeValid == "1") {
        if ($billtype == "1") {
            header("location:sellbillController.php?do=editprint&id=" . $sellbillId . "");
        } elseif ($billtype == "2") {
            header("location:returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "");
        } elseif ($billtype == "3") {
            header("location:sellbillandruternController.php?do=editprint&id=" . $sellbillId . "");
        }

        //$smarty->assign('urldirect', $url);
        //$note ="تمت العملية بنجاح";
        //$smarty->assign('msgnote', $note);
        //$smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "1") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
        } elseif ($billtype == "2") {
            $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
        } elseif ($billtype == "3") {
            $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
        }
        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
        } else {
            $note = "There is not enough quantity in stock for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "1" && $saveValuebeforeValid == "0") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
        } elseif ($billtype == "2") {
            $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
        } elseif ($billtype == "3") {
            $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
        }

        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالخزنة المبلغ الكافى للفاتورة";
        } else {
            $note = "There is no quantity in the safe, sufficient amount for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "0") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
        } elseif ($billtype == "2") {
            $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
        } elseif ($billtype == "3") {
            $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
        }

        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالخزنة المبلغ الكافى ولا يوجد بالمخزن الكمية الكافية للفاتورة";
        } else {
            $note = "There is no quantity in the safe, the sufficient amount, and there is not enough quantity in the warehouse for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "update") {

    //
    include_once("../public/authentication.php");
    //Transaction
    $mytransactions = new Transaction();
    liveBackupComment("-- bill update start - with id = " . $_POST["oldid"] . " and $controlname = " . $_POST["controlname"]);
    try {
        $ordertype = (int) $_POST["ordertype"];
        $url = "";

        $controlname = $_POST["controlname"];
        $oldid = $_POST["oldid"];

        liveBackupComment("-- bill update start - delete start with id = " . $_POST["oldid"] . " and controlname = " . $_POST["controlname"]);
        if ($ordertype == 0) { //bill
            if ($controlname == 'sellbillController') {
                deletesellbill($oldid);
            } elseif ($controlname == 'returnsellbillController') {
                deletereturnsellbillid($oldid);
            } elseif ($controlname == 'sellbillandruternController') {
                deleteSellbillandrutern($oldid);
            }
        } elseif ($ordertype == 1) { //offer
            $sellBillOfferDAO->delete($oldid);
            $sellBillDetailOfferDAO->deleteBySellbillid($oldid);
            reverseOfferStoreMovement($oldid);
        }
        liveBackupComment("-- bill update start - delete end - with id = " . $_POST["oldid"] . " and controlname = " . $_POST["controlname"]);
        liveBackupComment("-- bill update start - new add start - with id = $oldid and controlname = $controlname");
        //reset $sellCostsArray as it has data from previous delete
        $mytransactions->commit();
        $mytransactions = new Transaction();
        $sellCostsArray = array();

        $addData = newadd($oldid, $controlname);

        $sellbillId = $addData[0];
        $returnsellbillId = $addData[1];
        $productsBeforeValid = $addData[2];
        $saveValuebeforeValid = $addData[3];
        $billtype = $addData[4];

        //commit
        $mytransactions->commit();
        liveBackupComment("-- bill update end - new add end - with oldid = $oldid and newid=$addData[0] and controlname = $controlname");

        ##buyTheSellBill
        if ($sellbillId > 0 && $ordertype == 0) {
            buyTheSellBill($sellbillId, 1);
        }

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success', 'id' => $sellbillId);
            echo json_encode($data);
            exit();
        } else {
            if ($ordertype == 1) { //offer
                //header("location:sellbillController.php?do=showDetail&sellbillid=" . $sellbillId . "");
                if ($_SESSION['erp_lang'] == 'ar') {
                    $note = " تمت العملية بنجاح";
                } else {
                    $note = "operation accomplished successfully";
                }
                $url = "sellbillController.php?do=showoffers";
                $smarty->assign('urldirect', $url);
                $smarty->assign('msgnote', $note);
                $smarty->display("notes2.html");
            } else { //bill
                if ($productsBeforeValid == "1" && $saveValuebeforeValid == "1") {
                    if ($billtype == "1") {
                        header("location:sellbillController.php?do=editprint&id=" . $sellbillId . "");
                    } elseif ($billtype == "2") {
                        header("location:returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "");
                    } elseif ($billtype == "3") {
                        header("location:sellbillandruternController.php?do=editprint&id=" . $sellbillId . "");
                    }

                    //$smarty->assign('urldirect', $url);
                    //$note ="تمت العملية بنجاح";
                    //$smarty->assign('msgnote', $note);
                    //$smarty->display("notes2.html");
                } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "1") {
                    if ($billtype == "1") {
                        $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                    } elseif ($billtype == "2") {
                        $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                    } elseif ($billtype == "3") {
                        $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                    }
                    $smarty->assign('urldirect', $url);

                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
                    } else {
                        $note = "There is not enough quantity in stock for the bill";
                    }
                    $smarty->assign('msgnote', $note);
                    $smarty->display("notes2.html");
                } elseif ($productsBeforeValid == "1" && $saveValuebeforeValid == "0") {
                    if ($billtype == "1") {
                        $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                    } elseif ($billtype == "2") {
                        $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                    } elseif ($billtype == "3") {
                        $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                    }

                    $smarty->assign('urldirect', $url);
                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "لا يوجد كمية بالخزنة المبلغ الكافى للفاتورة";
                    } else {
                        $note = "There is no quantity in the safe, sufficient amount for the bill";
                    }
                    $smarty->assign('msgnote', $note);
                    $smarty->display("notes2.html");
                } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "0") {
                    if ($billtype == "1") {
                        $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
                    } elseif ($billtype == "2") {
                        $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
                    } elseif ($billtype == "3") {
                        $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
                    }

                    $smarty->assign('urldirect', $url);
                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "لا يوجد كمية بالخزنة المبلغ الكافى ولا يوجد بالمخزن الكمية الكافية للفاتورة";
                    } else {
                        $note = "There is no quantity in the safe, the sufficient amount, and there is not enough quantity in the warehouse for the bill";
                    }
                    $smarty->assign('msgnote', $note);
                    $smarty->display("notes2.html");
                }
            }
        }
        if ($Programsettingdata->qrerp > 1) {
            qrerp($sellbillId);
        }
    } catch (Exception $e) {
        $mytransactions->rollback();
        //   echo $e;
        header("location:?do=error");
    }
} elseif ($do == "addAndRetuen") {



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

    $billnameId = $_POST['billnameid'];
    $sellorder = $_GET['sellorder'];

    $url = "";

    $addData = add();
    $sellbillId = $addData[0];
    $returnsellbillId = $addData[1];
    $productsBeforeValid = $addData[2];
    $saveValuebeforeValid = $addData[3];
    $billtype = (int) $addData[4];
    if ($Programsettingdata->qrerp > 1) {
        qrerp($sellbillId);
    }

    $saveBtnGoesTo = (int) $_POST["saveBtnGoesTo"];
    $ordertype = (int) $_POST["ordertype"];
    $printURL = "";
    if ($saveBtnGoesTo == 1) {
        //save btn clicked, go to new bill after print but you need to print bill too
        switch ($billtype) {
            case 1: //sell
                $printURL = "sellbillprintController.php?do=showDetail2&id=" . $sellbillId . "&ordertype=" . $ordertype . "&sellorder=" . $sellorder;
                break;
            case 2: //ret
                $printURL = "sellbillprintController.php?do=returnshowDetail&id=" . $sellbillId;
                break;
            case 3: //sell and ret
                $printURL = "sellbillprintController.php?do=returnandselshowDetail&id=" . $sellbillId;
                break;
        }
    }
    $_SESSION["printURL"] = $printURL;

    // echo "sellbillId => $sellbillId  ,returnsellbillId => $returnsellbillId , productsBeforeValid => $productsBeforeValid ,saveValuebeforeValid => $saveValuebeforeValid , billtype=> $billtype ";
    if ($productsBeforeValid == "1" && $saveValuebeforeValid == "1") {
        if ($billtype == "1") {
            header("location:sellbillController.php?do=addsellBill&billnameid=" . $billnameId);
        } elseif ($billtype == "2") {
            header("location:sellbillController.php?do=addsellBill&billnameid=" . $billnameId);
        } elseif ($billtype == "3") {
            header("location:sellbillController.php?do=addsellBill&billnameid=" . $billnameId);
        }
        //          $smarty->assign('urldirect', $url);
        //          $note ="تمت العملية بنجاح";
        //
        //          $smarty->assign('msgnote', $note);
        //          $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "1") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "2") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "3") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        }

        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
        } else {
            $note = "There is not enough quantity in stock for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "1" && $saveValuebeforeValid == "0") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "2") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "3") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        }
        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالخزنة المبلغ الكافى للفاتورة";
        } else {
            $note = "There is no quantity in the safe, sufficient amount for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "0") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "2") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "3") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        }

        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالخزنة المبلغ الكافى ولا يوجد بالمخزن الكمية الكافية للفاتورة";
        } else {
            $note = "There is no quantity in the safe, the sufficient amount, and there is not enough quantity in the warehouse for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "addAndSend") {
    include_once("../public/authentication.php");

    $billnameId = $_POST['billnameid'];
    $sellorder = $_GET['sellorder'];

    $url = "";

    $addData = add();
    $sellbillId = $addData[0];
    $returnsellbillId = $addData[1];
    $productsBeforeValid = $addData[2];
    $saveValuebeforeValid = $addData[3];
    $billtype = (int) $addData[4];
    if ($Programsettingdata->qrerp > 1) {
        qrerp($sellbillId);
    }

    if ($Programsettingdata->ebill == 1) {
        etabill($sellbillId);
    }

    $saveBtnGoesTo = (int) $_POST["saveBtnGoesTo"];
    $ordertype = (int) $_POST["ordertype"];
    $printURL = "";
    if ($saveBtnGoesTo == 1) {
        //save btn clicked, go to new bill after print but you need to print bill too
        switch ($billtype) {
            case 1: //sell
                $printURL = "sellbillprintController.php?do=showDetail2&id=" . $sellbillId . "&ordertype=" . $ordertype . "&sellorder=" . $sellorder;
                break;
            case 2: //ret
                $printURL = "sellbillprintController.php?do=returnshowDetail&id=" . $sellbillId;
                break;
            case 3: //sell and ret
                $printURL = "sellbillprintController.php?do=returnandselshowDetail&id=" . $sellbillId;
                break;
        }
    }
    $_SESSION["printURL"] = $printURL;

    // echo "sellbillId => $sellbillId  ,returnsellbillId => $returnsellbillId , productsBeforeValid => $productsBeforeValid ,saveValuebeforeValid => $saveValuebeforeValid , billtype=> $billtype ";
    if ($productsBeforeValid == "1" && $saveValuebeforeValid == "1") {
        if ($billtype == "1") {
            header("location:sellbillController.php?do=addsellBill&billnameid=" . $billnameId);
        } elseif ($billtype == "2") {
            header("location:sellbillController.php?do=addsellBill&billnameid=" . $billnameId);
        } elseif ($billtype == "3") {
            header("location:sellbillController.php?do=addsellBill&billnameid=" . $billnameId);
        }
        //          $smarty->assign('urldirect', $url);
        //          $note ="تمت العملية بنجاح";
        //
        //          $smarty->assign('msgnote', $note);
        //          $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "1") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "2") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "3") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        }

        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
        } else {
            $note = "There is not enough quantity in stock for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "1" && $saveValuebeforeValid == "0") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "2") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "3") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        }
        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالخزنة المبلغ الكافى للفاتورة";
        } else {
            $note = "There is no quantity in the safe, sufficient amount for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "0") {
        if ($billtype == "1") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "2") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        } elseif ($billtype == "3") {
            $url = "sellbillController.php?do=addsellBill&billnameid=" . $billnameId;
        }

        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يوجد كمية بالخزنة المبلغ الكافى ولا يوجد بالمخزن الكمية الكافية للفاتورة";
        } else {
            $note = "There is no quantity in the safe, the sufficient amount, and there is not enough quantity in the warehouse for the bill";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "addAndPrint") {
    include_once("../public/authentication.php");

    $billnameId = $_POST['billnameid'];



    $addData = add();
    $sellbillId = $addData[0];
    $returnsellbillId = $addData[1];
    $productsBeforeValid = $addData[2];
    $saveValuebeforeValid = $addData[3];
    $billtype = (int) $addData[4];
    if ($Programsettingdata->qrerp > 1) {
        qrerp($sellbillId);
    }

    $ordertype = (int) $_POST["ordertype"];
    $printURL = "";
    //save btn clicked, go to new bill after print but you need to print bill too
    switch ($billtype) {
        case 1: //sell
            $printURL = "sellbillprintController.php?do=showDetail2&id=" . $sellbillId . "&ordertype=" . $ordertype;
            break;
        case 2: //ret
            $printURL = "sellbillprintController.php?do=returnshowDetail&id=" . $sellbillId;
            break;
        case 3: //sell and ret
            $printURL = "sellbillprintController.php?do=returnandselshowDetail&id=" . $sellbillId;
            break;
    }
    header("location:" . $printURL);
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");

    $sellbillId = $_GET['id'];

    $showDetailData = showDetail($sellbillId);

    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('billCurrData', $showDetailData[4]);

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);
    $userSaveData = $mySaveEx->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);

    $myclientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);
    $smarty->assign("myclientdata", $myclientdata);

    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign("quantity", $showDetailData[2]);

    if ($showDetailData[0]->billnameid != 0 && isset($showDetailData[0]->billnameid) && $showDetailData[0]->billnameid != "" && !empty($showDetailData[0]->billnameid)) {
        $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
        $smarty->assign("billsettingsData", $billsettingsData);

        $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
        $smarty->assign("billnameAddData", $billnameAddData);
    }
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);

    $smarty->display("sellbillview/editprint.html");
} elseif ($do == "showDetail") {
    include_once("../public/authentication.php");

    $sellbillId = $_GET['sellbillid'];
    $ordertype = (int) $_GET['ordertype'];

    $smarty->assign('billId', $sellbillId);
    $smarty->assign('ordertype', $ordertype);
    $showDetailData = showDetail($sellbillId, $ordertype);

    $billOperations = $billOperationDAO->queryAll();
    $smarty->assign("billOperations", $billOperations);

    //getalldiscount
    $sellbilldiscount = $showDetailData[0]->sellbilldiscount;
    $sellbilldiscounttype = $showDetailData[0]->sellbilldiscounttype; //1 مباشر
    $sellbilltotalbill = $showDetailData[0]->sellbilltotalbill;
    $sellbillaftertotalbill = $showDetailData[0]->sellbillaftertotalbill;
    $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
    $tax = $showDetailData[0]->tax;

    if ($sellbilldiscounttype == 1) {

        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
        $discountvalue = $sellbilldiscount;
    } else {
        //discount
        $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
    }

    $smarty->assign('discountvalue', $discountvalue);
    $smarty->assign('taxvalue', $taxvalue);

    //visa payment
    $bankAccount = $bankAccountEX->loadBankAccount((int) $showDetailData[0]->visaAccountId);
    $smarty->assign('bankAccount', $bankAccount);

    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('billCurrData', $showDetailData[4]);
    $smarty->assign('billPayments', $showDetailData[3]);
    $smarty->assign('sellbilldetailtaxdata', $showDetailData[5]);

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $myclientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);
    $smarty->assign("myclientdata", $myclientdata);

    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign("quantity", $showDetailData[2]);

    if ($showDetailData[0]->billnameid != 0 && isset($showDetailData[0]->billnameid) && $showDetailData[0]->billnameid != "" && !empty($showDetailData[0]->billnameid)) {
        $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
        $smarty->assign("billsettingsData", $billsettingsData);

        $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
        $smarty->assign("billnameAddData", $billnameAddData);
    }
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);

    $sellbillimage = R::getRow('SELECT sellbillimage.* FROM `sellbillimage` WHERE sellbillid = ? ', [$sellbillId]);
    $smarty->assign("sellbillimage", $sellbillimage);

    $mysupplierdata = (object) R::getRow('select supplierid,suppliername from supplier where supplierid=' . $showDetailData[0]->sellToSupplier);
    $smarty->assign("mysupplierdata", $mysupplierdata);

    /*  print_r("<pre>");
      print_r($billsettingsData);
      print_r("<pre>"); */

    //check if sellbilldetails has many stores
    $manyStores = 0;
    $storeArray = [];
    $loop = 1;
    if (count($showDetailData[1]) > 1) {
        foreach ($showDetailData[1] as $data) {
            if ($loop > 1) {
                if (!in_array($data->storeid, $storeArray)) {
                    $manyStores = 1;
                    break;
                }
            }
            $storeArray[] = $data->storeid;
            $loop++;
        }
    }
    $smarty->assign('manyStores', $manyStores);

    $billStatus = R::getRow('select status from sellbillstatus where sellbillid = ' . $sellbillId . ' order by id desc limit 1')['status'];
    $smarty->assign('billStatus', $billStatus);


    $smarty->display("sellbillview/showdetail.html");
} elseif ($do == "showDetail2") {
    include_once("../public/authentication.php");

    $sellbillId = $_GET['sellbillid'];

    $showDetailData = showDetail($sellbillId);

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('billCurrData', $showDetailData[4]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign("quantity", $showDetailData[2]);

    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);

    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);
    //here the smarty templates
    $smarty->display("sellbillview/editprint2.html");
} elseif ($do == "deleterestaurant") {
    include_once("../public/authentication.php");
    $sellbillId = $_GET['sellbillid'];
    $ordertype = (int) $_GET['ordertype'];
    $orderId = (int) $_GET['orderid'];
    $billReservation = (int) $_GET['reservation'];
    try {
        $restaurantOrder = $restaurantOrderDAO->load($orderId);
        $restaurantOrder->del = 1;
        $restaurantOrderDAO->update($restaurantOrder);
        $saveValuebeforeValid = delete($sellbillId);
        header('Location:' . $hosturl . '/controllers/ordersreport.php');
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    $sellbillId = $_GET['sellbillid'];
    $ordertype = (int) $_GET['ordertype'];
    $billReservation = (int) $_GET['reservation'];
    try {
        $response = delete($sellbillId);
        $saveValuebeforeValid = $response[0];
        $flag = $response[2];

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            if ($flag == 1) {
                $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
                echo json_encode($data);
            } else if ($flag == 2) {
                $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
                echo json_encode($data);
            }
        } else {
            if ($billReservation == 4) {
                header('Location:' . $hosturl . '/controllers/salesreportbills.php?do=billReservation');
            } elseif ($ordertype == 0) {
                header("location:?do=sucess");
            } elseif ($ordertype == 1) {
                header("location:?do=showoffers");
            }
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "discountcontrol") {
    $allDiscounts = $discountControlDAO->queryAll();
    $smarty->assign("allDiscounts", $allDiscounts);

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

    $smarty->display("sellbillview/discountcontrol.html");
    $smarty->assign("discountcontrol", 1);
} elseif ($do == "discountcontrolsave") {

    try {
        $discountControlEX->truncate();
        $itr = (int) filter_input(INPUT_POST, 'itr');
        for ($i = 1; $i <= $itr; $i++) {
            //$id = (int) filter_input(INPUT_POST, 'id' . $i);
            $total_from = (float) filter_input(INPUT_POST, 'total_from' . $i);
            $total_to = (float) filter_input(INPUT_POST, 'total_to' . $i);
            $discount = (float) filter_input(INPUT_POST, 'discount' . $i);

            if (isset($total_from, $total_to, $discount) && $discount > 0) {
                $discountControl->totalFrom = $total_from;
                $discountControl->totalTo = $total_to;
                $discountControl->discount = $discount;
                $discountControl->userid = $_SESSION['userid'];
                $discountControl->sysdate = date('Y-m-d H:i:s');
                $discountControl->conditions = 0;
                $discountControlDAO->insert($discountControl);
            }
        }

        if ($_SESSION['erp_lang'] == 'ar') {
            $note = " تمت العملية بنجاح";
        } else {
            $note = "operation accomplished successfully";
        }
    } catch (Exception $e) {
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = " لقد حدث خطأ";
        } else {
            $note = "An error has occurred";
        }
    }
    $url = "sellbillController.php?do=discountcontrol";
    $smarty->assign('urldirect', $url);
    $smarty->assign('msgnote', $note);
    $smarty->display("notes2.html");
} elseif ($do == "showoffers") {
    include_once("../public/authentication.php");

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);

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

    $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("usergroup", $usergroup);

    //    $clientData = loadAllClient();
    //    $smarty->assign("clientData", $clientData);
    //  $sellbillSearchData=loadAllSellBill();
    $smarty->assign("sellbillSearchData", $sellbillSearchData);

    $sellerData = loadseller();
    $smarty->assign("sellerData", $sellerData);

    $sellerinsertData = $userDAO->queryAll();
    $smarty->assign("sellerinsertData", $sellerinsertData);

    $billsettingsData = loadBillProperty(3);
    $smarty->assign("billsettingsData", $billsettingsData);

    showAllOffers();
    $smarty->display("sellbillview/showoffers.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "saveOfferAsBill") {
    $offerId = (int) $_GET['offerId'];
    $mysellbilldata = $sellBillOfferDAO->load($offerId);
    if ($offerId > 0 && $mysellbilldata->orderSavedBillId == 0) {

        ####### 1- set some required post values
        $mysellbildetales = $sellBillDetailOfferEX->queryWithSellBillId($offerId);
        $clientdata = $myClientRecord->load($mysellbilldata->sellbillclientid);
        $_POST = array(
            'bns' => uniqid("0"),
            'bn' => date('Y-m-d H:i:s'),
            'tempclientName' => $clientdata->clientname,
            'carNumber' => '',
            'carType' => '',
            'carChase' => '',
            'carMotor' => '',
            'Costcenter' => '-1',
            'supplier' => $clientdata->clientid,
            'hidden_debt' => $clientdata->clientdebt,
            'pricetype' => 0,
            'hiddenpricetype' => 0,
            'storeid' => $mysellbilldata->sellbillstoreid,
            'sellerid' => $_SESSION['userid'],
            'billnameid' => 3,
            'settingclient' => 0,
            'settingstore' => 0,
            'settingseller' => 1,
            'settingdate' => 0,
            'settingQuantityAlert' => 0,
            'ordertype' => 0,
            'returnhidden_itr' => 1,
            'sellbilltotalbill' => $mysellbilldata->sellbilltotalbill,
            'sellbillprice' => $mysellbilldata->sellbilltotalbill,
            'distype' => $mysellbilldata->sellbilldiscounttype,
            'gendis' => $mysellbilldata->sellbilldiscount,
            'tax' => $mysellbilldata->tax,
            'sellbillaftertotalbill' => $mysellbilldata->sellbillaftertotalbill,
            'genpay' => $mysellbilldata->sellbilltotalpayed,
            'gen4totalinput' => $mysellbilldata->sellbillaftertotalbill - $mysellbilldata->sellbilltotalpayed,
            'clientdebtafter' => $clientdata->clientdebt + $mysellbilldata->sellbillaftertotalbill - $mysellbilldata->sellbilltotalpayed,
            'comment' => $mysellbilldata->comment,
            'hidden_itr' => count($mysellbildetales),
            'taxOfDiscountPercentage' => $mysellbilldata->taxOfDiscountPer,
            'taxOfDiscountVal' => $mysellbilldata->taxOfDiscountVal,
            'offerId' => $offerId,
            'totalprodiscount' => $mysellbilldata->totalprodiscount,
            'manage_ex' => $mysellbilldata->manage_ex,
            'med_hallmark' => $mysellbilldata->med_hallmark,
            'pay_rec_no' => $mysellbilldata->pay_rec_no,
            'pay_rec_val' => $mysellbilldata->pay_rec_val,
            'decisionNo' => $mysellbilldata->decisionNo,
            'decisionValue' => $mysellbilldata->decisionValue,
        );
        $i = 1;
        $totQuantity = 0;
        foreach ($mysellbildetales as $value) {
            //
            $parcodeType = 'parcode';
            $productserailid = 0;
            $issold = $myProductserialEx->queryallisdSerial($value->sellbilldetailproductid, $value->parcode, " and sizeid=$value->sizeid and colorid=$value->colorid ");
            if ($issold->productserailid > 0 && $issold->don > 0) {
                $parcodeType = 'serialnumber';
                $productserailid = $issold->productserailid;
            }
            $ebillTaxes = R::findAll('sellbilldetailtax', 'sellbilldetailid = ? and conditions = 0 and is_offer =1', [$value->sellbilldetailid]);

            $e = 1;
            foreach ($ebillTaxes as $one) {
                $_POST['type_' . $i . '_' . $e] = $one->type;
                $_POST['subtype_' . $i . '_' . $e] = $one->subtype;
                $_POST['rate_' . $i . '_' . $e] = $one->rate;
                $_POST['amount_' . $i . '_' . $e] = $one->amount;
                $e++;
            }
            $taxesitr = $_POST['taxesitr_' . $i . ''] = $e;




            //
            $_POST['parcode' . $i] = $value->parcode;
            $_POST['parcodeType' . $i] = $parcodeType;
            $_POST['productserailid' . $i] = $productserailid;
            $_POST['prstorid' . $i] = $mysellbilldata->sellbillstoreid;
            $_POST['comment' . $i] = $value->note;
            $_POST['product' . $i] = $value->sellbilldetailproductid;
            $_POST['productunit' . $i] = $value->productunitid;
            $_POST['pronum' . $i] = $value->sellbilldetailquantity;
            $_POST['scunitname' . $i] = 0;
            $_POST['bouns' . $i] = 0;
            $_POST['proprice' . $i] = $value->sellbilldetailprice;
            $_POST['catdis' . $i] = $value->categorydiscount;
            $_POST['productpricetype' . $i] = $value->pricetype;
            $_POST['prodis' . $i] = $value->discountvalue;
            $_POST['discounttype' . $i] = $value->discounttype;
            $_POST['hidden_prototal' . $i] = $value->sellbilldetailtotalprice;

            $_POST['pricetype'] = $value->pricetype;
            $_POST['hiddenpricetype'] = $value->pricetype;

            $totQuantity += $value->sellbilldetailquantity;
            $i++;
        }
        $_POST['sellQuantity'] = $totQuantity;

        ###### 2- do as do="add"
        //"single client"$_POST['supplier'];
        $addData = add();
        // header("location:sellbillController.php?do=editprint&id=".$sellbillId."");
        $sellbillId = $addData[0];
        $returnsellbillId = $addData[1];
        $productsBeforeValid = $addData[2];
        $saveValuebeforeValid = $addData[3];
        $billtype = $addData[4];

        if ($productsBeforeValid == "1" && $saveValuebeforeValid == "1") {
            if ($billtype == "1") {
                // header("location:sellbillController.php?do=show&id=" . $sellbillId . "");
                header("location:sellbillController.php?do=editprint&id=" . $sellbillId . "");
            } elseif ($billtype == "2") {
                //header("location:returnsellbillController.php?do=show&id=" . $returnsellbillId . "");
                header("location:returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "");
            } elseif ($billtype == "3") {
                header("location:sellbillandruternController.php?do=editprint&id=" . $sellbillId . "");
            }
        } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "1") {
            if ($billtype == "1") {
                $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
            } elseif ($billtype == "2") {
                $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
            } elseif ($billtype == "3") {
                $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
            }

            $smarty->assign('urldirect', $url);
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
            } else {
                $note = "There is not enough quantity in stock for the bill";
            }
            $smarty->assign('msgnote', $note);
            $smarty->display("notes2.html");
        } elseif ($productsBeforeValid == "1" && $saveValuebeforeValid == "0") {
            if ($billtype == "1") {
                $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
            } elseif ($billtype == "2") {
                $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
            } elseif ($billtype == "3") {
                $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
            }

            $smarty->assign('urldirect', $url);
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "لا يوجد كمية بالخزنة المبلغ الكافى للفاتورة";
            } else {
                $note = "There is no quantity in the safe, sufficient amount for the bill";
            }
            $smarty->assign('msgnote', $note);
            $smarty->display("notes2.html");
        } elseif ($productsBeforeValid == "0" && $saveValuebeforeValid == "0") {
            if ($billtype == "1") {
                $url = "sellbillController.php?do=editprint&id=" . $sellbillId . "";
            } elseif ($billtype == "2") {
                $url = "returnsellbillController.php?do=editprint&id=" . $returnsellbillId . "";
            } elseif ($billtype == "3") {
                $url = "sellbillandruternController.php?do=editprint&id=" . $sellbillId . "";
            }

            $smarty->assign('urldirect', $url);
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "لا يوجد كمية بالخزنة المبلغ الكافى ولا يوجد بالمخزن الكمية الكافية للفاتورة";
            } else {
                $note = "There is no quantity in the safe, the sufficient amount, and there is not enough quantity in the warehouse for the bill";
            }
            $smarty->assign('msgnote', $note);
            $smarty->display("notes2.html");
        }
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $smarty->assign("Programsettingdata", $Programsettingdata);

    $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("usergroup", $usergroup);

    //    $clientData = loadAllClient();
    //    $smarty->assign("clientData", $clientData);
    //  $sellbillSearchData=loadAllSellBill();
    $smarty->assign("sellbillSearchData", $sellbillSearchData);

    $sellerData = loadseller();
    $smarty->assign("sellerData", $sellerData);

    $sellerinsertData = $userDAO->queryAll();
    $smarty->assign("sellerinsertData", $sellerinsertData);

    $billsettingsData = loadBillProperty(3);
    $smarty->assign("billsettingsData", $billsettingsData);

    $allTypeClient = R::getAll('select typeId,typeName from typeclient where conditions=0');
    $smarty->assign("allTypeClient", $allTypeClient);


    //    $smarty->assign("searchinonestore", $_SESSION['searchinonestore']);
    if ($userdata->userstoreid == 0) {
        if ($userdata->storeids == "") {
            //no store allowed
            $stores = array();
        } else if ($userdata->storeids == 0) {
            //all stores
            $stores = $myStoreEx->queryByConditions();
        } else {
            //some stores
            $stores = $myStoreEx->queryByConditions(' AND  store.storeId in (' . $userdata->storeids . ') ');
        }
    } else {
        $stores = $myStoreEx->queryByConditions(' and store.storeId = ' . $userdata->userstoreid . ' ');
    }

    $smarty->assign("stores", $stores);
    $smarty->assign("storeid", $_SESSION['storeid']);


    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
            $saves = $mySaveRecord->queryAll();
        } else {
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $mySaveEx->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("saves", $saves);
        $smarty->assign("saveid", $_SESSION['saveid']);
    } else {
        $smarty->assign('saveid', $_SESSION['saveid']);
    }





    // $stores = $myStoreRecord->queryAll();
    // $smarty->assign("stores", $stores);
    // $saves = $mySaveRecord->queryAll();
    // $smarty->assign("saves", $saves);

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

    $billOperations = $billOperationDAO->queryAll();
    $smarty->assign("billOperations", $billOperations);

    showAll();
    $smarty->display("sellbillview/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "uploadfile") {
    $sellbillid = filter_input(INPUT_POST, 'sellbillid');
    $handle = new upload($_FILES['imageu']);
    $images = uploadImages($handle, "../views/default/images/sellbill", 300, 300);
    $imageid = filter_input(INPUT_POST, 'imageid');
    if (!$imageid) {
        R::exec("INSERT INTO `sellbillimage`(`sellbillid`, `images`) VALUES
         ($sellbillid, '$images')");
    } else {
        R::exec("UPDATE `sellbillimage` SET `sellbillid`= $sellbillid,`images`='$images'
           WHERE id = $imageid");
    }
} elseif ($do == "executeOperation") {
    include_once("../public/authentication.php");

    // here the function that do the action
    executeOperation();

    //    $clientData = loadAllClient();
    //    $smarty->assign("clientData", $clientData);
    //$sellbillSearchData=loadAllSellBill();
    $smarty->assign("sellbillSearchData", $sellbillSearchData);

    $today = date("Y-m-d H:i:s");
    //showAll($today, $today);
    $smarty->display("sellbillview/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "showallajax") {
    showallajax();
} elseif ($do == "delLaterNakdiPayed") {
    include_once("../public/authentication.php");
    // here the function that do the action
    delLaterNakdiPayed();
    header("location:?do=sucess");
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
##ObgyVisit
elseif ($do == "addObgyVisit") {
    $erpDB = $_POST["erpDB"];
    $sessionDBName = ConnectionProperty::getDatabase();
    if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
        $sessionDBName = $_SESSION['dbname'];
    }
    //choose erpDB user has choosen in obygy_app
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $_SESSION['userid'] = (isset($_POST['userid']) && $_POST['userid'] > 0) ? (int) $_POST['userid'] : 1;
        $_SESSION['saveid'] = (isset($_POST['saveid']) && $_POST['saveid'] > 0) ? (int) $_POST['saveid'] : 1;
    }

    addObgyVisit();

    //go back to your db
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $sessionDBName;
        unset($_SESSION['userid']); //tempppppppppppppppp
        unset($_SESSION['saveid']);
    }
} elseif ($do == "delObgyVisit") {
    $erpDB = $_POST["erpDB"];
    $sellbillId = $_POST["sellbillId"];
    $sessionDBName = ConnectionProperty::getDatabase();
    if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
        $sessionDBName = $_SESSION['dbname'];
    }
    //choose erpDB user has choosen in obygy_app
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;

        //it is reuired by eng.sherif to keep edit info to person who add, not the one who is updating as long as it is not الاستقبال group
        if (isset($_POST['obgyGroupId']) && $_POST['obgyGroupId'] == 3) {
            //it is reception الاستقبال// and its id @royal=3
            //use data coming for user who make update
        } else {
            //keep using the same data of user who made bill
            $billData = $mySellbillRecord->load($sellbillId);
            $_POST['userid'] = $billData->userid;
            $_POST['saveid'] = $billData->sellbillsaveid;
        }

        $_SESSION['userid'] = (isset($_POST['userid']) && $_POST['userid'] > 0) ? (int) $_POST['userid'] : 1;
        $_SESSION['saveid'] = (isset($_POST['saveid']) && $_POST['saveid'] > 0) ? (int) $_POST['saveid'] : 1;
    }
    delete($sellbillId, 1);

    //go back to your db
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $sessionDBName;
        unset($_SESSION['userid']); //tempppppppppppppppp
    }
} elseif ($do == "updateObgyVisit") {
    $sellbillId = $_POST["sellbillId"];
    $erpDB = $_POST["erpDB"];
    $sessionDBName = ConnectionProperty::getDatabase();
    if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
        $sessionDBName = $_SESSION['dbname'];
    }
    //choose erpDB user has choosen in obygy_app
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $billData = $mySellbillRecord->load($sellbillId);
        //it is reuired by eng.sherif to keep edit info to person who add, not the one who is updating as long as it is not الاستقبال group
        if (isset($_POST['obgyGroupId']) && $_POST['obgyGroupId'] == 3) {
            //it is reception الاستقبال// and its id @royal=3
            //use data coming for user who make update
        } else {
            //keep using the same data of user who made bill
            $_POST['userid'] = $billData->userid;
            $_POST['saveid'] = $billData->sellbillsaveid;
        }


        $_SESSION['userid'] = (isset($_POST['userid']) && $_POST['userid'] > 0) ? (int) $_POST['userid'] : 1;
        $_SESSION['saveid'] = (isset($_POST['saveid']) && $_POST['saveid'] > 0) ? (int) $_POST['saveid'] : 1;

        //قيود اليومية
        foreach (explode(',', $billData->dailyentryid) as $entryid) {
            reverseEntryWithItsID($entryid, 1);
        }
    }

    deletesellbill($sellbillId, 1);
    addObgyVisit($sellbillId);

    //go back to your db
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $sessionDBName;
        unset($_SESSION['userid']); //tempppppppppppppppp
        unset($_SESSION['saveid']);
    }
}
##online orders "from shop2"
elseif ($do == "onlineOrderConfirm") {
    $onlineOrderId = (int) filter_input(INPUT_GET, "id");
    $clientChoosen = (int) filter_input(INPUT_GET, "client");
    ###
    $onlineStoreSetting = getOrHandleOnlineStoreSetting();
    ###
    $mainStoreId = explode(',', $onlineStoreSetting->availableStores)[0]; //1;
    $onlineStoreId = $onlineStoreSetting->onlinestoreid;
    ##save as bill
    $addData = addOnlineOrderAsSellBill($onlineOrderId, $onlineStoreId, $clientChoosen, $onlineStoreSetting);
    ##
    //update order status online "in shop2"
    $all_items = array(
        'orderid' => $onlineOrderId,
        'status' => '6'
    ); //6 means accepted تم تنفيذه من خلال المتجر
    CURL_IT($all_items, $onlineStoreSetting->url . '/api_erp/updateOnlineOrderStatus');
    //delete order data
    $onlineTempOrderProductDAO->deleteByOrderid($onlineOrderId);
    $onlineTempOrderDAO->deleteByOnlineorderid($onlineOrderId);
    $onlineTempOrderClientDAO->deleteByOrderid($onlineOrderId);

    $sellbillId = $addData[0];
    $returnsellbillId = $addData[1];
    $productsBeforeValid = $addData[2];
    $saveValuebeforeValid = $addData[3];
    $billtype = $addData[4];
    $billnameId = $_POST['billnameid'];

    header("location:sellbillController.php?do=editprint&id=" . $sellbillId . "");
} elseif ($do == "ebillerrors") {
    $sellbillid = (int) filter_input(INPUT_GET, "sellbillid");
    $etasellbillstatus = R::findAll("etasellbillstatus", " sellbillid =? ", [$sellbillid]);
    $smarty->assign("etasellbillstatus", $etasellbillstatus);
    $smarty->display("sellbillview/ebillerrors.html");
} elseif ($do == "onlineOrderRefuse") {
    $onlineOrderId = (int) filter_input(INPUT_GET, "id");
    ###
    $onlineStoreSetting = getOrHandleOnlineStoreSetting();
    ###
    $mainStoreId = explode(',', $onlineStoreSetting->availableStores)[0]; //1;
    $onlineStoreId = $onlineStoreSetting->onlinestoreid;
    ##
    $onlineTempOrder = $onlineTempOrderDAO->queryByOnlineorderid($onlineOrderId);
    $onlineTempOrderProducts = $onlineTempOrderProductDAO->queryByOrderid($onlineTempOrder->onlineorderid);
    //move products back to main menu
    $operationnum = getNextIdStoreMovement();
    foreach ($onlineTempOrderProducts as $value) {
        //move from store online to mainstore
        moveProductFromStoreToAnother($value->productid, $value->quantity, $onlineStoreId, $mainStoreId, $operationnum);
    }
    //update order status online "in shop2"
    $all_items = array(
        'orderid' => $onlineOrderId,
        'status' => '7'
    ); //7 means refused تم رفضه من خلال المتجر
    CURL_IT($all_items, $onlineStoreSetting->url . '/api_erp/updateOnlineOrderStatus');
    //delete order data
    $onlineTempOrderProductDAO->deleteByOrderid($onlineOrderId);
    $onlineTempOrderDAO->deleteByOnlineorderid($onlineOrderId);
    $onlineTempOrderClientDAO->deleteByOrderid($onlineOrderId);
    header("location:onlinestoresetting.php?do=onlineOrders");
}
## export bill
elseif ($do == "billToExcel") {
    require_once '../library/Classes/PHPExcel.php';
    require_once '../library/Classes/PHPExcel/IOFactory.php';

    $sellbillId = (int) $_GET['sellbillid'];
    $ordertype = (int) $_GET['ordertype'];
    $showDetailData = showDetail($sellbillId, $ordertype);

    //start excel
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->setActiveSheetIndex(0);
    $objPHPExcel->getActiveSheet()
            ->setTitle("sellbill$sellbillId");
    PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);

    //write to excel
    $objPHPExcel->getActiveSheet()
            ->SetCellValue('A1', 'client')
            ->SetCellValue('B1', 'Siam');
    $objPHPExcel->getActiveSheet()
            ->SetCellValue('F1', 'date')
            ->SetCellValue('G1', $showDetailData[0]->sellbilldate);
    $objPHPExcel->getActiveSheet()
            ->SetCellValue('A2', 'billid')
            ->SetCellValue('B2', $showDetailData[0]->sellbillid); //الرقم التسلسلي
    $objPHPExcel->getActiveSheet()
            ->SetCellValue('F2', 'serial')
            ->SetCellValue('G2', $showDetailData[0]->sellbillserial); //رقم الفاتورة
    //set table head
    $myColums = array(
        'catid',
        'CatName',
        'Parcode',
        'product id',
        'product name',
        'quantity',
        'price',
        'sizeid',
        'colorid',
        'sizeName',
        'colorName'
    );
    $RowStartTitles = 3;
    $col = 0;
    foreach ($myColums as $title) {
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartTitles, $title);
    }
    ## Auto size columns for active sheet
    $RowStartProduct = 4;
    //setCellValueByColumnAndRow($column, $row, $value);//Note that rows are 1-based whereas columns are 0-based, so „A1“ becomes (0,1)
    foreach ($showDetailData[1] as $proData) {
        if ($proData->sizeid > 0 && $proData->colorid > 0) {
            //same parcode
        } else {
            $proData->parcode = useSpecializedParcodeDigits($proData->parcode, $proData->sellbilldetailproductid, $Programsettingdata->specializedParcodeDigits);
        }
        $productunitData = loadProductUnitWithProductAndUnit($proData->sellbilldetailproductid, $proData->productunitid);
        $productnumber = $productunitData->productnumber;
        $finalquantity = $proData->sellbilldetailquantity * $productnumber;

        $col = 0;
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->sellbilldetailcatid);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->productCatName);
        $col++;
        $objPHPExcel->getActiveSheet()
                ->getCell('C' . $RowStartProduct)->setValueExplicit($proData->parcode, PHPExcel_Cell_DataType::TYPE_STRING); //this is to save leading zeros at left
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->sellbilldetailproductid);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->productName);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $finalquantity); //sellbilldetailquantity
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->sellbilldetailprice);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->sizeid);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->colorid);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->sizeName);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartProduct, $proData->colorName);
        $RowStartProduct++;
    }
    //style
    $styleArray = array(
        'font' => array(
            'bold' => true,
            'italic' => true,
            //'underline' => true,
            'size' => 11,
            'color' => array(
                'rgb' => 'ffffff'
            ),
            'name' => 'Verdana'
        ),
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
        ),
        'borders' => array(
            'allborders' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
        //'top' => array(
        //    'style' => PHPExcel_Style_Border::BORDER_THICK,
        //),
        //'bottom' => array(
        //    'style' => PHPExcel_Style_Border::BORDER_THICK,
        //),
        ),
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array(
                'rgb' => '666666'
            )
        ),
    );

    $objPHPExcel->getActiveSheet()
            ->getStyle('A3:K3')
            ->applyFromArray($styleArray);
    $objPHPExcel->getActiveSheet()
            ->getStyle('A1:A2')
            ->applyFromArray($styleArray);
    $objPHPExcel->getActiveSheet()
            ->getStyle('F1:F2')
            ->applyFromArray($styleArray);

    foreach (range('A', 'Z') as $columnID) {
        $objPHPExcel->getActiveSheet()
                ->getColumnDimension($columnID)->setWidth(17.1); //->setAutoSize(true);
    }

    // Redirect output to a client’s web browser (Excel5)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;
                filename = "sellbill' . $sellbillId . '.xls"');
    header('Cache-Control: max-age = 0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    //Clearing a Workbook from memory
    $objPHPExcel->disconnectWorksheets();
    unset($objPHPExcel);

    //code guide
    //https://github.com/PHPOffice/PHPExcel/tree/develop/Documentation/markdown/Overview
    /* //Creating a spreadsheet
      $objPHPExcel = new PHPExcel();
      $objPHPExcel->setActiveSheetIndex(0);
      //$objPHPExcel->getActiveSheet()->setTitle('Minimalistic demo');

      //$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'A Text')->SetCellValue('A2', 'A Text');
      //$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'Hello')->setCellValue('B1', 'world!');
      ////setCellValueByColumnAndRow($column, $row, $value);//Note that rows are 1-based whereas columns are 0-based, so „A1“ becomes (0,1)
      //$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 3, "fatmaaa");

      //$objPHPExcel->getActiveSheet()->getStyle("A1:C1")->getFont()->setBold(true);


      //write the Excel file to the harddisk
      //$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
      //$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
      //$objWriter->save('MyExcel.xlsx');
      //or
      // Redirect output to a client’s web browser (Excel5)
      //header('Content-Type: application/vnd.ms-excel');
      //header('Content-Disposition: attachment;filename="results.xls"');
      //header('Cache-Control: max-age=0');
      //$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
      //$objWriter->save('php://output');
      ////Clearing a Workbook from memory
      //$objPHPExcel->disconnectWorksheets();
      //unset($objPHPExcel);
     */
} elseif ($do == "billToPDF") {
    sellBillAsPDF('download');
}
##
elseif ($do == "serializeProducts") {
    $itr = (int) $_POST['itr'];
    $sellbillId = (int) $_POST['sellbillId'];
    $sellbillclientId = (int) $_POST['sellbillclientId'];
    for ($i = 0; $i <= $itr; $i++) {
        $proid = (int) $_POST['proid' . $i];
        $requiredQuantity = (int) $_POST['requiredQuantity' . $i];
        $proSerials = $_POST['proSerials' . $i];
        $sellbilldetailid = $_POST['sellbilldetailid' . $i];

        decreaseProductParcodeSerialQuantity($proid, 0, 0, $requiredQuantity, $proSerials, $sellbillId, $sellbillclientId, $sellbilldetailid, 0, 'add');
    }
} elseif ($do == "changeStatus") {
    $sellbillId = filter_input(INPUT_POST, 'sellbillid');
    $status = filter_input(INPUT_POST, 'status');
    try {
        $billStatus = R::dispense("sellbillstatus");
        $billStatus->sellbillid = $sellbillId;
        $billStatus->status = $status;
        $billStatus->userid = $_SESSION['userid'];
        $billStatus->sysdate = date('Y-m-d H:i:s');
        $billStatusId = R::store($billStatus);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}
$smarty->assign("customValidation", 1);
$smarty->assign("customsellbill", 1);
$smarty->assign("customreturnsellbill", 1);

//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} elseif ($do != "addObgyVisit" && $do != "delObgyVisit" && $do != "updateObgyVisit" && $do != "showallajax" && $do != "billToExcel" && $do != "billToPDF") {
    $smarty->display("footer.html");
}

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

function checkRoundNumbers() {
    global $programSettingExt;

    $roundNumbersStatus = $programSettingExt->getRoundNumbersStatus();
    return $roundNumbersStatus;
}

function checkPreviousPrice() {
    global $programSettingExt;

    $previousPriceStatus = $programSettingExt->getPreviousPriceStatus();
    return $previousPriceStatus;
}

//select data from client tbl
function loadClient() {
    global $myClientRecord;

    $clientData = $myClientRecord->queryByCondition(0);
    return $clientData;
}

//select data from client tbl
function loadAllClient() {
    global $myClientRecord;

    $clientData = $myClientRecord->queryAll();
    return $clientData;
}

function loadAllSellBill() {
    global $mySellbillRecord;

    // select all data from sellbill tbl
    $sellbillSearchData = $mySellbillRecord->queryAll();
    return $sellbillSearchData;
}

// select from Store tbl
function loadStore() {
    global $myStoreRecord;

    // select all data from Storetbl
    $storeData = $myStoreRecord->queryByConditions(0);
    return $storeData;
}

// select from Product tbl
function loadProduct() {
    global $myProductEx;

    // select all data from producttbl
    $productData = $myProductEx->queryWithCoditionsAndCatConditions();

    foreach ($productData as $product) {
        $productcatName;

        $product->productName = loadProductCatNameById($product->productCatId, $productcatName, 1) . "/" . $product->productName;
    }
    return $productData;
}

// select from Product tbl
function loadProductCatNameById($productCatId, $productcatName, $itr) {
    //to use the variable out side the funcion
    global $myProductcatRecord;

    $productcatNamex = $productcatName;
    // select all data from producttbl
    $productcatData = $myProductcatRecord->load($productCatId);

    if (count($productcatData) > 0) {
        if ($itr == 1) {
            $productcatNamex = $productcatData->productCatName;
        } elseif ($itr == 2) {
            $productcatNamex = $productcatData->productCatName . "/" . $productcatNamex;
        }

        if ($productcatData->productCatParent != 0) {
            return loadProductCatNameById($productcatData->productCatParent, $productcatNamex, 2);
        }
    }
    return $productcatNamex;
}

// select from Billname tbl
function loadBillname() {
    global $myBillnameEx;

    // select all data from Billname
    $billnameData = $myBillnameEx->queryByType(0);
    return $billnameData;
}

// select from Billname tbl
function loadBillProperty($billnameid) {
    global $myBillsettingEx;

    // select all data from Billname
    $billsettingsData = $myBillsettingEx->queryWithBillnameId($billnameid);
    return $billsettingsData;
}

// select from user tbl
function loadseller() {

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

    // select all data from user
    $userData = $myUserEx->queryWithLevel(3);

    return $userData;
}

//load sellbill detail
function showDetail($sellbillid, $ordertype) {
    //to use the variable out side the funcion
    global $mySellbillEx;
    global $mySellbilldetailEx;
    global $sellBillOfferEX;
    global $sellBillDetailOfferEX;
    global $clientDeptChangeExt;
    global $billOperationDAO;
    global $sellBillCurrEX;
    global $knownWaysDAO;

    $client_bills;
    $ordertype = $_GET['ordertype'];

    if ($ordertype == 0) { //bill
        //load purchasebillreturn data by id
        $sellbillData = $mySellbillEx->loadSellBillById($sellbillid);
        $billCurrData = $sellBillCurrEX->queryOneBySellbillid($sellbillid);

        $sellbilldetailData = $mySellbilldetailEx->queryWithSellBillId($sellbillid);


        $billOperations = $billOperationDAO->load($sellbillData->billoperationid);
        $sellbillData->billoperationName = $billOperations->name;
        if ($sellbillData->knownwayId) {
            $knownWay = $knownWaysDAO->load($sellbillData->knownwayId);
            $sellbillData->wayName = $knownWay->name;
        }
        ########################################################################
        //Get Payments on a Bill At Controller clientPayedDeptSellBillsController.php
        //and this is like do=="show_details"
        $client_dept_Bills = $clientDeptChangeExt->selectByBillIdAndControl($sellbillid, 'clientPayedDeptSellBillsController.php');
        $client_bills = array();

        $finalnetbillvalue = $sellbillData->sellbillaftertotalbill;
        $waitvalue = $sellbillData->sellbillfinalbill;
        $payed = $sellbillData->sellbilltotalpayed;
        $x = 1;
        foreach ($client_dept_Bills as $cli_bill_val) {
            $clientdebtchangeamount = $cli_bill_val->clientdebtchangeamount;
            $paytype = $cli_bill_val->paytype;
            $date = $cli_bill_val->clientdebtchangedate;

            if ($x == 1) {
                $wait_before = $waitvalue;
                $wait_aftre = $wait_before - ($clientdebtchangeamount); //$wait_before - ( $payed + $clientdebtchangeamount );
            } else {
                $wait_before = $wait_aftre;

                $wait_aftre = $wait_before - $clientdebtchangeamount;
            }
            //if( $waitvalue > 0 ){
            $client_bills[] = array(
                'itra' => $x,
                'finalnetbillvalue' => $finalnetbillvalue,
                'wait_before' => $wait_before,
                'clientdebtchangeamount' => $clientdebtchangeamount,
                'wait_after' => $wait_aftre,
                'date' => $date,
                'paytype' => $paytype,
                'userName' => $cli_bill_val->employeename,
            );

            $x++;
        }
        ########################################################################
        $sellbilldetailtaxdata = R::getAll('SELECT type,subtype,sum(amount) as amount FROM sellbilldetailtax WHERE conditions=0 and sellbilldetailid
            in ( select sellbilldetailid from sellbilldetail where sellbillid = ' . $sellbillid . ')
            group by type,subtype');
    } elseif ($ordertype == 1) { //offer
        //load purchasebillreturn data by id
        $sellbillData = $sellBillOfferEX->loadSellBillById($sellbillid);

        $sellbilldetailData = $sellBillDetailOfferEX->queryWithSellBillId($sellbillid);
    }

    //print_r($sellbilldetailData);
    $quantity = 0;
    foreach ($sellbilldetailData as $sellbilldetail) {
        $quantity = $quantity + ($sellbilldetail->sellbilldetailquantity);
        $sellbilldetail->soldSerialsInDetails;
    }

    ##use currency values
    if (isset($billCurrData)) {
        $sellbillData->sellbilldiscount = $billCurrData->sellbilldiscountC;
        $sellbillData->sellbilltotalbill = $billCurrData->sellbilltotalbillC;
        $sellbillData->sellbillaftertotalbill = $billCurrData->sellbillaftertotalbillC;
        $sellbillData->sellbilltotalpayed = $billCurrData->sellbilltotalpayedC;
        $sellbillData->sellbillfinalbill = $billCurrData->sellbillfinalbillC;
        $sellbillData->sellbildirectpayment = $billCurrData->sellbildirectpaymentC;
        $sellbillData->tax = $billCurrData->taxC;
        $sellbillData->delivery = $billCurrData->deliveryC;
        $sellbillData->totalafterdelivery = $billCurrData->totalafterdeliveryC;
        $sellbillData->cashPayed = $billCurrData->cashPayedC;
        $sellbillData->visaPayed = $billCurrData->visaPayedC;
        $sellbillData->extraDiscountVal = $billCurrData->extraDiscountValC;
        $sellbillData->taxOfDiscountVal = $billCurrData->taxOfDiscountValC;
        $sellbillData->totalprodiscountC = $billCurrData->totalprodiscountC;
        ##
        $sellbillData->sellbilltotaldeptbefor = $sellbillData->sellbilltotaldeptbefor * $billCurrData->conversionFactor;
        $sellbillData->sellbilltotaldeptafter = $sellbillData->sellbilltotaldeptafter * $billCurrData->conversionFactor;
        foreach ($sellbilldetailData as $value) {
            $value->sellbilldetailprice = $value->sellbilldetailpriceC;
            $value->sellbilldetailtotalprice = $value->sellbilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
    }

    return array(
        $sellbillData,
        $sellbilldetailData,
        $quantity,
        $client_bills,
        $billCurrData,
        $sellbilldetailtaxdata
    );
}

// add in sellbill tbl
function add() {
    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbillEx;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    global $myReturnsellbill;
    global $myReturnsellbillRecord;
    global $myReturnsellbilldetail;
    global $myReturnsellbilldetailRecord;

    global $mySellbillandrutern;
    global $mySellbillandruternRecord;
    global $mySellandruternbilldetail;
    global $mySellandruternbilldetailRecord;

    //
    global $sellBillCurr;
    global $sellBillCurrDAO;
    global $sellBillCurrEX;
    global $sellBillAndRuternCurr;
    global $sellBillAndRuternCurrDAO;
    global $sellBillAndRuternCurrEX;
    global $returnSellBillCurr;
    global $returnSellBillCurrDAO;
    global $returnSellBillCurrEX;
    global $mySaveEx;

    //Temsellbill
    global $Temsellbill;
    global $TemsellbillDAO;
    //Temsellbilldetail
    global $Temsellbilldetail;
    global $TemsellbilldetailDAO;

    //Temreturnsellbill
    global $Temreturnsellbill;
    global $TemreturnsellbillDAO;
    //Temreturnsellbilldetail
    global $Temreturnsellbilldetail;
    global $TemreturnsellbilldetailDAO;

    //Temsellbillandrutern
    global $Temsellbillandrutern;
    global $TemsellbillandruternDAO;
    //Temsellandruternbilldetail
    global $Temsellandruternbilldetail;
    global $TemsellandruternbilldetailDAO;

    global $CostcenterEX;
    global $CostcenterDAO;
    global $Costcenter;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;

    global $soldSerialProduct;
    global $soldSerialProductDAO;

    global $ProductunitDAO;
    global $Productunit;
    global $myProductunitEx;

    global $myClientRecord;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    global $dailyEntryDebtor2;
    global $dailyEntryDebtorDAO2;

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

    global $accountsTreeDAO;
    global $accountsTree;

    global $mySave;
    global $mySaveRecord;

    global $myBillsettingEx;

    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $sellBillDetailOfferDAO;
    global $sellBillOfferDAO;

    global $bankAccountEX;
    global $bankAccountDAO;
    global $bankAccount;

    global $sellBillOfferEX;
    global $myStoreRecord;

    global $clientEX;

    //
    global $sellbillId; //nedded for collective product##fatma
    global $firstProductId; //nedded for royal
    global $noOfDecimalPlaces;

    global $Programsettingdata;
    global $sellbillDate;
    global $sellCostsArray;
    global $ordertype;

    if (!isset($_POST['bns']) || empty($_POST['bns'])) {
        $_POST['bns'] = uniqid("0");
    }

    liveBackupComment("-- bill add start - with serial " . $_POST['bns']);
    //Transaction
    $mytransactions = new Transaction();
    $storeDetailIds = $sizeColrDetailIds = [];
    try {

        $ordertype = (int) $_POST["ordertype"]; //0 bill , 1 offfer
        $offerId = (int) $_POST["offerId"]; //0 bill , 1 offfer
        $tempSaveBillId = (int) $_POST["tempSaveBillId"]; //bill  with autosave
        $billnameId = $_POST['billnameid'];
        $saveid = (int) $_POST['saveid'];
        if (!isset($_POST['saveid']) || empty($saveid)) {
            $saveid = $_SESSION['saveid'];
        }

        $settingClient = (int) $_POST['settingclient'];
        $settingStore = (int) $_POST['settingstore'];

        $settingSeller = (int) $_POST['settingseller'];
        $settingDate = (int) $_POST['settingdate'];
        $settingQuantityCondition = $_POST['settingquantitycondition'];

        $tempClientName = $_POST['tempclientName'];

        $sellbillclientId = $_POST['supplier'];

        $sellbilltotaldeptBefor = $_POST['hidden_debt'];
        $sellbilltotaldeptAfter = $_POST['clientdebtafter'];
        $tax = (float) $_POST["tax"];
        $taxVal = (float) $_POST["taxVal"];

        $currencyId = (int) $_POST["currencyId"];
        $cFactor = (float) $_POST["cFactor"];

        $sellbillcarnumber = $_POST['carNumber'];
        $sellbillcartype = $_POST['carType'];
        $sellbillcarchase = $_POST['carChase'];
        $sellbillcarmotor = $_POST['carMotor'];

        $Costcenterid = (int) $_POST["Costcenter"];
        $billReservation = (int) $_POST["billReservation"];
        $billReservationDate = $_POST["billReservationDate"];

        $collectionType = (int) $_POST["collectionType"];
        $collectionDate = $_POST["collectionDate"];

        $isTaxBill = $_POST["isTaxBill"];
        $taxBillNumber = $_POST["taxBillNumber"];

        $knownwayId = (int) $_POST["knownwayId"];
        $travelDriverId = (int) $_POST["travelDriverId"];
        $travelBusId = (int) $_POST["travelBusId"];
        $travelPathId = (int) $_POST['travelPathId'];
        $travelTripId = (int) $_POST['travelTripId'];
        $travelTripTypeId = (int) $_POST['travelTripTypeId'];
        $travelTripDateId = (int) $_POST['travelTripDateId'];
        $sellToSupplier = (int) $_POST['sellToSupplier'];
        $whatShippingCost = (int) $_POST['whatShippingCost'];


        $clientName = loadClientNameById($sellbillclientId);
        if (empty($tempClientName)) {
            $tempClientName = $_POST['tempclientName'] = $clientName;
        }

        $sellbildirectPayment;
        //client
        if ($settingClient == 0 && $_POST['supplier'] != 1) {
            $sellbildirectPayment = 1;
        } else {
            $sellbildirectPayment = 0;
        }

        //Date
        if ($settingDate == 0) {
            $sellbillDate = $_POST['bn']; //date("Y-m-d H:i:s");
        } else {
            $sellbillDate = date("Y-m-d H:i:s");
        }

        //Store
        if ($settingStore == 0) {
            $sellbillstoreId = $_POST['storeid'];
        } else {
            $sellbillstoreId = $_POST['storeid'];
        }

        //seller
        if ($settingSeller == 0) {
            $sellerId = $_POST['sellerid'];
            if ($sellerId == "-1" || $sellerId == "" || $sellerId == NULL) {
                $sellerId = 0;
            }
        } else {
            $sellerId = 0;
        }

        $comment = $_POST['comment'];

        $sellbillSerial = $_POST['bns'];
        $sellbillno = $_POST['sellbillno'];
        //$priceType = $_POST['hiddenpricetype'];
        $priceType = (int) $_POST['pricetype'];

        $sellbilltotalBill = $_POST['sellbilltotalbill']; //اجمالى الفاتورة قبل الخصم
        $sellbillDiscountType = $_POST['distype']; //نوع الخصم
        $visa = (float) $_POST['genpayvisa'];
        $visaAccount = (int) $_POST['visaAccount'];
        if (empty($visaAccount)) {
            $visa = 0;
        }
        $isBankAccountTransfer = (int) $_POST['isBankAccountTransfer'];
        $extraDiscountPer = (float) $_POST['extraDiscountPer'];
        $extraDiscountVal = (float) $_POST['extraDiscountVal'];
        $taxOfDiscountPer = (float) $_POST['taxOfDiscountPercentage'];
        $taxOfDiscountVal = (float) $_POST['taxOfDiscountVal'];

        $sellbillDiscount = (float) $_POST['gendis']; //قيمة الخصم
        $sellbillAftertotalBill = (float) $_POST['sellbillaftertotalbill']; //القيمة بعد الخصم
        $sellbilltotalPayed = (float) $_POST['genpay']; //المدفوع
        if ($sellbillAftertotalBill > 0) {
            $sellbillFinalbill = $sellbillAftertotalBill - $sellbilltotalPayed - $visa; //المتبقى
        } else {
            //return is more
            $sellbillFinalbill = $sellbillAftertotalBill + $sellbilltotalPayed + $visa; //المتبقى
        }

        $sellbillPrice = (float) $_POST['sellbillprice']; //اجمالى المبيعات
        $returnsellbillPrice = (float) $_POST['returnsellbillprice']; //اجمالى مردودات المبيعات
        $sellQuantity = (float) $_POST['sellQuantity'];
        $returnsellQuantity = (float) $_POST['returnsellQuantity'];

        /* -- reverse store operations on stores for offer  ----------------- */
        if ($offerId > 0) {
            $oldOrdertype = $ordertype;
            $ordertype = 1;
            reverseOfferStoreMovement($offerId);
            $ordertype = $oldOrdertype;
        }

        /* ------------------------------------------------------------------ */

        if ($ordertype == 0) { //bill only not offer
            $clientdata = getClientDataFromClientInUseSP($sellbillclientId);
            //$clientdata = $myClientRecord->load($sellbillclientId);
        }

        $sellbilltotaldeptBefor = $clientdata->clientdebt; //$_POST['hidden_debt'];
        $gen4totalinput = $sellbillAftertotalBill - $sellbilltotalPayed - $visa; //$_POST["gen4totalinput"];
        if ($currencyId > 1) {
            $gen4totalinput = $gen4totalinput / $cFactor;
        }
        $totalprodiscount = (float) $_POST['totalProDis']; //خصومات المنتج
        $manage_ex = (float) $_POST['manage_ex'];
        $med_hallmark = (float) $_POST['med_hallmark'];
        $pay_rec_no = (float) $_POST['pay_rec_no'];
        $pay_rec_val = (float) $_POST['pay_rec_val'];
        $decisionNo = (float) $_POST['decisionNo'];
        $decisionValue = (float) $_POST['decisionValue'];
        ##curr conversion
        $billCurrInsertId = 0;
        //$saveData = $mySaveEx->loadForUpdateEx($_SESSION['saveid']);
        $saveData = $mySaveEx->loadEx($_SESSION['saveid']);
        $saveConversionFactor = $saveData->conversionFactor;
        $sellbilldiscountC = $sellbillDiscount;
        $sellbilltotalbillC = $sellbilltotalBill;
        $sellbillaftertotalbillC = $sellbillAftertotalBill;
        $sellbilltotalpayedC = $sellbilltotalPayed;
        $sellbillfinalbillC = $sellbillFinalbill;
        $sellbildirectpaymentC = $sellbildirectPayment;
        $taxValC = $taxVal;
        $deliveryC = $sellbilldelivery;
        $totalafterdeliveryC = $totalaafterdelivery;
        $cashPayedC = $sellbilltotalPayed;
        $visaPayedC = $visa;
        $extraDiscountValC = $extraDiscountVal;
        $sellbilldiscountC = $sellbillDiscount;
        $totalprodiscountC = $totalprodiscount;
        if ($currencyId > 1) {
            if ($sellbillDiscountType != "2")
                $sellbillDiscount = $sellbillDiscount / $cFactor;
            $sellbilltotalBill = $sellbilltotalBill / $cFactor;
            $sellbillAftertotalBill = $sellbillAftertotalBill / $cFactor;
            $sellbilltotalPayed = $sellbilltotalPayed / $cFactor;
            $sellbillFinalbill = $sellbillFinalbill / $cFactor;
            $sellbildirectPayment = 1;
            $taxVal = $taxVal / $cFactor;
            $sellbilldelivery = $sellbilldelivery / $cFactor;
            $totalaafterdelivery = $totalaafterdelivery / $cFactor;
            $cashPayed = $sellbilltotalPayed / $cFactor;
            $visa = $visa / $cFactor;
            $extraDiscountVal = $extraDiscountVal / $cFactor;
            $taxOfDiscountVal = $taxOfDiscountVal / $cFactor;
            $totalprodiscount = $totalprodiscount / $cFactor;
            $manage_ex = $manage_ex / $cFactor;
            $med_hallmark = $med_hallmark / $cFactor;
            $pay_rec_no = $pay_rec_no / $cFactor;
            $pay_rec_val = $pay_rec_val / $cFactor;
        }
        ###################################################
        if ($sellbillclientId == 1) {
            $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + $gen4totalinput; //$_POST['clientdebtafter'];
        } else {

            $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + $gen4totalinput; //$sellbillFinalbill;
        }

        $sellbilldelivery = (float) $_POST['delivery']; //قيمه الشحن / التوصيل
        $totalaafterdelivery = (float) $_POST['valdeliveryhidden']; //الاجمالي العام بعد التوصيل
        ##get $billTotalBeforeDiscount
        $billTotalBeforeDiscount = $sellbilltotalBill;
        ##get $billDiscountVal
        $billDiscountVal = $sellbillDiscount;
        if ($sellbillDiscountType == "2") {
            $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
            $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
        }
        ########################################################################
        //////////////////////////////////////////////////////////////////////////
        $sellbillItr = (int) $_POST['hidden_itr'];
        $returnSellbillItr = (int) $_POST['returnhidden_itr'];

        $productsBeforeValid = 1;
        $saveValuebeforeValid = 1;
        /* ----------------------------- */
        $sellbillId;
        $returnsellbillId;
        $billtype;
        /* ------------------------ */
        if ($ordertype == 0) { //bill
            if ($billnameId != 11) {
                //check storerdetail value
                //check product quantity
                $settingQuantityAlert = (int) $_POST['settingQuantityAlert'];
                if ($sellbillPrice >= 0 && $settingQuantityAlert == 0) {
                    $h = 1;
                    for ($h = 1; $h <= $sellbillItr; $h++) {
                        $productId = $_POST['product' . $h . ''];

                        $sizeId = 0;
                        $colorId = 0;
                        $sizeColorStoreDetailId = 0;
                        if (strpos($productId, "hasSizeColor") !== false) {
                            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                            $productId = $productIdComplex[0];
                            $sizeId = $productIdComplex[1];
                            $colorId = $productIdComplex[2];
                            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                        }
                        $productQuantity = $_POST['pronum' . $h . ''];

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

                            //get storefrom productquantity before change
                            $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];
                            $isService = (int) $storedetailData[3];

                            //check if productquantityFromBefore greater than 0 or not
                            if ($isService == 0) { //product
                                $productsBeforeValid = 1;
                                if ($productquantityBefore > 0 && count($allStoredetailData) > 0) {
                                    $productsAfterValid = $productquantityBefore - $productQuantity;

                                    if ($productsAfterValid >= 0) {
                                        $productsBeforeValid = 1;
                                    } else {
                                        $productsBeforeValid = 0;
                                        //return $productsBeforeValid;
                                    }
                                } else {
                                    $productsBeforeValid = 0;
                                    //return $productsBeforeValid;
                                }
                            } else {
                                //service
                                $productsBeforeValid = 1;
                            }
                        }
                    }
                }

                /////////////////check savefrom value before transfer//////////////////////
                if ($returnsellbillPrice > 0 && ($sellbillPrice <= 0 || $sellbillAftertotalBill)) {
                    $saveValueafterValid;

                    //get save value
                    $saveValueBefore = getSaveValueBefore($saveid);

                    $saveValueafterValid = $saveValueBefore - $sellbilltotalPayed;

                    if ($saveValueafterValid >= 0) {
                        $saveValuebeforeValid = 1;
                    } else {
                        $saveValuebeforeValid = 0;
                        //return $saveValuebeforeValid;
                    }
                }

                $billHasReturn = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 1);
                $billHasReturn = $billHasReturn[0];
                $billtype;
                //check if bill has main part of sell or buy. which is not return
                $billHasSell = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 16);
                $billHasSell = $billHasSell[0];
                $billHasReturn->billsettingsvalue == 0;
                //use it if value of bill is 0 only
                $bill_is = '';
                //if ($sellbillPrice == 0 && $returnsellbillPrice == 0) {
                if ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 0) {
                    //بيع و مردود
                    $bill_is = 'sellAndRet';
                } elseif ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 1) {
                    //مبيعات
                    $bill_is = 'sell';
                } elseif ($billHasSell->billsettingsvalue == 1 && $billHasReturn->billsettingsvalue == 0) {
                    //مردود
                    $bill_is = 'ret';
                }
                //                else {
                //                    //بيع و مردود
                //                    $bill_is = 'sellAndRet';
                //                }
                //}
                // مبيعات و ومردودات
                //insert data into Sellbillandrutern tbl
                if (($sellbillPrice > 0 && $returnsellbillPrice > 0) || $bill_is == 'sellAndRet') {
                    /// print_r(11111);
                    $billtype = 3; // مبيعات و ومردودات
                    $mySellbillandrutern->billnameid = $billnameId;
                    $mySellbillandrutern->conditions = 0;
                    $mySellbillandrutern->sellbildirectpayment = $sellbildirectPayment;
                    $mySellbillandrutern->sellbillaftertotalbill = $sellbillAftertotalBill;
                    $mySellbillandrutern->sellbillclientid = $sellbillclientId;
                    $mySellbillandrutern->sellbillclientname = $clientName;
                    $mySellbillandrutern->sellbilldate = $sellbillDate;
                    $mySellbillandrutern->sellbilldiscount = $sellbillDiscount;
                    $mySellbillandrutern->sellbilldiscounttype = $sellbillDiscountType;
                    $mySellbillandrutern->tempclientName = $tempClientName;
                    $mySellbillandrutern->sellQuantity = $sellQuantity;
                    $mySellbillandrutern->returnsellQuantity = $returnsellQuantity;
                    $mySellbillandrutern->tax = $tax;

                    if ($sellbilltotalBill < 0) {
                        //$sellbillFinalbill = $sellbillAftertotalBill + $sellbilltotalPayed;
                        $sellbillFinalbill = $sellbillAftertotalBill + abs($sellbilltotalPayed) + abs($visa);
                        $gen4totalinput = $sellbillAftertotalBill + abs($sellbilltotalPayed) + abs($visa);
                        $sellbilltotaldeptAfter = $sellbilltotaldeptBefor - ($gen4totalinput * -1);
                    }
                    $mySellbillandrutern->sellbillfinalbill = $sellbillFinalbill;
                    $mySellbillandrutern->sellbillsaveid = $saveid;
                    $mySellbillandrutern->sellbillserial = $sellbillSerial;
                    $mySellbillandrutern->sellbillstoreid = $sellbillstoreId;
                    $mySellbillandrutern->sellbillsysdate = date("Y-m-d H:i:s");
                    $mySellbillandrutern->sellbilltotalbill = $sellbilltotalBill;
                    $mySellbillandrutern->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
                    $mySellbillandrutern->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                    $mySellbillandrutern->sellbilltotalpayed = $sellbilltotalPayed + $visa;
                    $mySellbillandrutern->sellerid = $sellerId;
                    $mySellbillandrutern->userid = $_SESSION['userid'];
                    $mySellbillandrutern->sellbillprice = $sellbillPrice;
                    $mySellbillandrutern->returnsellbillprice = $returnsellbillPrice;
                    $mySellbillandrutern->carnumber = $sellbillcarnumber;
                    $mySellbillandrutern->cartype = $sellbillcartype;
                    $mySellbillandrutern->carchase = $sellbillcarchase;
                    $mySellbillandrutern->carmotor = $sellbillcarmotor;
                    $mySellbillandrutern->costcenterid = $Costcenterid;
                    $mySellbillandrutern->dailyentryid = 0;
                    $mySellbillandrutern->comment = $comment;
                    $mySellbillandrutern->cashPayed = $sellbilltotalPayed;
                    $mySellbillandrutern->visaPayed = $visa;
                    $mySellbillandrutern->visaAccountId = $visaAccount;
                    $mySellbillandrutern->isBankAccountTransfer = $isBankAccountTransfer;
                    $mySellbillandrutern->extraDiscountPer = $extraDiscountPer;
                    $mySellbillandrutern->extraDiscountVal = $extraDiscountVal;
                    $mySellbillandrutern->taxOfDiscountPer = $taxOfDiscountPer;
                    $mySellbillandrutern->taxOfDiscountVal = $taxOfDiscountVal;
                    $mySellbillandrutern->billReservation = $billReservation;
                    $mySellbillandrutern->billReservationDate = $billReservationDate;
                    $mySellbillandrutern->obgyBillType = (int) $_POST['obgyBillType'];
                    $mySellbillandrutern->billoperationid = (int) $_POST['billoperationid'];
                    $mySellbillandrutern->pricetype = $priceType;
                    $mySellbillandrutern->currencyId = $currencyId;
                    $mySellbillandrutern->sellbillno = $sellbillno;
                    $mySellbillandrutern->totalprodiscount = $totalprodiscount;
                    $mySellbillandrutern->manage_ex = $manage_ex;
                    $mySellbillandrutern->med_hallmark = $med_hallmark;
                    $mySellbillandrutern->pay_rec_no = $pay_rec_no;
                    $mySellbillandrutern->pay_rec_val = $pay_rec_val;
                    $mySellbillandrutern->decisionNo = $decisionNo;
                    $mySellbillandrutern->decisionValue = $decisionValue;

                    if ($tempSaveBillId > 0) {
                        $sellbillId = $tempSaveBillId;
                        $mySellbillandrutern->sellbillid = $tempSaveBillId;
                        $mySellbillandruternRecord->update($mySellbillandrutern);

                        //this will make details of auto save del all then insert =>it is faster "0.6 sec for 20products in bill" but lose indexes of table
                        //comment that line it would be update statments//but also uncomment code of update details
                        $mySellandruternbilldetailRecord->deleteBySellbillid($tempSaveBillId);
                    } else {
                        $sellbillId = $mySellbillandruternRecord->insert($mySellbillandrutern);
                    }
                    ##curr conversion
                    if ($currencyId > 1) {
                        $sellBillAndRuternCurr->sellbillid = $sellbillId;
                        $sellBillAndRuternCurr->conversionFactor = $cFactor;
                        $sellBillAndRuternCurr->sellbilldiscountC = $sellbilldiscountC;
                        $sellBillAndRuternCurr->sellbilltotalbillC = $sellbilltotalbillC;
                        $sellBillAndRuternCurr->sellbillaftertotalbillC = $sellbillaftertotalbillC;
                        $sellBillAndRuternCurr->sellbilltotalpayedC = $sellbilltotalpayedC;
                        $sellBillAndRuternCurr->sellbillfinalbillC = $sellbillfinalbillC;
                        $sellBillAndRuternCurr->sellbildirectpaymentC = 1;
                        $sellBillAndRuternCurr->taxC = $taxC;
                        //                        $sellBillAndRuternCurr->deliveryC = $deliveryC;
                        //                        $sellBillAndRuternCurr->totalafterdeliveryC = $totalafterdeliveryC;
                        $sellBillAndRuternCurr->cashPayedC = $cashPayedC;
                        $sellBillAndRuternCurr->visaPayedC = $visaPayedC;
                        $sellBillAndRuternCurr->extraDiscountValC = $extraDiscountValC;
                        $sellBillAndRuternCurr->taxOfDiscountValC = $taxOfDiscountValC;
                        $sellBillAndRuternCurr->saveConversionFactor = $saveConversionFactor;
                        $sellBillAndRuternCurr->totalprodiscountC = $totalprodiscountC;
                        $billCurrInsertId = $sellBillAndRuternCurrDAO->insert($sellBillAndRuternCurr);
                    }

                    //affect client debt first so that making two bills in same time dont corrupt debt
                    if ($sellbillclientId != 0) {
                        //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                        //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                        {

                            //update rawmaterialssupplierdebt
                            updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                            if ($sellbilltotalBill < 0) {
                                $sellbillFinalbill = $sellbillFinalbill * -1;
                                insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 1, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, $sellbilltotalPayed);
                            } else {
                                insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, $sellbilltotalPayed);
                            }
                            markClientAsNOTInUse($sellbillclientId);
                        }
                    }

                    $Costcenterdetail->costamount = $sellbillAftertotalBill;
                    $Costcenterdetail->costcenterid = $Costcenterid;
                    $Costcenterdetail->costdate = date('Y-m-d');
                    $Costcenterdetail->del = 0;
                    $Costcenterdetail->modelid = $sellbillId;
                    $Costcenterdetail->processname = 'فاتوره مبيعات ومردودات';
                    $Costcenterdetail->tablename = 'sellbillandruternController.php';
                    $Costcenterdetail->type = 2;
                    $Costcenterdetail->uesrid = $_SESSION['userid'];

                    if ($Costcenterid != -1 && $Costcenterid != '-1') {
                        $CostcenterdetailDAO->insert($Costcenterdetail);
                    }

                    //insert Sell Data into Sellandruternbilldetail tbl
                    $sellbillItr = $_POST['hidden_itr'];
                    $h = 1;
                    for ($h = 1; $h <= $sellbillItr; $h++) {
                        ## if input are encoded in json put it again in post
                        if (isset($_POST["obj" . $h])) {
                            foreach (json_decode(str_replace("'", '"', $_POST["obj" . $h]), true) as $key => $value) {
                                $_POST[$key . $h] = $value;
                            }
                        }

                        $parcode = $_POST['parcode' . $h . ''];
                        $parcodeType = $_POST['parcodeType' . $h . ''];
                        $productserailId = $_POST['productserailid' . $h . ''];
                        $productId = $_POST['product' . $h . ''];
                        $sizeId = 0;
                        $colorId = 0;
                        $sizeColorStoreDetailId = 0;
                        if (strpos($productId, "hasSizeColor") !== false) {
                            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                            $productId = $productIdComplex[0];
                            $sizeId = $productIdComplex[1];
                            $colorId = $productIdComplex[2];
                            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                        }
                        $productunitId = $_POST['productunit' . $h . ''];
                        $proHeight = (float) $_POST['proHeight' . $h . ''];
                        $proWidth = (float) $_POST['proWidth' . $h . ''];
                        $quantity = $_POST['pronum' . $h . ''];
                        $price = $_POST['proprice' . $h . ''];
                        $catdis = $_POST['catdis' . $h . ''];
                        $discountValue = $_POST['prodis' . $h . ''];
                        $discounttype = $_POST['discounttype' . $h . ''];
                        $totalPrice = $_POST['hidden_prototal' . $h . ''];
                        $comment = $_POST['comment' . $h . ''];
                        $prstorid = $_POST['prstorid' . $h . ''];
                        $scunitname = $_POST['scunitname' . $h . ''];
                        $pricetypepro = $_POST['pricetypepro' . $h . ''];
                        $proSerials = $_POST['proSerials' . $h . ''];

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

                            $sellbillstoreId = $prstorid;
                        } else {
                            $sellbillstoreId = $_POST['storeid'];
                            //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                        }

                        if ($productunitId == "") {
                            $productunitId = 0;
                        }

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

                            if ($firstProductId == 0) {
                                $firstProductId = $productId;
                            }
                            $productData = loadProductById($productId);
                            //
                            $productnumber = (float) $_POST['proNum' . $h];
                            if ($productnumber <= 0) {
                                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                                $productnumber = $productunitData->productnumber;
                            }
                            $finalquantity = $quantity * $productnumber;
                            //
                            $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($sellbillstoreId, $productId, $sizeId, $colorId, $productData->productBuyPrice, $finalquantity, 0);
                            $theBuyPrice = $comingData[0];
                            $buyPricesHistoryBookIdQuantity = $comingData[1];
                            $mySellandruternbilldetail->buyprice = $theBuyPrice; //$productData->productBuyPrice;
                            $mySellandruternbilldetail->buyPricesHistoryBookIdQuantity = $buyPricesHistoryBookIdQuantity;

                            $mySellandruternbilldetail->discountvalue = $discountValue;
                            $mySellandruternbilldetail->note = $comment;
                            $mySellandruternbilldetail->parcode = $parcode;
                            $mySellandruternbilldetail->pricetype = $priceType;
                            $mySellandruternbilldetail->productunitid = $productunitId;
                            $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                            $mySellandruternbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                            $mySellandruternbilldetail->sellbilldetailprice = $price;
                            $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                            $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                            $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                            $mySellandruternbilldetail->sellbillid = $sellbillId;
                            $mySellandruternbilldetail->selltype = 0; //مبيعات
                            $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                            $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                            $mySellandruternbilldetail->storeid = $sellbillstoreId;
                            $mySellandruternbilldetail->discounttype = $discounttype;
                            $mySellandruternbilldetail->otherdetailquantity = $scunitname;
                            $mySellandruternbilldetail->sizeid = $sizeId;
                            $mySellandruternbilldetail->colorid = $colorId;
                            $mySellandruternbilldetail->pricetypepro = $pricetypepro;
                            $mySellandruternbilldetail->proHeight = $proHeight;
                            $mySellandruternbilldetail->proWidth = $proWidth;
                            $mySellandruternbilldetail->soldSerialsInDetails = $proSerials;

                            ##curr conversion
                            $mySellandruternbilldetail->sellbilldetailpriceC = $mySellandruternbilldetail->sellbilldetailprice;
                            $mySellandruternbilldetail->sellbilldetailtotalpriceC = $mySellandruternbilldetail->sellbilldetailtotalprice;
                            $mySellandruternbilldetail->discountvalueC = $mySellandruternbilldetail->discountvalue;
                            $mySellandruternbilldetail->proSellTrackingSerial = $_POST['proSellTrackingSerial' . $h];
                            if ($currencyId > 1) {
                                $price = $price / $cFactor;
                                $totalPrice = $totalPrice / $cFactor;
                                $discountValue = $discountValue / $cFactor;

                                $mySellandruternbilldetail->sellbilldetailprice = $price;
                                $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                                $mySellandruternbilldetail->discountvalue = $discountValue;
                            }
                            ##################################
                            //  print_r($mySellandruternbilldetail);
                            $tempSaveBillIdRow = (int) filter_input(INPUT_POST, "tempSaveBillIdRow$h");
                            //                            if ($tempSaveBillId > 0 && $tempSaveBillIdRow > 0) {
                            //                                $detailId = $tempSaveBillIdRow;
                            //                                $mySellandruternbilldetail->sellbilldetailid = $tempSaveBillIdRow;
                            //                                $mySellandruternbilldetailRecord->update($mySellandruternbilldetail);
                            //                            } else {
                            $detailId = $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);
                            //                            }
                            //update DON if is Serial
                            if (!empty($proSerials)) {
                                decreaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillId, $sellbillclientId, $detailId, 1, 'add');
                            } else if ($parcodeType == "serialnumber") {
                                //update don column (quantity) in productserial table
                                updateSerailQty($productserailId, $finalquantity);
                                insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 1, $sellbillclientId);
                            }

                            $isService = isService($productId);
                            if ($isService == 0) { //if product
                                //get store productquantity before change
                                $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                $allStoredetailData = $storedetailData[0];
                                $storedetailId = $storedetailData[1];
                                $productquantityBefore = $storedetailData[2];

                                if (count($allStoredetailData) > 0) {

                                    //update productquantity in storedetail
                                    $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "فاتوره مبيعات ومردودات", "sellbillandruternController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                } else {
                                    $specialQuantityAfter = $finalquantity * -1;

                                    //insert in storedetail tbl
                                    $strDtlIds = $insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "فاتوره مبيعات ومردودات", "sellbillandruternController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                }

                                //other unit
                                if ($scunitname > 0) {
                                    $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                    $allStoredetailDataother = $allStoredetailData2[0];
                                    $storeDetailIdother = $allStoredetailData2[1];
                                    $productQuantityBeforeother = $allStoredetailData2[2];

                                    if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                        //update productquantity in storedetail
                                        $finalquantityother = $productQuantityBeforeother - $scunitname;
                                        $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", date("Y-m-d H:i:s"), 1);
                                    } else {
                                        //insert in storedetail tbl
                                        if ($scunitname > 0) {
                                            $strDtlIds = insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname) * -1, date("Y-m-d H:i:s"), 1);

                                            //insert in storereport
                                            insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname) * -1, 1, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", date("Y-m-d H:i:s"), 1);
                                        }
                                    }
                                }

                                if ($sizeId == 0 && $colorId == 0)
                                    $storeDetailIds[] = $storedetailId ? $storedetailId : $strDtlIds[0];
                                else
                                    $sizeColrDetailIds[] = $storeDetailIdother ? $storeDetailIdother : $strDtlIds[1];
                            }
                        }
                    }

                    //insert Return Data into Sellandruternbilldetail tbl
                    $returnSellbillItr = $_POST['returnhidden_itr'];
                    $h = 1;
                    for ($h = 1; $h <= $returnSellbillItr; $h++) {
                        ## if input are encoded in json put it again in post
                        if (isset($_POST["objRet" . $h])) {
                            foreach (json_decode(str_replace("'", '"', $_POST["objRet" . $h]), true) as $key => $value) {
                                $_POST[$key . $h] = $value;
                            }
                        }
                        $parcode = $_POST['returnparcode' . $h . ''];
                        $parcodeType = $_POST['returnparcodeType' . $h . ''];
                        $productserailId = $_POST['returnproductserailid' . $h . ''];
                        $productId = $_POST['returnproduct' . $h . ''];
                        $sizeId = 0;
                        $colorId = 0;
                        $sizeColorStoreDetailId = 0;
                        if (strpos($productId, "hasSizeColor") !== false) {
                            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                            $productId = $productIdComplex[0];
                            $sizeId = $productIdComplex[1];
                            $colorId = $productIdComplex[2];
                            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                        }
                        $productunitId = $_POST['returnproductunit' . $h . ''];
                        $proHeight = (float) $_POST['returnproHeight' . $h . ''];
                        $proWidth = (float) $_POST['returnproWidth' . $h . ''];
                        $quantity = $_POST['returnpronum' . $h . ''];
                        $price = $_POST['returnproprice' . $h . ''];
                        $discountValue = $_POST['returnprodis' . $h . ''];
                        $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
                        $comment = $_POST['returncomment' . $h . ''];
                        $returndiscounttype = $_POST['returndiscounttype' . $h . ''];
                        $reprstorid = $_POST['reprstorid' . $h . ''];
                        $scunitname = $_POST['returnscunitname' . $h . ''];
                        $retpricetypepro = $_POST['retpricetypepro' . $h . ''];
                        $proSerials = $_POST['proSerialsRet' . $h . ''];

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

                            $sellbillstoreId = $reprstorid;
                        } else {
                            $sellbillstoreId = $_POST['storeid'];
                            //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                        }
                        if ($productunitId == "") {
                            $productunitId = 0;
                        }

                        if (isset($productId) && $productId != '-1' && $productId != "") {
                            $productData = loadProductById($productId);

                            $mySellandruternbilldetail->buyprice = $productData->productBuyPrice;
                            $mySellandruternbilldetail->buyPricesHistoryBookIdQuantity = '';
                            $mySellandruternbilldetail->discountvalue = $discountValue;
                            $mySellandruternbilldetail->note = $comment;
                            $mySellandruternbilldetail->parcode = $parcode;
                            $mySellandruternbilldetail->pricetype = $priceType;
                            $mySellandruternbilldetail->productunitid = $productunitId;
                            $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                            $mySellandruternbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                            $mySellandruternbilldetail->sellbilldetailprice = $price;
                            $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                            $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                            $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                            $mySellandruternbilldetail->sellbillid = $sellbillId;
                            $mySellandruternbilldetail->selltype = 1; //مردودات
                            $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                            $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                            $mySellandruternbilldetail->storeid = $sellbillstoreId;
                            $mySellandruternbilldetail->discounttype = $returndiscounttype;
                            $mySellandruternbilldetail->otherdetailquantity = $scunitname;
                            $mySellandruternbilldetail->sizeid = $sizeId;
                            $mySellandruternbilldetail->colorid = $colorId;
                            $mySellandruternbilldetail->pricetypepro = $retpricetypepro;
                            $mySellandruternbilldetail->proHeight = $proHeight;
                            $mySellandruternbilldetail->proWidth = $proWidth;
                            $mySellandruternbilldetail->soldSerialsInDetails = $proSerials;
                            ##curr conversion
                            $mySellandruternbilldetail->sellbilldetailpriceC = $mySellandruternbilldetail->sellbilldetailprice;
                            $mySellandruternbilldetail->sellbilldetailtotalpriceC = $mySellandruternbilldetail->sellbilldetailtotalprice;
                            $mySellandruternbilldetail->discountvalueC = $mySellandruternbilldetail->discountvalue;
                            $mySellandruternbilldetail->proSellTrackingSerial = $_POST['retproSellTrackingSerial' . $h];
                            if ($currencyId > 1) {
                                $price = $price / $cFactor;
                                $totalPrice = $totalPrice / $cFactor;
                                $discountValue = $discountValue / $cFactor;

                                $mySellandruternbilldetail->sellbilldetailprice = $price;
                                $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                                $mySellandruternbilldetail->discountvalue = $discountValue;
                            }
                            $tempSaveBillIdRowRet = (int) filter_input(INPUT_POST, "tempSaveBillIdRowRet$h");
                            //                            if ($tempSaveBillId > 0 && $tempSaveBillIdRowRet > 0) {
                            //                                $detailId = $tempSaveBillIdRowRet;
                            //                                $mySellandruternbilldetail->sellbilldetailid = $tempSaveBillIdRowRet;
                            //                                $mySellandruternbilldetailRecord->update($mySellandruternbilldetail);
                            //                            } else {
                            $detailId = $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);
                            //                            }

                            $productnumber = (float) $_POST['retProNum' . $h];
                            if ($productnumber <= 0) {
                                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                                $productnumber = $productunitData->productnumber;
                            }
                            $finalquantity = $quantity * $productnumber;

                            //update DON if is Serial
                            if (!empty($proSerials)) {
                                increaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillId, $sellbillclientId, $detailId, 4, 'add');
                            } else if ($parcodeType == "serialnumber") {
                                //update don column (quantity) in productserial table
                                updateSerailQty_ForReturn($productserailId, $finalquantity);
                                insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 4, $sellbillclientId);
                            }

                            $isService = isService($productId);
                            if ($isService == 0) { //if product
                                //get storeto productquantity before change
                                $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                $allStoredetailData = $storedetailData[0];
                                $storedetailId = $storedetailData[1];
                                $productquantityBefore = $storedetailData[2];

                                if (count($allStoredetailData) > 0) {

                                    //update productquantity in storedetail
                                    $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                } else {
                                    //insert in storedetail tbl
                                    $strDtlIds = insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                }

                                //other unit
                                if ($scunitname > 0) {
                                    $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                    $allStoredetailDataother = $allStoredetailData2[0];
                                    $storeDetailIdother = $allStoredetailData2[1];
                                    $productQuantityBeforeother = $allStoredetailData2[2];

                                    if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                        //update productquantity in storedetail
                                        $finalquantityother = $productQuantityBeforeother + $scunitname;
                                        $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", date("Y-m-d H:i:s"), 1);
                                    } else {
                                        //insert in storedetail tbl
                                        if ($scunitname > 0) {
                                            $strDtlIds = insertStoredetailupdate2($sellbillstoreId, $productId, $scunitname, date("Y-m-d H:i:s"), 1);

                                            //insert in storereport
                                            insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, $scunitname, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", date("Y-m-d H:i:s"), 1);
                                        }
                                    }
                                }

                                if ($sizeId == 0 && $colorId == 0)
                                    $storeDetailIds[] = $storedetailId ? $storedetailId : $strDtlIds[0];
                                else
                                    $sizeColrDetailIds[] = $storeDetailIdother ? $storeDetailIdother : $strDtlIds[1];
                            }
                        }
                    }

                    //check if payed or not to change save value
                    if ($sellbilltotalPayed != 0) {
                        if ($sellbillAftertotalBill > 0) {

                            //get saveValue before and saveValue after Plus lPayed
                            $saveData = getSaveValueAndPlus($saveid, $sellbilltotalPayed, $saveConversionFactor);
                            $saveId = $saveData[0];
                            $saveValuebefore = $saveData[1];
                            $saveValueafter = $saveData[2];
                            ##curr conversion
                            $sellbilltotalPayedSaveCurr = $saveData[3];
                            $saveConversionFactor = $saveData[4];
                            if ($currencyId > 1 && $billCurrInsertId > 0) {
                                $sellBillAndRuternCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                            }

                            //update save value after add sellbill
                            updateSave($saveId, $saveValueafter);

                            //insert into savedaily tbl from save
                            $_SESSION['client_id'] = $sellbillclientId;
                            insertSavedailyupdate($saveValuebefore, $sellbilltotalPayedSaveCurr, 0, $saveId, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
                            unset($_SESSION['client_id']);
                        } else {
                            //get saveValue before and saveValue after Plus lPayed
                            // $saveData = getSaveValueAndMins($saveid, abs($sellbilltotalPayed), $saveConversionFactor);
                            $saveData = getSaveValueAndMins($saveid, abs($sellbilltotalPayed), $saveConversionFactor);
                            $saveId = $saveData[0];
                            $saveValuebefore = $saveData[1];
                            $saveValueafter = $saveData[2];
                            ##curr conversion
                            $sellbilltotalPayedSaveCurr = $saveData[3];
                            $saveConversionFactor = $saveData[4];
                            if ($currencyId > 1 && $billCurrInsertId > 0) {
                                $sellBillAndRuternCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                            }

                            //update save value after add sellbill
                            updateSave($saveId, $saveValueafter);

                            $specialSellbilltotalPayed = $sellbilltotalPayed * -1;

                            //insert into savedaily tbl from save
                            $_SESSION['client_id'] = $sellbillclientId;
                            insertSavedailyupdate($saveValuebefore, $sellbilltotalPayedSaveCurr, 1, $saveId, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
                            unset($_SESSION['client_id']);
                        }
                    }
                    if ($visa != 0 && $visaAccount > 0) {
                        if ($sellbillAftertotalBill > 0) {
                            $visaAccountData = $bankAccountDAO->load($visaAccount);
                            if ($isBankAccountTransfer == 1) {
                                $visaDisPerVal = 0;
                            } else {
                                $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                            }
                            $accountBefore = $visaAccountData->accountbeginingbalance;
                            $visaAccountData->accountbeginingbalance = $accountBefore + $visa - $visaDisPerVal;
                            $visaAccountData->accountdate = date('Y-m-d');
                            $visaAccountData->accountid = $visaAccount;
                            $bankAccountEX->updateacount($visaAccountData);

                            //Insert in accountmovement table the payment
                            $afterVal = $accountBefore + $visa;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 0, "سداد فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));

                            //Insert in accountmovement table the disount per
                            if ($isBankAccountTransfer != 1) {
                                $afterVal_AfterDisc = $afterVal - $visaDisPerVal;
                                insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 1, "نسبة خصم الفيزا من تحصيل فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));
                            }
                        } else {
                            $visaAccountData = $bankAccountDAO->load($visaAccount);
                            if ($isBankAccountTransfer == 1) {
                                $visaDisPerVal = 0;
                            } else {
                                $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                            }
                            $accountBefore = $visaAccountData->accountbeginingbalance;
                            $visaAccountData->accountbeginingbalance = $accountBefore - $visa + $visaDisPerVal;
                            $visaAccountData->accountdate = date('Y-m-d');
                            $visaAccountData->accountid = $visaAccount;
                            $bankAccountEX->updateacount($visaAccountData);

                            //Insert in accountmovement table the payment
                            $afterVal = $accountBefore - $visa;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 1, "سداد فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));

                            //Insert in accountmovement table the disount per
                            if ($isBankAccountTransfer != 1) {
                                $afterVal_AfterDisc = $afterVal + $visaDisPerVal;
                                insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 0, "نسبة خصم الفيزا من تحصيل فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));
                            }
                        }
                    }
                }

                //مبيعات
                //insert data into Sellbill tbl
                elseif (($sellbillPrice > 0 && $returnsellbillPrice <= 0) || $bill_is == 'sell') {
                    $billtype = 1; //مبيعات


                    $mySellbill->billnameid = $billnameId;
                    $mySellbill->conditions = 0;
                    $mySellbill->sellbildirectpayment = $sellbildirectPayment;
                    $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
                    $mySellbill->sellbillclientid = $sellbillclientId;
                    $mySellbill->sellbillclientname = $clientName;
                    $mySellbill->sellbilldate = $sellbillDate;
                    $mySellbill->sellbilldiscount = $sellbillDiscount;
                    $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
                    $mySellbill->sellbillfinalbill = $sellbillFinalbill;
                    $mySellbill->sellbillsaveid = $saveid;
                    $mySellbill->sellbillserial = $sellbillSerial;
                    $mySellbill->sellbillstoreid = $sellbillstoreId;
                    $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
                    $mySellbill->sellbilltotalbill = $sellbilltotalBill;
                    $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
                    $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                    $mySellbill->sellbilltotalpayed = $sellbilltotalPayed + $visa;
                    $mySellbill->sellerid = $sellerId;
                    $mySellbill->userid = $_SESSION['userid'];
                    $mySellbill->tempclientName = $tempClientName;
                    $mySellbill->sellQuantity = $sellQuantity;
                    $mySellbill->tax = $tax;
                    $mySellbill->carnumber = $sellbillcarnumber;
                    $mySellbill->cartype = $sellbillcartype;
                    $mySellbill->carchase = $sellbillcarchase;
                    $mySellbill->carmotor = $sellbillcarmotor;
                    $mySellbill->costcenterid = $Costcenterid;
                    $mySellbill->dailyentryid = 0;
                    $mySellbill->comment = $comment;
                    $mySellbill->delivery = $sellbilldelivery;
                    $mySellbill->totalafterdelivery = $totalaafterdelivery;
                    $mySellbill->billReservation = $billReservation;
                    $mySellbill->billReservationDate = $billReservationDate;
                    $mySellbill->cashPayed = $sellbilltotalPayed;
                    $mySellbill->visaPayed = $visa;
                    $mySellbill->visaAccountId = $visaAccount;
                    $mySellbill->isBankAccountTransfer = $isBankAccountTransfer;
                    $mySellbill->extraDiscountPer = $extraDiscountPer;
                    $mySellbill->extraDiscountVal = $extraDiscountVal;
                    $mySellbill->taxOfDiscountPer = $taxOfDiscountPer;
                    $mySellbill->taxOfDiscountVal = $taxOfDiscountVal;
                    $mySellbill->collectionType = $collectionType;
                    $mySellbill->collectionDate = $collectionDate;
                    $mySellbill->webApiId = (int) $_POST['webApiId'];
                    $mySellbill->taxBillNumber = 0;
                    $mySellbill->qrerpid = '';
                    $mySellbill->qrerpids = '';
                    $mySellbill->obgyBillType = (int) $_POST['obgyBillType'];
                    $mySellbill->billoperationid = (int) $_POST['billoperationid'];
                    $mySellbill->datestarting = $_POST['datestarting'];
                    $mySellbill->pricetype = $priceType;
                    $mySellbill->currencyId = $currencyId;
                    $mySellbill->knownwayId = $knownwayId;
                    $mySellbill->travelBusId = $travelBusId;
                    $mySellbill->travelDriverId = $travelDriverId;
                    $mySellbill->travelPathId = $travelPathId;
                    $mySellbill->travelTripId = $travelTripId;
                    $mySellbill->travelTripTypeId = $travelTripTypeId;
                    $mySellbill->totalprodiscount = $totalprodiscount;
                    $mySellbill->manage_ex = $manage_ex;
                    $mySellbill->med_hallmark = $med_hallmark;
                    $mySellbill->pay_rec_no = $pay_rec_no;
                    $mySellbill->pay_rec_val = $pay_rec_val;
                    $mySellbill->decisionNo = $decisionNo;
                    $mySellbill->decisionValue = $decisionValue;
                    $mySellbill->sellToSupplier = $sellToSupplier;
                    $mySellbill->whatShippingCost = $whatShippingCost;
                    $mySellbill->shipfrom = (int) $_POST['shipfrom'];
                    $mySellbill->shipto = (int) $_POST['shipto'];
                    $mySellbill->paymethodshipping = (int) $_POST['paymethodshipping'];
                    $mySellbill->sellbilltypeclientid = (int) $_POST['sellbilltypeclientid'];


                    if ($isTaxBill == 1 && $taxBillNumber > 0) {
                        //get fresh $taxBillNumber
                        $taxBillNumber = (int) $mySellbillEx->getNextTaxBillNumber($DBName) + 1;
                        $mySellbill->taxBillNumber = $taxBillNumber;
                    }
                    //by eng sherif as i get sellbillaftertotalbill = 0 when disount = 0
                    //i am stoping it as it is working and $mySellbill->sellbillaftertotalbill has many other parameters more than tax only
                    //                    if ($sellbillDiscount == 0) {
                    //                        $mySellbill->sellbillaftertotalbill = $mySellbill->sellbilltotalbill + ($mySellbill->sellbilltotalbill * ($tax / 100));
                    //                    }
                    if ($tempSaveBillId > 0) {
                        $sellbillId = $tempSaveBillId;
                        $mySellbill->sellbillid = $tempSaveBillId;
                        $mySellbillRecord->update($mySellbill);

                        //this will make details of auto save del all then insert =>it is faster "0.6 sec for 20products in bill" but lose indexes of table
                        //comment that line it would be update statments//but also uncomment code of update details
                        $mySellbilldetailRecord->deleteBySellbillid($tempSaveBillId);
                    } else {
                        $sellbillId = $mySellbillRecord->insert($mySellbill);
                    }
                    ##curr conversion
                    if ($currencyId > 1) {
                        $sellBillCurr->sellbillid = $sellbillId;
                        $sellBillCurr->conversionFactor = $cFactor;
                        $sellBillCurr->sellbilldiscountC = $sellbilldiscountC;
                        $sellBillCurr->sellbilltotalbillC = $sellbilltotalbillC;
                        $sellBillCurr->sellbillaftertotalbillC = $sellbillaftertotalbillC;
                        $sellBillCurr->sellbilltotalpayedC = $sellbilltotalpayedC;
                        $sellBillCurr->sellbillfinalbillC = $sellbillfinalbillC;
                        $sellBillCurr->sellbildirectpaymentC = 1;
                        $sellBillCurr->taxC = $taxC;
                        $sellBillCurr->deliveryC = $deliveryC;
                        $sellBillCurr->totalafterdeliveryC = $totalafterdeliveryC;
                        $sellBillCurr->cashPayedC = $cashPayedC;
                        $sellBillCurr->visaPayedC = $visaPayedC;
                        $sellBillCurr->extraDiscountValC = $extraDiscountValC;
                        $sellBillCurr->taxOfDiscountValC = $taxOfDiscountValC;
                        $sellBillCurr->saveConversionFactor = $saveConversionFactor;
                        $sellBillCurr->totalprodiscountC = $totalprodiscountC;
                        $billCurrInsertId = $sellBillCurrDAO->insert($sellBillCurr);
                    }


                    if ($offerId > 0) {
                        $sellBillOfferEX->updateOrderSavedBillId($sellbillId, $offerId);
                    }
                    //affect client debt first so that making two bills in same time dont corrupt debt
                    if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                        updatewebStoreType($sellbillclientId);
                        //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                        //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                        {

                            //update rawmaterialssupplierdebt
                            updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                            insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات", $sellbillId, $sellbilltotaldeptAfter, "sellbillController.php", "اضافة فاتورة مبيعات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, $sellbilltotalPayed);
                            markClientAsNOTInUse($sellbillclientId);
                        }
                    }

                    $Costcenterdetail->costamount = $sellbillAftertotalBill;
                    $Costcenterdetail->costcenterid = $Costcenterid;
                    $Costcenterdetail->costdate = date('Y-m-d');
                    $Costcenterdetail->del = 0;
                    $Costcenterdetail->modelid = $sellbillId;
                    $Costcenterdetail->processname = 'فاتوره مبيعات';
                    $Costcenterdetail->tablename = 'sellbillController.php';
                    $Costcenterdetail->type = '0';
                    $Costcenterdetail->uesrid = $_SESSION['userid'];

                    if ($Costcenterid != -1 && $Costcenterid != '-1') {
                        $CostcenterdetailDAO->insert($Costcenterdetail);
                    }

                    //insert Sell Data into Sellbilldetail tbl
                    $sellbillItr = $_POST['hidden_itr'];
                    $h = 1;
                    for ($h = 1; $h <= $sellbillItr; $h++) {
                        ## if input are encoded in json put it again in post
                        if (isset($_POST["obj" . $h])) {
                            foreach (json_decode(str_replace("'", '"', $_POST["obj" . $h]), true) as $key => $value) {
                                $_POST[$key . $h] = $value;
                            }
                        }
                        $parcode = $_POST['parcode' . $h . ''];
                        $taxesitr = $_POST['taxesitr_' . $h . ''];
                        $parcodeType = $_POST['parcodeType' . $h . ''];
                        $productserailId = $_POST['productserailid' . $h . ''];
                        $productId = $_POST['product' . $h . ''];
                        $sizeId = 0;
                        $colorId = 0;
                        $sizeColorStoreDetailId = 0;
                        if (strpos($productId, "hasSizeColor") !== false) {
                            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                            $productId = $productIdComplex[0];
                            $sizeId = $productIdComplex[1];
                            $colorId = $productIdComplex[2];
                            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                        }
                        $productunitId = $_POST['productunit' . $h . ''];
                        $proHeight = (float) $_POST['proHeight' . $h . ''];
                        $proWidth = (float) $_POST['proWidth' . $h . ''];
                        $quantity = $_POST['pronum' . $h . ''];
                        $price = $_POST['proprice' . $h . ''];
                        $catdis = $_POST['catdis' . $h . ''];
                        $discountValue = (float) $_POST['prodis' . $h . ''];
                        $totalPrice = $_POST['hidden_prototal' . $h . ''];
                        $comment = $_POST['comment' . $h . ''];
                        $prstorid = $_POST['prstorid' . $h . ''];
                        $discounttype = $_POST['discounttype' . $h . ''];
                        $scunitname = $_POST['scunitname' . $h . ''];
                        $pricetypepro = $_POST['pricetypepro' . $h . ''];
                        $proSerials = $_POST['proSerials' . $h . ''];
                        $playstationPlayId = (int) $_POST['playstationPlayId' . $h . ''];
                        $travelBrokerId = (int) $_POST['travelBrokerId' . $h . ''];

                        if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {

                            //print_r('in if prstorid'.$prstorid.'<br>');
                            $sellbillstoreId = $prstorid;
                        } else {
                            $sellbillstoreId = $_POST['storeid'];
                            //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                        }
                        if ($productunitId == "") {
                            $productunitId = 0;
                        }
                        //print_r('the final'.$sellbillstoreId.'<br>');
                        if (isset($productId) && $productId != '-1' && $productId != "") {

                            if ($firstProductId == 0) {
                                $firstProductId = $productId;
                            }

                            $productData = loadProductById($productId);
                            //
                            $productnumber = (float) $_POST['proNum' . $h];
                            if ($productnumber <= 0) {
                                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                                //print_r($productunitData);
                                $productnumber = $productunitData->productnumber;
                            }
                            $finalquantity = $quantity * $productnumber;
                            //
                            $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($sellbillstoreId, $productId, $sizeId, $colorId, $productData->productBuyPrice, $finalquantity, 0);
                            $theBuyPrice = $comingData[0];
                            $buyPricesHistoryBookIdQuantity = $comingData[1];
                            $mySellbilldetail->buyprice = $theBuyPrice; //$productData->productBuyPrice;
                            $mySellbilldetail->buyPricesHistoryBookIdQuantity = $buyPricesHistoryBookIdQuantity;

                            $mySellbilldetail->discountvalue = $discountValue;
                            $mySellbilldetail->note = $comment;
                            if ($Programsettingdata->sendBillToRestaurant == 1) {
                                $mySellbilldetail->note = $_POST['hiddenNotes' . $h];
                            }
                            $mySellbilldetail->parcode = $parcode;
                            $mySellbilldetail->pricetype = $priceType;
                            $mySellbilldetail->productunitid = $productunitId;
                            $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                            $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                            $mySellbilldetail->sellbilldetailprice = $price;
                            $mySellbilldetail->sellbilldetailproductid = $productId;
                            $mySellbilldetail->sellbilldetailquantity = $quantity;
                            $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                            $mySellbilldetail->sellbillid = $sellbillId;
                            $mySellbilldetail->buydiscount = $productData->buydiscount;
                            $mySellbilldetail->buydiscounttype = $productData->discounttype;
                            $mySellbilldetail->storeid = $sellbillstoreId;
                            $mySellbilldetail->discounttype = $discounttype;
                            $mySellbilldetail->otherdetailquantity = $scunitname;
                            $mySellbilldetail->sizeid = $sizeId;
                            $mySellbilldetail->colorid = $colorId;
                            $mySellbilldetail->pricetypepro = $pricetypepro;
                            $mySellbilldetail->playstationPlayId = $playstationPlayId;
                            $mySellbilldetail->proHeight = $proHeight;
                            $mySellbilldetail->proWidth = $proWidth;
                            $mySellbilldetail->soldSerialsInDetails = $proSerials;
                            $mySellbilldetail->travelBrokerId = $travelBrokerId;
                            $mySellbilldetail->categorydiscount = $catdis;

                            ##curr conversion
                            $mySellbilldetail->sellbilldetailpriceC = $mySellbilldetail->sellbilldetailprice;
                            $mySellbilldetail->sellbilldetailtotalpriceC = $mySellbilldetail->sellbilldetailtotalprice;
                            $mySellbilldetail->discountvalueC = $mySellbilldetail->discountvalue;
                            $mySellbilldetail->prosellDiscountPer = (float) $_POST['prosellDiscountPer' . $h];
                            $mySellbilldetail->prosellDiscountPerType = (int) $_POST['prosellDiscountPerType' . $h];
                            $mySellbilldetail->prosellDiscountVal = (float) $_POST['prosellDiscountVal' . $h];
                            $mySellbilldetail->proSellTrackingSerial = $_POST['proSellTrackingSerial' . $h];
                            if ($currencyId > 1) {
                                $price = $price / $cFactor;
                                $totalPrice = $totalPrice / $cFactor;
                                $discountValue = $discountValue / $cFactor;

                                $mySellbilldetail->sellbilldetailprice = $price;
                                $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                                $mySellbilldetail->discountvalue = $discountValue;
                            }
                            ##################################

                            $tempSaveBillIdRow = (int) filter_input(INPUT_POST, "tempSaveBillIdRow$h");
                            //                            if ($tempSaveBillId > 0 && $tempSaveBillIdRow > 0) {
                            //                                $detailId = $tempSaveBillIdRow;
                            //                                $mySellbilldetail->sellbilldetailid = $tempSaveBillIdRow;
                            //                                $mySellbilldetailRecord->update($mySellbilldetail);
                            //                            } else {
                            $detailId = $mySellbilldetailRecord->insert($mySellbilldetail);

                            $e = 1;

                            for ($e = 1; $e <= $taxesitr; $e++) {
                                if (!$_POST['type_' . $h . '_' . $e]) {
                                    continue;
                                }

                                $sellbilldetailtax = R::dispense('sellbilldetailtax');
                                $sellbilldetailtax->sellbilldetailid = $detailId;
                                $sellbilldetailtax->conditions = 0;
                                $sellbilldetailtax->type = $_POST['type_' . $h . '_' . $e];
                                $sellbilldetailtax->subtype = $_POST['subtype_' . $h . '_' . $e];
                                $sellbilldetailtax->rate = $_POST['rate_' . $h . '_' . $e];
                                $sellbilldetailtax->amount = $_POST['amount_' . $h . '_' . $e];
                                R::store($sellbilldetailtax);
                            }
                            //                            }
                            //update DON if is Serial
                            if (!empty($proSerials)) {
                                decreaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillId, $sellbillclientId, $detailId, 0, 'add');
                            } else if ($parcodeType == "serialnumber") {
                                //print("<br>serialnumber<br>");
                                //updateSerailDon($productserailId, 1, $sellbillId);
                                updateSerailQty($productserailId, $finalquantity);
                                insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 0, $sellbillclientId);
                            }

                            $isService = isService($productId);
                            if ($isService == 0) { //if product
                                //get store productquantity before change
                                $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                $allStoredetailData = $storedetailData[0];
                                $storedetailId = $storedetailData[1];
                                $productquantityBefore = $storedetailData[2];

                                //print("qty: ".$finalquantity.'<br>');
                                if (count($allStoredetailData) > 0) {

                                    //update productquantity in storedetail
                                    $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                } else {
                                    $specialQuantityAfter = $finalquantity * -1;

                                    //insert in storedetail tbl
                                    $strDtlIds = insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                }

                                //other unit
                                if ($scunitname > 0) {
                                    $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                    $allStoredetailDataother = $allStoredetailData2[0];
                                    $storeDetailIdother = $allStoredetailData2[1];
                                    $productQuantityBeforeother = $allStoredetailData2[2];

                                    if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                        //update productquantity in storedetail
                                        $finalquantityother = $productQuantityBeforeother - $scunitname;
                                        $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                    } else {
                                        //insert in storedetail tbl
                                        if ($scunitname > 0) {
                                            $strDtlIds = insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname) * -1, date("Y-m-d H:i:s"), 1);

                                            //insert in storereport
                                            insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname) * -1, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                        }
                                    }
                                }

                                if ($sizeId == 0 && $colorId == 0)
                                    $storeDetailIds[] = $storedetailId ? $storedetailId : $strDtlIds[0];
                                else
                                    $sizeColrDetailIds[] = $storeDetailIdother ? $storeDetailIdother : $strDtlIds[1];
                            }
                        }
                    }


                    //check if payed or not to change save value
                    if ($sellbilltotalPayed > 0) {
                        //get saveValue before and saveValue after Plus lPayed
                        $saveData = getSaveValueAndPlus($saveid, $sellbilltotalPayed, $saveConversionFactor);
                        $saveId = $saveData[0];
                        $saveValuebefore = $saveData[1];
                        $saveValueafter = $saveData[2];
                        ##curr conversion
                        $sellbilltotalPayedSaveCurr = $saveData[3];
                        $saveConversionFactor = $saveData[4];
                        if ($currencyId > 1 && $billCurrInsertId > 0) {
                            $sellBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                        }

                        //update save value after add sellbill
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl from save
                        $_SESSION['client_id'] = $sellbillclientId;
                        insertSavedailyupdate($saveValuebefore, $sellbilltotalPayedSaveCurr, 0, $saveId, "اضافة فاتورة مبيعات", $sellbillId, $saveValueafter, "sellbillController.php", date("Y-m-d H:i:s"));
                        unset($_SESSION['client_id']);
                    }
                    if ($visa != 0 && $visaAccount > 0) {
                        $visaAccountData = $bankAccountDAO->load($visaAccount);
                        if ($isBankAccountTransfer == 1) {
                            $visaDisPerVal = 0;
                        } else {
                            $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                        }
                        $accountBefore = $visaAccountData->accountbeginingbalance;
                        $visaAccountData->accountbeginingbalance = $accountBefore + $visa - $visaDisPerVal;
                        $visaAccountData->accountdate = date('Y-m-d');
                        $visaAccountData->accountid = $visaAccount;
                        $bankAccountEX->updateacount($visaAccountData);

                        //Insert in accountmovement table the payment
                        $afterVal = $accountBefore + $visa;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 0, "سداد فاتورة", "sellbillController.php", $sellbillId, date('Y-m-d H:i:s'));

                        //Insert in accountmovement table the disount per
                        if ($isBankAccountTransfer != 1) {
                            $afterVal_AfterDisc = $afterVal - $visaDisPerVal;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 1, "نسبة خصم الفيزا من تحصيل فاتورة", "sellbillController.php", $sellbillId, date('Y-m-d H:i:s'));
                        }
                    }


                    if ($Programsettingdata->sendBillToRestaurant == 1) {
                        printKitchenFromSellBill($sellbillId);
                    }

                    //Add Status
                    $billStatus = R::dispense("sellbillstatus");
                    $billStatus->sellbillid = $sellbillId;
                    $billStatus->status = "new";
                    $billStatus->userid = $_SESSION['userid'];
                    $billStatus->sysdate = date('Y-m-d H:i:s');
                    $billStatusId = R::store($billStatus);
                }

                //مردودات مبيعات
                //insert data into returnSellbill tbl
                elseif (($sellbillPrice <= 0 && $returnsellbillPrice > 0) || $bill_is == 'ret') {
                    $billtype = 2; //مردودات مبيعات


                    $sellbillFinalbill = $sellbillAftertotalBill + abs($sellbilltotalPayed) + abs($visa);
                    $gen4totalinput = $sellbillAftertotalBill + abs($sellbilltotalPayed) + abs($visa);
                    $sellbilltotaldeptAfter = $sellbilltotaldeptBefor - ($gen4totalinput * -1);

                    $myReturnsellbill->billnameid = $billnameId;
                    $myReturnsellbill->conditions = 0;
                    $myReturnsellbill->returnsellbildirectpayment = $sellbildirectPayment;
                    $myReturnsellbill->returnsellbillaftertotalbill = $sellbillAftertotalBill * -1;
                    $myReturnsellbill->returnsellbillclientid = $sellbillclientId;
                    $myReturnsellbill->returnsellbillclientname = $clientName;
                    $myReturnsellbill->returnsellbilldate = $sellbillDate;
                    $myReturnsellbill->returnsellbilldiscount = $sellbillDiscount;
                    $myReturnsellbill->returnsellbilldiscounttype = $sellbillDiscountType;
                    $myReturnsellbill->returnsellbillfinalbill = $sellbillFinalbill;
                    $myReturnsellbill->returnsellbillsaveid = $saveid;
                    $myReturnsellbill->returnsellbillserial = $sellbillSerial;
                    $myReturnsellbill->returnsellbillstoreid = $sellbillstoreId;
                    $myReturnsellbill->returnsellbillsysdate = date("Y-m-d H:i:s");
                    $myReturnsellbill->returnsellbilltotalbill = $sellbilltotalBill * -1;
                    $myReturnsellbill->returnsellbilltotaldeptafter = $sellbilltotaldeptAfter;
                    $myReturnsellbill->returnsellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                    $myReturnsellbill->returnsellbilltotalpayed = $sellbilltotalPayed + $visa;
                    $myReturnsellbill->sellerid = $sellerId;
                    $myReturnsellbill->userid = $_SESSION['userid'];
                    $myReturnsellbill->tempclientName = $tempClientName;
                    $myReturnsellbill->returnsellQuantity = $returnsellQuantity;
                    $myReturnsellbill->tax = $tax;
                    $myReturnsellbill->carnumber = $sellbillcarnumber;
                    $myReturnsellbill->cartype = $sellbillcartype;
                    $myReturnsellbill->carchase = $sellbillcarchase;
                    $myReturnsellbill->carmotor = $sellbillcarmotor;
                    $myReturnsellbill->costcenterid = $Costcenterid;
                    $myReturnsellbill->dailyentryid = 0;
                    $myReturnsellbill->comment = $comment;
                    $myReturnsellbill->billReservation = $billReservation;
                    $myReturnsellbill->billReservationDate = $billReservationDate;
                    $myReturnsellbill->cashPayed = $sellbilltotalPayed;
                    $myReturnsellbill->visaPayed = $visa;
                    $myReturnsellbill->visaAccountId = $visaAccount;
                    $myReturnsellbill->isBankAccountTransfer = $isBankAccountTransfer;
                    $myReturnsellbill->extraDiscountPer = $extraDiscountPer;
                    $myReturnsellbill->extraDiscountVal = $extraDiscountVal;
                    $myReturnsellbill->taxOfDiscountPer = $taxOfDiscountPer;
                    $myReturnsellbill->taxOfDiscountVal = $taxOfDiscountVal;
                    $myReturnsellbill->obgyBillType = (int) $_POST['obgyBillType'];
                    $myReturnsellbill->billoperationid = (int) $_POST['billoperationid'];
                    $myReturnsellbill->pricetype = $priceType;
                    $myReturnsellbill->currencyId = $currencyId;
                    $myReturnsellbill->sellbillno = $sellbillno;
                    $myReturnsellbill->returnsellbilltypeclientid = (int) $_POST['sellbilltypeclientid'];

                    if ($tempSaveBillId > 0) {
                        $sellbillId = $returnsellbillId = $tempSaveBillId;
                        $myReturnsellbill->returnsellbillid = $tempSaveBillId;
                        $myReturnsellbillRecord->update($myReturnsellbill);

                        //this will make details of auto save del all then insert =>it is faster "0.6 sec for 20products in bill" but lose indexes of table
                        //comment that line it would be update statments//but also uncomment code of update details
                        $myReturnsellbilldetailRecord->deleteByReturnsellbillid($tempSaveBillId);
                    } else {
                        $sellbillId = $returnsellbillId = $myReturnsellbillRecord->insert($myReturnsellbill);
                    }

                    ##curr conversion
                    if ($currencyId > 1) {
                        $returnSellBillCurr->returnsellbillid = $sellbillId;
                        $returnSellBillCurr->conversionFactor = $cFactor;
                        $returnSellBillCurr->returnsellbilldiscountC = $sellbilldiscountC;
                        $returnSellBillCurr->returnsellbilltotalbillC = $sellbilltotalbillC;
                        $returnSellBillCurr->returnsellbillaftertotalbillC = $sellbillaftertotalbillC;
                        $returnSellBillCurr->returnsellbilltotalpayedC = $sellbilltotalpayedC;
                        $returnSellBillCurr->returnsellbillfinalbillC = $sellbillfinalbillC;
                        $returnSellBillCurr->returnsellbildirectpaymentC = 1;
                        $returnSellBillCurr->taxC = $taxC;
                        //                        $returnSellBillCurr->deliveryC = $deliveryC;
                        //                        $returnSellBillCurr->totalafterdeliveryC = $totalafterdeliveryC;
                        $returnSellBillCurr->cashPayedC = $cashPayedC;
                        $returnSellBillCurr->visaPayedC = $visaPayedC;
                        $returnSellBillCurr->extraDiscountValC = $extraDiscountValC;
                        $returnSellBillCurr->taxOfDiscountValC = $taxOfDiscountValC;
                        $returnSellBillCurr->saveConversionFactor = $saveConversionFactor;
                        $billCurrInsertId = $returnSellBillCurrDAO->insert($returnSellBillCurr);
                    }

                    //affect client debt first so that making two bills in same time dont corrupt debt
                    if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                        //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                        //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                        {

                            //update rawmaterialssupplierdebt
                            if ($sellbillclientId == 1) {

                            } else {

                            }
                            updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                            insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, abs($sellbillFinalbill), 1, "اضافة فاتورة مردوات مبيعات", $returnsellbillId, $sellbilltotaldeptAfter, "returnsellbillController.php", "اضافة فاتورة مردوات مبيعات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, $sellbilltotalPayed);
                            markClientAsNOTInUse($sellbillclientId);
                        }
                    }

                    $Costcenterdetail->costamount = $sellbillAftertotalBill;
                    $Costcenterdetail->costcenterid = $Costcenterid;
                    $Costcenterdetail->costdate = date('Y-m-d');
                    $Costcenterdetail->del = 0;
                    $Costcenterdetail->modelid = $returnsellbillId;
                    $Costcenterdetail->processname = 'فاتوره مردودات مبيعات';
                    $Costcenterdetail->tablename = 'returnsellbillController.php';
                    $Costcenterdetail->type = 1;
                    $Costcenterdetail->uesrid = $_SESSION['userid'];

                    if ($Costcenterid != -1 && $Costcenterid != '-1') {
                        $CostcenterdetailDAO->insert($Costcenterdetail);
                    }

                    //insert Return Data into returnsellbilldetail tbl
                    $returnSellbillItr = $_POST['returnhidden_itr'];
                    $h = 1;
                    for ($h = 1; $h <= $returnSellbillItr; $h++) {
                        ## if input are encoded in json put it again in post
                        if (isset($_POST["objRet" . $h])) {
                            foreach (json_decode(str_replace("'", '"', $_POST["objRet" . $h]), true) as $key => $value) {
                                $_POST[$key . $h] = $value;
                            }
                        }
                        $parcode = $_POST['returnparcode' . $h . ''];
                        $parcodeType = $_POST['returnparcodeType' . $h . ''];
                        $productserailId = $_POST['returnproductserailid' . $h . ''];
                        $productId = $_POST['returnproduct' . $h . ''];
                        $sizeId = 0;
                        $colorId = 0;
                        $sizeColorStoreDetailId = 0;
                        if (strpos($productId, "hasSizeColor") !== false) {
                            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                            $productId = $productIdComplex[0];
                            $sizeId = $productIdComplex[1];
                            $colorId = $productIdComplex[2];
                            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                        }
                        $productunitId = (int) $_POST['returnproductunit' . $h . ''];
                        $proHeight = (float) $_POST['returnproHeight' . $h . ''];
                        $proWidth = (float) $_POST['returnproWidth' . $h . ''];
                        $quantity = $_POST['returnpronum' . $h . ''];
                        $price = $_POST['returnproprice' . $h . ''];
                        $discountValue = $_POST['returnprodis' . $h . ''];
                        $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
                        $comment = $_POST['returncomment' . $h . ''];
                        $returndiscounttype = $_POST['returndiscounttype' . $h . ''];
                        $scunitname = $_POST['returnscunitname' . $h . ''];
                        $retpricetypepro = $_POST['retpricetypepro' . $h . ''];
                        $proSerials = $_POST['proSerialsRet' . $h . ''];

                        $reprstorid = $_POST['reprstorid' . $h . ''];
                        if (isset($reprstorid) && $reprstorid != -1 && $reprstorid != '') {

                            $sellbillstoreId = $reprstorid;
                        } else {
                            $sellbillstoreId = $_POST['storeid'];
                            //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                        }


                        if (isset($productId) && $productId != '-1' && $productId != "") {
                            if ($firstProductId == 0) {
                                $firstProductId = $productId;
                            }
                            if (empty($productunitId) || $productunitId == -1) {
                                //$productunitId = 0;
                                $productunitId = getfirstunittWithProductNumberEQ1($productId);
                            }

                            $productData = loadProductById($productId);
                            //                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                            $myReturnsellbilldetail->buyprice = $productData->productBuyPrice;
                            $myReturnsellbilldetail->conditions = 0;
                            $myReturnsellbilldetail->discountvalue = $discountValue;
                            $myReturnsellbilldetail->note = $comment;
                            $myReturnsellbilldetail->parcode = $parcode;
                            $myReturnsellbilldetail->pricetype = $priceType;
                            $myReturnsellbilldetail->productunitid = $productunitId;
                            $myReturnsellbilldetail->returnsellbilldetailcatid = $productData->productCatId;
                            $myReturnsellbilldetail->returnsellbilldetailprice = $price;
                            $myReturnsellbilldetail->returnsellbilldetailproductid = $productId;
                            $myReturnsellbilldetail->returnsellbilldetailquantity = $quantity;
                            $myReturnsellbilldetail->returnsellbilldetailtotalprice = $totalPrice;
                            $myReturnsellbilldetail->returnsellbillid = $returnsellbillId;
                            $myReturnsellbilldetail->buydiscount = $productData->buydiscount;
                            $myReturnsellbilldetail->buydiscounttype = $productData->discounttype;
                            $myReturnsellbilldetail->storeid = $sellbillstoreId;
                            $myReturnsellbilldetail->discounttype = $returndiscounttype;
                            $myReturnsellbilldetail->otherdetailquantity = $scunitname;
                            $myReturnsellbilldetail->sizeid = $sizeId;
                            $myReturnsellbilldetail->colorid = $colorId;
                            $myReturnsellbilldetail->pricetypepro = $retpricetypepro;
                            $myReturnsellbilldetail->proHeight = $proHeight;
                            $myReturnsellbilldetail->proWidth = $proWidth;
                            $myReturnsellbilldetail->soldSerialsInDetails = $proSerials;
                            ##curr conversion
                            $myReturnsellbilldetail->returnsellbilldetailpriceC = $myReturnsellbilldetail->returnsellbilldetailprice;
                            $myReturnsellbilldetail->returnsellbilldetailtotalpriceC = $myReturnsellbilldetail->returnsellbilldetailtotalprice;
                            $myReturnsellbilldetail->discountvalueC = $myReturnsellbilldetail->discountvalue;
                            $myReturnsellbilldetail->proSellTrackingSerial = $_POST['retproSellTrackingSerial' . $h];
                            if ($currencyId > 1) {
                                $price = $price / $cFactor;
                                $totalPrice = $totalPrice / $cFactor;
                                $discountValue = $discountValue / $cFactor;

                                $myReturnsellbilldetail->returnsellbilldetailprice = $price;
                                $myReturnsellbilldetail->returnsellbilldetailtotalprice = $totalPrice;
                                $myReturnsellbilldetail->discountvalue = $discountValue;
                            }
                            ##################################

                            $tempSaveBillIdRowRet = (int) filter_input(INPUT_POST, "tempSaveBillIdRowRet$h");
                            //                            if ($tempSaveBillId > 0 && $tempSaveBillIdRowRet > 0) {
                            //                                $detailId = $tempSaveBillIdRowRet;
                            //                                $myReturnsellbilldetail->returnsellbilldetailid = $tempSaveBillIdRowRet;
                            //                                $myReturnsellbilldetailRecord->update($myReturnsellbilldetail);
                            //                            } else {
                            $detailId = $myReturnsellbilldetailRecord->insert($myReturnsellbilldetail);
                            //                            }

                            $productnumber = (float) $_POST['retProNum' . $h];
                            if ($productnumber <= 0) {
                                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                                $productnumber = $productunitData->productnumber;
                            }
                            $finalquantity = $quantity * $productnumber;

                            //update DON if is Serial
                            if (!empty($proSerials)) {
                                increaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $returnsellbillId, $sellbillclientId, $detailId, 3, 'add');
                            } else if ($parcodeType == "serialnumber") {
                                //updateSerailDon($productserailId, 0, 0);
                                updateSerailQty_ForReturn($productserailId, $finalquantity);
                                insertIntoSoldSerialProduct($productserailId, $finalquantity, $returnsellbillId, 3, $sellbillclientId);
                            }

                            $isService = isService($productId);
                            if ($isService == 0) { //if product
                                //get storeto productquantity before change
                                $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                $allStoredetailData = $storedetailData[0];
                                $storedetailId = $storedetailData[1];
                                $productquantityBefore = $storedetailData[2];

                                if (count($allStoredetailData) > 0) {

                                    //update productquantity in storedetail
                                    $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "returnsellbilldetailid", $detailId, $productId, "returnsellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات", "returnsellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                } else {
                                    //insert in storedetail tbl
                                    insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, date("Y-m-d H:i:s"), "returnsellbilldetailid", $detailId, $productId, "returnsellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات", "returnsellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                }

                                //other unit
                                if ($scunitname > 0) {
                                    $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                    $allStoredetailDataother = $allStoredetailData2[0];
                                    $storeDetailIdother = $allStoredetailData2[1];
                                    $productQuantityBeforeother = $allStoredetailData2[2];

                                    if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                        //update productquantity in storedetail
                                        $finalquantityother = $productQuantityBeforeother + $scunitname;
                                        $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات ", "returnsellbillController.php", date("Y-m-d H:i:s"), 1);
                                    } else {
                                        //insert in storedetail tbl
                                        if ($scunitname > 0) {
                                            insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname), date("Y-m-d H:i:s"), 1);

                                            //insert in storereport
                                            insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname), 0, $returnsellbillId, "اضافة فاتورة مردودات ", "returnsellbillController.php", date("Y-m-d H:i:s"), 1);
                                        }
                                    }
                                }

                                if ($sizeId == 0 && $colorId == 0)
                                    $storeDetailIds[] = $storedetailId ? $storedetailId : $strDtlIds[0];
                                else
                                    $sizeColrDetailIds[] = $storeDetailIdother ? $storeDetailIdother : $strDtlIds[1];
                            }
                        }
                    }

                    //check if payed or not to change save value
                    if ($sellbilltotalPayed != 0) {

                        //get saveValue before and saveValue after mins sellbilltotalPayed
                        $saveData = getSaveValueAndMins($saveid, abs($sellbilltotalPayed), $saveConversionFactor);
                        $saveId = $saveData[0];
                        $saveValuebefore = $saveData[1];
                        $saveValueafter = $saveData[2];
                        ##curr conversion
                        $sellbilltotalPayedSaveCurr = $saveData[3];
                        $saveConversionFactor = $saveData[4];
                        if ($currencyId > 1 && $billCurrInsertId > 0) {
                            $returnSellBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                        }

                        //update saveFrom value after add transfer
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl from savefrom
                        $specialSellbilltotalPayed = $sellbilltotalPayedSaveCurr * -1;
                        $_SESSION['client_id'] = $sellbillclientId;
                        insertSavedailyupdate($saveValuebefore, $specialSellbilltotalPayed, 1, $saveId, "اضافة فاتورة مردوات مبيعات", $returnsellbillId, $saveValueafter, "returnsellbillController.php", date("Y-m-d H:i:s"));
                        unset($_SESSION['client_id']);
                    }
                    if ($visa != 0 && $visaAccount > 0) {
                        $visaAccountData = $bankAccountDAO->load($visaAccount);
                        if ($isBankAccountTransfer == 1) {
                            $visaDisPerVal = 0;
                        } else {
                            $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                        }
                        $accountBefore = $visaAccountData->accountbeginingbalance;
                        $visaAccountData->accountbeginingbalance = $accountBefore - $visa + $visaDisPerVal;
                        $visaAccountData->accountdate = date('Y-m-d');
                        $visaAccountData->accountid = $visaAccount;
                        $bankAccountEX->updateacount($visaAccountData);

                        //Insert in accountmovement table the payment
                        $afterVal = $accountBefore - $visa;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 1, "سداد فاتورة", "returnsellbillController.php", $sellbillId, date('Y-m-d H:i:s'));

                        //Insert in accountmovement table the disount per
                        if ($isBankAccountTransfer != 1) {
                            $afterVal_AfterDisc = $afterVal + $visaDisPerVal;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 0, "نسبة خصم الفيزا من تحصيل فاتورة", "returnsellbillController.php", $sellbillId, date('Y-m-d H:i:s'));
                        }
                    }
                }

                if ($sellerId > 0) {
                    $clientEX->updateClientDelegateid($sellbillclientId, $sellerId);
                }
            }

            /* ---------------------------------------------------------------------------------------------------------- */

            /* ---------------------------------------------------- بداية القيود اليومية ------------------------------------------------------ */
            doBillDailyEntry($billtype, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $saveid, $visa, $visaAccount, $gen4totalinput, $clientdata->treeId, $taxOfDiscountVal, $billDiscountVal, $sellbilltotalBill, $sellbillAftertotalBill, $taxVal, $sellCostsArray, $sellbillstoreId, $firstProductId, (int) $_POST['billoperationid']);
            writePaymentToRoyalFinancialReport($sellbillclientId, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $visa, $saveId, $bankAccountId, (int) $_POST['obgyBillType'], $billtype, 'add');



            quickProfitBill($sellbillPrice, $returnsellbillPrice, $billDiscountVal, $sellbillclientId, 1);
        } elseif ($ordertype == 1) { //its an offer not bill
            $billtype = 1; //مبيعات


            $mySellbill->billnameid = $billnameId;
            $mySellbill->conditions = 0;
            $mySellbill->sellbildirectpayment = $sellbildirectPayment;
            $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
            $mySellbill->sellbillclientid = $sellbillclientId;
            $mySellbill->sellbillclientname = $clientName;
            $mySellbill->sellbilldate = $sellbillDate;
            $mySellbill->sellbilldiscount = $sellbillDiscount;
            $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
            $mySellbill->sellbillfinalbill = $sellbillFinalbill;
            $mySellbill->sellbillsaveid = $saveid;
            $mySellbill->sellbillserial = $sellbillSerial;
            $mySellbill->sellbillstoreid = $sellbillstoreId;
            $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
            $mySellbill->sellbilltotalbill = $sellbilltotalBill;
            $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
            $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
            $mySellbill->sellbilltotalpayed = $sellbilltotalPayed + $visa;
            $mySellbill->sellerid = $sellerId;
            $mySellbill->userid = $_SESSION['userid'];
            $mySellbill->tempclientName = $tempClientName;
            $mySellbill->sellQuantity = $sellQuantity;
            $mySellbill->tax = $tax;
            $mySellbill->carnumber = $sellbillcarnumber;
            $mySellbill->cartype = $sellbillcartype;
            $mySellbill->carchase = $sellbillcarchase;
            $mySellbill->carmotor = $sellbillcarmotor;
            $mySellbill->costcenterid = $Costcenterid;
            $mySellbill->dailyentryid = 0;
            $mySellbill->comment = $comment;
            $mySellbill->delivery = $sellbilldelivery;
            $mySellbill->totalafterdelivery = $totalaafterdelivery;
            $mySellbill->billReservation = $billReservation;
            $mySellbill->billReservationDate = $billReservationDate;
            $mySellbill->cashPayed = $sellbilltotalPayed;
            $mySellbill->visaPayed = $visa;
            $mySellbill->visaAccountId = $visaAccount;
            $mySellbill->isBankAccountTransfer = $isBankAccountTransfer;
            $mySellbill->extraDiscountPer = $extraDiscountPer;
            $mySellbill->extraDiscountVal = $extraDiscountVal;
            $mySellbill->taxOfDiscountPer = $taxOfDiscountPer;
            $mySellbill->taxOfDiscountVal = $taxOfDiscountVal;
            $mySellbill->collectionType = $collectionType;
            $mySellbill->collectionDate = $collectionDate;
            $mySellbill->webApiId = (int) $_POST['webApiId'];
            $mySellbill->taxBillNumber = 0;
            $mySellbill->qrerpid = '';
            $mySellbill->qrerpids = '';
            $mySellbill->obgyBillType = (int) $_POST['obgyBillType'];
            $mySellbill->billoperationid = (int) $_POST['billoperationid'];
            $mySellbill->datestarting = $_POST['datestarting'];
            $mySellbill->pricetype = $priceType;
            $mySellbill->totalprodiscount = $totalprodiscount;
            $mySellbill->manage_ex = $manage_ex;
            $mySellbill->med_hallmark = $med_hallmark;
            $mySellbill->pay_rec_no = $pay_rec_no;
            $mySellbill->pay_rec_val = $pay_rec_val;
            $mySellbill->decisionNo = $decisionNo;
            $mySellbill->decisionValue = $decisionValue;
            if ($isTaxBill == 1 && $taxBillNumber > 0) {
                //get fresh $taxBillNumber
                $taxBillNumber = (int) $mySellbillEx->getNextTaxBillNumber($DBName) + 1;
                $mySellbill->taxBillNumber = $taxBillNumber;
            }
            //by eng sherif as i get sellbillaftertotalbill = 0 when disount = 0
            //i am stoping it as it is working and $mySellbill->sellbillaftertotalbill has many other parameters more than tax only
            //                    if ($sellbillDiscount == 0) {
            //                        $mySellbill->sellbillaftertotalbill = $mySellbill->sellbilltotalbill + ($mySellbill->sellbilltotalbill * ($tax / 100));
            //                    }
            $mySellbill->deletedsellid = 0;
            $mySellbill->controlname = $controlname;
            $mySellbill->obygyVisitId = 0;
            $mySellbill->costcenterid = 0;
            $mySellbill->comment = $comment;
            $mySellbill->conditions = 0;
            $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
            $mySellbill->userid = $_SESSION['userid'];
            $mySellbill->delbyuserid = 0;
            $mySellbill->lastReviewType = 0;
            $mySellbill->billReservation = $billReservation;
            $mySellbill->billReservationDate = $billReservationDate;
            $sellbillId = $sellBillOfferDAO->insert($mySellbill);

            $detailsArr = array();
            //insert Sell Data into Sellbilldetail tbl
            $sellbillItr = $_POST['hidden_itr'];
            $h = 1;
            for ($h = 1; $h <= $sellbillItr; $h++) {
                ## if input are encoded in json put it again in post
                if (isset($_POST["obj" . $h])) {
                    foreach (json_decode(str_replace("'", '"', $_POST["obj" . $h]), true) as $key => $value) {
                        $_POST[$key . $h] = $value;
                    }
                }
                $parcode = $_POST['parcode' . $h . ''];
                $parcodeType = $_POST['parcodeType' . $h . ''];
                $productserailId = $_POST['productserailid' . $h . ''];
                $productId = $_POST['product' . $h . ''];
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                }
                $productunitId = $_POST['productunit' . $h . ''];
                $quantity = $_POST['pronum' . $h . ''];
                $price = $_POST['proprice' . $h . ''];
                $catdis = $_POST['catdis' . $h . ''];
                $discountValue = $_POST['prodis' . $h . ''];
                $totalPrice = $_POST['hidden_prototal' . $h . ''];
                $comment = $_POST['comment' . $h . ''];
                $prstorid = $_POST['prstorid' . $h . ''];
                $discounttype = $_POST['discounttype' . $h . ''];
                $scunitname = $_POST['scunitname' . $h . ''];
                $pricetypepro = $_POST['pricetypepro' . $h . ''];

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

                    //print_r('in if prstorid'.$prstorid.'<br>');
                    $sellbillstoreId = $prstorid;
                } else {
                    $sellbillstoreId = $_POST['storeid'];
                    //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                }
                if ($productunitId == "") {
                    $productunitId = 0;
                }
                //print_r('the final'.$sellbillstoreId.'<br>');
                if (isset($productId) && $productId != '-1' && $productId != "") {
                    $productData = loadProductById($productId);

                    // $mySellbilldetail->buyprice = $productData->productBuyPrice;
                    $mySellbilldetail->buyprice = $productData->productBuyPrice;

                    $mySellbilldetail->discountvalue = $discountValue;
                    $mySellbilldetail->note = $comment;
                    $mySellbilldetail->parcode = $parcode;
                    $mySellbilldetail->pricetype = $priceType;
                    $mySellbilldetail->productunitid = $productunitId;
                    $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                    $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                    $mySellbilldetail->sellbilldetailprice = $price;
                    $mySellbilldetail->sellbilldetailproductid = $productId;
                    $mySellbilldetail->sellbilldetailquantity = $quantity;
                    $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                    $mySellbilldetail->sellbillid = $sellbillId;
                    $mySellbilldetail->buydiscount = $productData->buydiscount;
                    $mySellbilldetail->buydiscounttype = $productData->discounttype;
                    $mySellbilldetail->storeid = $sellbillstoreId;
                    $mySellbilldetail->discounttype = $discounttype;
                    $mySellbilldetail->otherdetailquantity = $scunitname;
                    $mySellbilldetail->sizeid = $sizeId;
                    $mySellbilldetail->colorid = $colorId;
                    $mySellbilldetail->pricetypepro = $pricetypepro;
                    $mySellbilldetail->categorydiscount = $catdis;
                    $mySellbilldetail->scunitqty = 0;
                    $mySellbilldetail->onlineOrderId = 0;

                    $detailId = $sellBillDetailOfferDAO->insert($mySellbilldetail);
                    array_push($detailsArr, $mySellbilldetail);


                    $taxesitr = $_POST['taxesitr_' . $h . ''];
                    $e = 1;

                    for ($e = 1; $e <= $taxesitr; $e++) {
                        if (!$_POST['type_' . $h . '_' . $e]) {
                            continue;
                        }

                        $sellbilldetailtax = R::dispense('sellbilldetailtax');
                        $sellbilldetailtax->sellbilldetailid = $detailId;
                        $sellbilldetailtax->is_offer = 1; //mean to use sellbilldetailid in sellbilldetailoffer table
                        $sellbilldetailtax->conditions = 0;
                        $sellbilldetailtax->type = $_POST['type_' . $h . '_' . $e];
                        $sellbilldetailtax->subtype = $_POST['subtype_' . $h . '_' . $e];
                        $sellbilldetailtax->rate = $_POST['rate_' . $h . '_' . $e];
                        $sellbilldetailtax->amount = $_POST['amount_' . $h . '_' . $e];
                        R::store($sellbilldetailtax);
                    }

                    $billnameData = R::findOne('billname', 'where billnameid = ' . $billnameId);
                    if ($billnameData->storeeffect == 1) {
                        if ($productData->isService == 0 && $Programsettingdata->preparingStore != $sellbillstoreId) { //if product && stores are not same
                            $productnumber = (float) $_POST['proNum' . $h];
                            if ($productnumber <= 0) {
                                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                                $productnumber = $productunitData->productnumber;
                            }
                            $finalquantity = $quantity * $productnumber;


                            /* -- decrease from stroe --------------------------- */
                            //get store productquantity before change
                            $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];
                            $billTotalBeforeDiscount = $sellbilltotalBill;
                            $billDiscountVal = 0;

                            //print("qty: ".$finalquantity.'<br>');
                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            } else {
                                $specialQuantityAfter = $finalquantity * -1;

                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            }

                            // /* -- increase from stroe --------------------------- */
                            // //get storeto productquantity before change
                            // $sellbillstoreId = $Programsettingdata->preparingStore;
                            // $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);
                            // $allStoredetailData = $storedetailData[0];
                            // $storedetailId = $storedetailData[1];
                            // $productquantityBefore = $storedetailData[2];
                            // if (count($allStoredetailData) > 0) {
                            //     //update productquantity in storedetail
                            //     $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            //     //insert in storereport
                            //     insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", $sellbillDate, $sizeId, $colorId);
                            // } else {
                            //     //insert in storedetail tbl
                            //     insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            //     //insert in storereport
                            //     insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", $sellbillDate, $sizeId, $colorId);
                            // }
                        }
                    }
                }
            }

            doOfferDailyEntry($sellbillId, $mySellbill, $detailsArr);
        }

        $mytransactions->commit();

        ##buyTheSellBill
        if ($sellbillId > 0 && $ordertype == 0) {
            buyTheSellBill($sellbillId, 0);
        }
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $sellbillclientId = $_POST['supplier'];
        markClientAsNOTInUse($sellbillclientId);
    }
    liveBackupComment("-- bill add end - with serial " . $_POST['bns'] . " and sellbillId = $sellbillId and returnsellbillId = $returnsellbillId");
    markStoreDetailNotInUse($storeDetailIds, $sizeColrDetailIds);
    return array(
        $sellbillId,
        $returnsellbillId,
        $productsBeforeValid,
        $saveValuebeforeValid,
        $billtype,
        $ordertype
    );
}

//load client by Id tbl
function loadClientNameById($clientId) {
    //to use the variable out side the funcion
    global $myClientRecord;

    //load client by Id tbl
    $clientData = $myClientRecord->load($clientId);
    $clientName = $clientData->clientname;

    return $clientName;
}

//load client by Id tbl
function loadClientDataById($clientId) {
    //to use the variable out side the funcion
    global $myClientRecord;

    //load client by Id tbl
    $clientData = $myClientRecord->load($clientId);

    return $clientData;
}

// load Product by id tbl
function loadProductById($productid) {
    //to use the variable out side the funcion
    global $myProductRecord;
    global $myProductEx;

    // load Product by id tbl
    $productData = $myProductEx->loadByProductId($productid);

    return $productData;
}

function loadProductUnitWithProductAndUnit($productId, $unitId) {

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

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($productId, $unitId);

    return $productunitData;
}

function getfirstunittWithProductNumberEQ1($productId) {

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

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->getfirstunittWithProductNumberEQ1($productId);

    return $productunitData->productunitid;
}

function showAll() {
    global $mySellbillEx;
    global $myClientRecord;
    global $userDAO;
    global $smarty;
    global $ProgramsettingDAO;
    global $myStoreRecord;
    global $mySaveRecord;
    global $myUserRecord;
    global $Programsettingdata;


    $queryString = ' WHERE';
    $queryStringDetails = '';
    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $shippingDateFrom = $_REQUEST['shippingDateFrom'];
    $shippingDateTo = $_REQUEST['shippingDateTo'];

    $deliverDateFrom = $_REQUEST['deliverDateFrom'];
    $deliverDateTo = $_REQUEST['deliverDateTo'];

    $collectionType = $_REQUEST['collectionType'];
    $collectionDateFrom = $_REQUEST['collectionDateFrom'];
    $collectionDateTo = $_REQUEST['collectionDateTo'];
    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['sellbillid'];
    $clientId = (int) $_REQUEST['clientid'];
    $typeclient = (int) $_REQUEST['typeclient'];
    $sellerid = $_REQUEST['sellerid'];
    $selleruserid = $_REQUEST['selleruserid'];
    $storeid = $_REQUEST['storeid'];
    $saveid = $_REQUEST['saveid'];
    $hideDel = (int) $_REQUEST['hideDel'];
    $hidePayed = (int) $_REQUEST['hidePayed'];
    $obgyBillType = (int) $_REQUEST['obgyBillType'];
    $billoperationid = (int) $_REQUEST['billoperationid'];
    $proSellTrackingSerial = $_REQUEST['proSellTrackingSerial'];
    $pricetype = (isset($_REQUEST['pricetype'])) ? (int) $_REQUEST['pricetype'] : -1;
    $sellbillcomment = $_REQUEST['sellbillcomment'];
    $tripid = (int) $_REQUEST['tripid'];

    if (isset($clientId) && $clientId > 0) {

        $messageData = $myClientRecord->load($clientId);
        $message .= "<br> إسم العميل: " . $messageData->clientname;

        $queryString .= ' sellbill.sellbillclientid = ' . $clientId . ' AND';
    }

    $userData = $myUserRecord->load($_SESSION['userid']);


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

        $messageData = $userDAO->load($sellerid);
        switch ($Programsettingdata->delegate_seller) {
            case 0:
                $message .= "<br> إسم البائع: $messageData->employeename ";
                break;
            case 1:
                $message .= "<br> إسم المندوب : $messageData->employeename ";
                break;
            case 2:
                $message .= "<br> إسم الطبيب : $messageData->employeename ";
                break;
        }

        $queryString .= ' sellbill.sellerid = ' . $sellerid . ' AND';
    }

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

        $messageData = $userDAO->load($selleruserid);
        $message .= "<br> إسم المستخدم: " . $messageData->employeename;

        $queryString .= ' sellbill.userid = ' . $selleruserid . ' AND';
    }

    if (isset($sellbillcomment) && $sellbillcomment != "") {
        $message .= "<br> التعليق الفاتورة: " . $sellbillcomment;
        $queryString .= " sellbill.comment LIKE '%" . $sellbillcomment . "%' AND ";
    }

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

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

        $queryString .= ' sellbill.sellbillserial = "' . $sellbillSerial . '" AND';
    }
    if (isset($sellbillId) && $sellbillId != "") {

        $message .= "<br> الرقم المتسلسل : " . $sellbillId;

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



    if (isset($storeid) && $storeid != "-1") {
        $messageData = $myStoreRecord->load($storeid);
        $message .= "<br> إسم المخزن: " . $messageData->storeName;
        $queryString .= ' sellbill.sellbillstoreid = ' . $storeid . ' AND';
    }

    if (isset($saveid) && $saveid != "-1") {
        $messageData = $mySaveRecord->load($saveid);
        $message .= "<br> إسم الخزنة: " . $messageData->savename;
        $queryString .= ' sellbill.sellbillsaveid = ' . $saveid . ' AND';
    }
    // else if ($_SESSION['searchinonesave'] == 0) {
    //     if ($_SESSION['saveids'] != 0) {
    //      $queryString .= ' sellbill.sellbillsaveid in (' . $_SESSION['saveids'] . ') AND';
    //     }
    // }else{
    // 	$messageData = $mySaveRecord->load($_SESSION['saveid']);
    //     $message .= "<br> إسم الخزنة: " . $messageData->savename;
    //     $queryString .= ' sellbill.sellbillsaveid = ' . $_SESSION['saveid'] . ' AND';
    // }


    if (isset($tripid) && $tripid > 0) {
        $queryString .= ' sellbill.travelTripId = ' . $tripid . ' AND';
    }


    if (isset($shippingDateFrom) && $shippingDateFrom != "" && isset($shippingDateTo) && $shippingDateTo != "") {
        $message .= "<br> تاريخ الشحن من  : " . $shippingDateFrom . " تاريخ الشحن الى : " . $shippingDateTo . "";
        $queryString .= ' sellbill.datestarting >= "' . $shippingDateFrom . '" and sellbill.datestarting <= "' . $shippingDateTo . '" AND';
    }
    if (isset($deliverDateFrom) && $deliverDateFrom != "" && isset($deliverDateTo) && $deliverDateTo != "") {
        $message .= "<br> تاريخ التسليم من  : " . $deliverDateFrom . " تاريخ التسليم الى : " . $deliverDateTo . "";
        $queryString .= ' sellbill.datestarting >= "' . $deliverDateFrom . '" and sellbill.datestarting <= "' . $deliverDateTo . '" AND';
    }
    if (isset($collectionType) && $collectionType > 0) {
        if ($collectionType == 1) {
            $message .= "<br> نوع التحصيل: " . "شيك";
        } elseif ($collectionType == 2) {
            $message .= "<br> نوع التحصيل: " . "مفتوح";
        }
        $queryString .= ' sellbill.collectionType = ' . $collectionType . ' AND';
    }
    if (isset($pricetype) && $pricetype >= 0 && $pricetype <= 2) {
        switch ($pricetype) {
            case 0:
                $message .= "<br> نوع السعر: " . "جملة";
                break;
            case 1:
                $message .= "<br> نوع السعر: " . "تجزئة";
                break;
            case 2:
                $message .= "<br> نوع السعر: " . "نصف جمملة";
                break;
        }

        $queryString .= ' sellbill.pricetype = ' . $pricetype . ' AND';
    }
    if (isset($collectionDateFrom) && $collectionDateFrom != "" && isset($collectionDateTo) && $collectionDateTo != "") {
        $message .= "<br> تاريخ الاستحقاق من  : " . $collectionDateFrom . " تاريخ الاستحقاق الى : " . $collectionDateTo . "";
        if (!isset($collectionType) || $collectionType < 1) {
            $queryString .= ' sellbill.collectionType > 0 AND';
        }
        $queryString .= ' sellbill.collectionDate >= "' . $collectionDateFrom . '" and sellbill.collectionDate <= "' . $collectionDateTo . '" AND';
    }
    if ($billoperationid > 0) {
        //        $message .= "<br> اخفاء المحذوف ";
        $queryString .= ' sellbill.billoperationid = ' . $billoperationid . ' AND';
    }
    if (isset($hideDel) && $hideDel == 1) {
        $message .= "<br> اخفاء المحذوف ";
        $queryString .= ' sellbill.conditions = 0 AND';
    }
    if ($obgyBillType > 0) {
        //        $message .= "<br> اخفاء المحذوف ";
        $queryString .= ' sellbill.obgyBillType = ' . $obgyBillType . ' AND';
    }

    if (!empty($proSellTrackingSerial)) {
        $message .= "<br> Serial : " . $proSellTrackingSerial;
        $queryStringDetails = ' and proSellTrackingSerial="' . $proSellTrackingSerial . '" ';
    }

    ##fatma
    $search = $_REQUEST['search'];
    if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
        if ($search == "dateOnly") {
            //display the converted time ##reportsPlusHours
            $Programsetting = $ProgramsettingDAO->load(1);
            $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
            if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
                $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
                $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
                $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
            } else {
                $endDate = $endDate . ' 23:59:59';
                $startDate = $startDate . " 00:00:00";
            }
        }

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

        $queryString .= ' sellbill.sellbilldate >= "' . $startDate . '" and sellbill.sellbilldate <= "' . $endDate . '" AND';
    }

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

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

        //print("<br>queryString: ".$queryString."<br>");
    }

    $totalBills = 0;

    $getTodayBills = (int) filter_input(INPUT_POST, 'getTodayBills');
    //if ($queryString == "") {
    if ($getTodayBills == 1) {
        $queryString = "";

        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        ################
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $startDate = $startYesterday;
            $endDate = $endYesterday;
        } else {
            $startDate = $startToday;
            $endDate = $endToday;
        }
        ##############
        $queryString .= ' where  sellbill.sellbilldate >= "' . $startDate . '" and sellbill.sellbilldate <=  "' . $endDate . '" ';
    }
    //hide old edit or deleted bills
    //$queryString .= ' and  sellbill.conditions = 0 ';
    //print_r($queryString);
    if ($queryString || $queryStringDetails) {

        if ($userData->viewbills == 3) {
            if ($userData->userstoreid == 0) {
                if ($userData->storeids == "") {
                    //no store allowed
                } else {
                    $queryString .= '  AND sellbill.sellbillstoreid in (' . $userData->storeids . ') ';
                }
            } else {
                $queryString .= ' AND sellbill.sellbillstoreid = ' . $userData->userstoreid . ' ';
            }
        }


        ##search details

        if (!empty($queryStringDetails)) {
            $detailsData = R::getAll('SELECT distinct sellbillid FROM sellbilldetail where 1 ' . $queryStringDetails);
            $sellbillidS = '';
            foreach ($detailsData as $value) {
                $sellbillidS .= $value['sellbillid'] . ",";
            }
            $sellbillidS = trim($sellbillidS, ",");
            $sellbillidS = empty($sellbillidS) ? 0 : $sellbillidS;
            if (empty($queryString)) {
                $queryString .= ' where 1 ';
            }
            $queryString .= " and sellbillid in (" . $sellbillidS . ")";
        }
        ##getting bills
        $sellbillData = R::getAll('SELECT sellbillid,sellbilldate,sellbilldiscount,sellbilldiscounttype,sellbilltotalbill,sellQuantity,pricetype,sellbilltotalpayed,sellbillfinalbill,sellbillaftertotalbill,sellbillserial,conditions,
                                   userid,sellerid,delbyuserid,sellbillclientid,sellbillstoreid,sellbillsaveid,deletedsellid,
                                   dailyentryid,shippingDate,collectionDate,estatus,epdf,dailyentryid,datestarting
                                   FROM sellbill ' . $queryString); //. ' ORDER BY sellbilldate desc ,sellbillid desc '

        list($billIDs, $userIDs, $sellerAndDelByIDs, $clientIDs, $storeIDs, $saveIDs) = [[], [], [], [], [], []];
        foreach ($sellbillData as $value) {
            $billIDs[] = $value['sellbillid'];
            $userIDs[] = $value['userid'];
            $sellerAndDelByIDs[] = $value['sellerid'];
            $sellerAndDelByIDs[] = $value['delbyuserid'];
            $clientIDs[] = $value['sellbillclientid'];
            $storeIDs[] = $value['sellbillstoreid'];
            $saveIDs[] = $value['sellbillsaveid'];
        }
        $billIDs = !empty($billIDs) ? array_unique($billIDs) : [0];
        $userIDs = !empty($userIDs) ? array_unique($userIDs) : [0];
        $sellerAndDelByIDs = !empty($sellerAndDelByIDs) ? array_unique($sellerAndDelByIDs) : [0];
        $clientIDs = !empty($clientIDs) ? array_unique($clientIDs) : [0];
        $storeIDs = !empty($storeIDs) ? array_unique($storeIDs) : [0];
        $saveIDs = !empty($saveIDs) ? array_unique($saveIDs) : [0];

        ##2- getting user data while applying viewbills conditions
        $userQueryString = '';
        if ($userData->viewbills == 0) {
            $userQueryString = ' AND userid =' . $_SESSION['userid'] . ' ';
        } else if ($userData->viewbills == 2) {
            $userQueryString = ' AND usergroupid =' . $_SESSION['usergroupid'] . ' ';
        }
        //////$sellbillData = $mySellbillEx->queryallWithOrder($queryString);
        $userDataArr = R::getAll('select userid,employeename from user where userid in(' . implode(',', $userIDs) . ') ' . $userQueryString);
        $userDataArr = customArrayIndexOne($userDataArr, 'userid');

        $paymentDataArr = R::getAll('SELECT billid, sum(clientdebtchangeamount) as clientdebtchangeamount
                FROM clientdebtchange where tablename = "clientPayedDeptSellBillsController.php" and billid in(' . implode(',', $billIDs) . ') group by billid');
        $paymentDataArr = customArrayIndexOne($paymentDataArr, 'billid');
        $sellBillDataTemp = array();
        foreach ($sellbillData as $value) {
            if ($userDataArr[$value['userid']] !== null) {
                $value['useremployeename'] = $userDataArr[$value['userid']]['employeename'];
                $value['billPayments'] = $paymentDataArr[$value['sellbillid']]['clientdebtchangeamount'];
                $value['sellbilltotalpayed'] += $paymentDataArr[$value['sellbillid']]['clientdebtchangeamount'];

                $billTotalBeforeDiscount = $value['sellbilltotalbill'];
                $sellbillDiscountType = $value['sellbilldiscounttype'];
                $sellbillDiscount = $value['sellbilldiscount'];
                if ($sellbillDiscountType == "2") {
                    $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
                    $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
                    $value['sellbilldiscount'] = $billDiscountVal;
                }
                if (!$hidePayed || (isset($hidePayed) && $hidePayed == 1 && $value['sellbilltotalpayed'] < $value['sellbillfinalbill']))
                    $sellBillDataTemp[] = $value;
            }
        }
        $sellbillData = $sellBillDataTemp;

        ##3-seller, delby data
        $userDataArr = R::getAll('select userid,employeename from user where userid in(' . implode(',', $sellerAndDelByIDs) . ') ');
        $userDataArr = customArrayIndexOne($userDataArr, 'userid');
        ##4-client
        $clientQS = '';
        if ($typeclient > 0) {
            $clientQS = ' AND typeclientid like "%,' . $typeclient . ',%" ';
        }
        $clientDataArr = R::getAll('select clientid,clientname from client where clientid in(' . implode(',', $clientIDs) . ') ' . $clientQS);
        $clientDataArr = customArrayIndexOne($clientDataArr, 'clientid');
        ##5- store
        $storeDataArr = R::getAll('select storeId,storeName from store where storeId in(' . implode(',', $storeIDs) . ') ');
        $storeDataArr = customArrayIndexOne($storeDataArr, 'storeId');
        ##6- save
        $saveDataArr = R::getAll('select saveid,savename from save where saveid in(' . implode(',', $saveIDs) . ') ');
        $saveDataArr = customArrayIndexOne($saveDataArr, 'saveid');
        ##7- editedbill
        $editedBillDataArr = R::getAll('select sellbillid,deletedsellid from sellbill where deletedsellid in(' . implode(',', $billIDs) . ') ');
        $editedBillDataArr = customArrayIndexOne($editedBillDataArr, 'deletedsellid');
        ##8- bill image
        $sellbillimageDataArr = R::getAll('SELECT sellbillimage.* FROM `sellbillimage` WHERE sellbillid in(' . implode(',', $billIDs) . ') ');
        $sellbillimageDataArr = customArrayIndexOne($sellbillimageDataArr, 'sellbillid');
        ##9- detail parcode
        if ($Programsettingdata->showparcode == 1) {
            $detailDataArr = R::getAll('SELECT sellbillid,parcode FROM sellbilldetail where sellbillid in(' . implode(',', $billIDs) . ') ');
            $detailDataArr = customArrayIndexMany($detailDataArr, 'sellbillid');
        }

        $sellBillDataTemp = array();
        foreach ($sellbillData as $value) {
            $value['employeename'] = $userDataArr[$value['sellerid']]['employeename'];
            $value['delbyusername'] = $userDataArr[$value['delbyuserid']]['employeename'];
            $value['clientname'] = $clientDataArr[$value['sellbillclientid']]['clientname'];
            $value['storeName'] = $storeDataArr[$value['sellbillstoreid']]['storeName'];
            $value['savename'] = $saveDataArr[$value['sellbillsaveid']]['savename'];
            $value['newSellbillidAfterEdit'] = $editedBillDataArr[$value['sellbillid']]['sellbillid'];
            $value['images'] = $sellbillimageDataArr[$value['sellbillid']]['images'];
            $value['sellbillimageid'] = $sellbillimageDataArr[$value['sellbillid']]['id'];

            $parcode = '';
            if ($Programsettingdata->showparcode == 1) {
                foreach ($detailDataArr[$value['sellbillid']] as $data) {
                    $parcode .= $data['parcode'] . ' / ';
                }
            }
            $value['parcodepro'] = $parcode;
            $value['sellbilltotalpayed'] = (float) $value['sellbilltotalpayed'];

            if ($value['conditions'] == 0) {
                $totalBills += $value['sellbillaftertotalbill'];
            }
            $billStatus = R::getRow('select status from sellbillstatus where sellbillid = ' . $value["sellbillid"] . ' order by id desc limit 1');
            $value['billStatus'] = $billStatus['status'];
            ##make it obj
            $obj = new stdClass();
            foreach ($value as $key1 => $value1) {
                $obj->$key1 = $value1;
            }
            ##
            if (isset($value['clientname']) && !empty($value['clientname'])) {
                $sellBillDataTemp[] = $obj;
            }
        }
        $sellbillData = $sellBillDataTemp;
    }
    $billsCount = count($sellbillData);
    $smarty->assign('billsCount', $billsCount);
    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function showAllOffers() {
    global $mySellbillEx;
    global $myClientRecord;
    global $userDAO;
    global $smarty;
    global $ProgramsettingDAO;
    global $sellBillOfferEX;
    global $Programsettingdata;

    $queryString = ' WHERE';
    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['sellbillid'];
    $clientId = (int) $_REQUEST['clientid'];
    $sellerid = $_REQUEST['sellerid'];
    $selleruserid = $_REQUEST['selleruserid'];

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

        $queryString .= ' sellbill.sellbillclientid = ' . $clientId . ' AND';
    }

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

        $messageData = $userDAO->load($sellerid);
        switch ($Programsettingdata->delegate_seller) {
            case 0:
                $message .= "<br> إسم البائع: $messageData->employeename ";
                break;
            case 1:
                $message .= "<br> إسم المندوب : $messageData->employeename ";
                break;
            case 2:
                $message .= "<br> إسم الطبيب : $messageData->employeename ";
                break;
        }

        $queryString .= ' sellbill.sellerid = ' . $sellerid . ' AND';
    }

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

        $messageData = $userDAO->load($selleruserid);
        $message .= "<br> إسم المستخدم: " . $messageData->employeename;

        $queryString .= ' sellbill.userid = ' . $selleruserid . ' AND';
    }

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

        $message .= "<br> رقم العرض: " . $sellbillSerial;

        $queryString .= ' sellbill.sellbillserial = "' . $sellbillSerial . '" AND';
    }
    if (isset($sellbillId) && $sellbillId != "") {

        $message .= "<br> الرقم المتسلسل : " . $sellbillId;

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

    ##fatma
    $search = $_REQUEST['search'];
    if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
        if ($search == "dateOnly") {
            //display the converted time ##reportsPlusHours
            $Programsetting = $ProgramsettingDAO->load(1);
            $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
            if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
                $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
                $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
                $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
            } else {
                $endDate = $endDate . ' 23:59:59';
                $startDate = $startDate . " 00:00:00";
            }
        }

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

        $queryString .= ' sellbill.sellbilldate >= "' . $startDate . '" and sellbill.sellbilldate <= "' . $endDate . '" AND';
    }

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

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

        //print("<br>queryString: ".$queryString."<br>");
    }

    $totalBills = 0;

    $getTodayBills = (int) filter_input(INPUT_POST, 'getTodayBills');
    //if ($queryString == "") {
    if ($getTodayBills == 1) {
        $queryString = "";

        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        ################
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $startDate = $startYesterday;
            $endDate = $endYesterday;
        } else {
            $startDate = $startToday;
            $endDate = $endToday;
        }
        ##############
        $queryString .= ' where  sellbill.sellbilldate >= "' . $startDate . '" and sellbill.sellbilldate <=  "' . $endDate . '" ';
    }
    //hide old edit or deleted bills
    //$queryString .= ' and  sellbill.conditions = 0 ';
    //print_r($queryString);
    if ($queryString) {
        $sellbillData = $sellBillOfferEX->queryallWithOrder($queryString);
    }

    $billsCount = count($sellbillData);
    $smarty->assign('billsCount', $billsCount);
    if ($billsCount > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }
    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByClient($clientId) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithClientId($clientId);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }
    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function newadd($oldid, $controlname) {
    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbillEx;

    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    global $myReturnsellbill;
    global $myReturnsellbillRecord;
    global $myReturnsellbillEx;

    global $myReturnsellbilldetail;
    global $myReturnsellbilldetailRecord;

    global $mySellbillandrutern;
    global $mySellbillandruternRecord;
    global $mySellbillandruternEx;

    global $mySellandruternbilldetail;
    global $mySellandruternbilldetailRecord;

    //
    global $sellBillCurr;
    global $sellBillCurrDAO;
    global $sellBillCurrEX;
    global $sellBillAndRuternCurr;
    global $sellBillAndRuternCurrDAO;
    global $sellBillAndRuternCurrEX;
    global $returnSellBillCurr;
    global $returnSellBillCurrDAO;
    global $returnSellBillCurrEX;
    global $mySaveRecord;
    global $mySaveEx;

    global $soldSerialProduct;
    global $soldSerialProductDAO;

    global $ProductunitDAO;
    global $Productunit;
    global $myProductunitEx;

    global $myProductserialEx;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    global $dailyEntryDebtor2;
    global $dailyEntryDebtorDAO2;

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

    global $accountsTreeDAO;
    global $accountsTree;

    global $mySave;
    global $mySaveRecord;

    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $sellBillDetailOfferDAO;
    global $sellBillDetailOfferEX;
    global $sellBillOfferDAO;
    global $sellBillOfferEX;

    global $bankAccountEX;
    global $bankAccountDAO;
    global $bankAccount;

    global $clientEX;

    global $sellbillId; //nedded for collective product##fatma
    global $firstProductId; //nedded for royal
    global $noOfDecimalPlaces;

    global $Programsettingdata;
    global $sellbillDate;
    global $sellCostsArray;

    if ($_GET['do'] != "update") { //Transaction
        $mytransactions = new Transaction();
    }
    try {
        $ordertype = (int) $_POST["ordertype"];
        $taxBillNumber = (int) $_POST["taxBillNumber"];

        $billnameId = $_POST['billnameid'];
        $saveid = (int) $_POST['saveid'];
        if (!isset($_POST['saveid']) || empty($saveid)) {
            $saveid = $_SESSION['saveid'];
        }

        $settingClient = (int) $_POST['settingclient'];
        $settingStore = (int) $_POST['settingstore'];
        $settingSeller = (int) $_POST['settingseller'];
        $settingDate = (int) $_POST['settingdate'];
        $settingQuantityCondition = $_POST['settingquantitycondition'];

        $tempClientName = $_POST['tempclientName'];
        $tax = (float) $_POST["tax"];
        $taxVal = (float) $_POST["taxVal"];

        $currencyId = (int) $_POST["currencyId"];
        $cFactor = (float) $_POST["cFactor"];

        $sellbillcarnumber = $_POST['carNumber'];
        $sellbillcartype = $_POST['carType'];
        $sellbillcarchase = $_POST['carChase'];
        $sellbillcarmotor = $_POST['carMotor'];

        $sellbillclientId = $_POST['supplier'];

        $Costcenterid = $_POST["Costcenter"];
        $billReservation = (int) $_POST["billReservation"];
        $billReservationDate = $_POST["billReservationDate"];

        $collectionType = (int) $_POST["collectionType"];
        $collectionDate = $_POST["collectionDate"];

        $knownwayId = (int) $_POST["knownwayId"];
        $travelDriverId = (int) $_POST["travelDriverId"];
        $travelBusId = (int) $_POST["travelBusId"];
        $travelPathId = (int) $_POST['travelPathId'];
        $travelTripId = (int) $_POST['travelTripId'];
        $travelTripTypeId = (int) $_POST['travelTripTypeId'];
        $travelTripDateId = (int) $_POST['travelTripDateId'];
        $sellToSupplier = (int) $_POST['sellToSupplier'];
        $whatShippingCost = (int) $_POST['whatShippingCost'];

        $comment = $_POST['comment'];
        $priceType = (int) $_POST['pricetype'];

        $clientName = loadClientNameById($sellbillclientId);
        if (empty($tempClientName)) {
            $tempClientName = $_POST['tempclientName'] = $clientName;
        }

        $sellbildirectPayment;
        //client
        if ($settingClient == 0 && $_POST['supplier'] != 1) {
            $sellbildirectPayment = 1;
        } else {
            $sellbildirectPayment = 0;
        }

        //Date
        if ($settingDate == 0) {
            $sellbillDate = $_POST['bn'];
        } else {
            $sellbillDate = date("Y-m-d H:i:s");
        }

        //Store
        if ($settingStore == 0) {
            $sellbillstoreId = $_POST['storeid'];
        } else {
            $sellbillstoreId = $_POST['storeid'];
        }

        //seller
        if ($settingSeller == 0) {
            $sellerId = $_POST['sellerid'];
            if ($sellerId == "-1" || $sellerId == "" || $sellerId == NULL) {
                $sellerId = 0;
            }
        } else {
            $sellerId = 0;
        }

        $sellbillSerial = $_POST['bns'];
        $priceType = (int) $_POST['hiddenpricetype'];
        $sellbillno = $_POST['sellbillno'];

        $sellbilltotalBill = (float) $_POST['sellbilltotalbill']; //اجمالى الفاتورة قبل الخصم
        $sellbillDiscountType = $_POST['distype']; //نوع الخصم
        $visa = (float) $_POST['genpayvisa'];
        $visaAccount = (int) $_POST['visaAccount'];
        if (empty($visaAccount)) {
            $visa = 0;
        }
        $isBankAccountTransfer = (int) $_POST['isBankAccountTransfer'];
        $extraDiscountPer = (float) $_POST['extraDiscountPer'];
        $extraDiscountVal = (float) $_POST['extraDiscountVal'];
        $taxOfDiscountPer = (float) $_POST['taxOfDiscountPercentage'];
        $taxOfDiscountVal = (float) $_POST['taxOfDiscountVal'];

        $sellbillDiscount = (float) $_POST['gendis']; //قيمة الخصم
        $sellbillAftertotalBill = (float) $_POST['sellbillaftertotalbill']; //القيمة بعد الخصم
        $sellbilltotalPayed = (float) $_POST['genpay']; //المدفوع
        $sellbillFinalbill = $sellbillAftertotalBill - $sellbilltotalPayed - $visa; //المتبقى
        $sellbillPrice = (float) $_POST['sellbillprice']; //اجمالى المبيعات
        $returnsellbillPrice = (float) $_POST['returnsellbillprice']; //اجمالى مردودات المبيعات
        $sellQuantity = (float) $_POST['sellQuantity'];
        $returnsellQuantity = (float) $_POST['returnsellQuantity'];
        $totalprodiscount = (float) $_POST['totalProDis']; //خصومات المنتج
        $manage_ex = (float) $_POST['manage_ex'];
        $med_hallmark = (float) $_POST['med_hallmark'];
        $pay_rec_no = (float) $_POST['pay_rec_no'];
        $pay_rec_val = (float) $_POST['pay_rec_val'];
        $decisionNo = (float) $_POST['decisionNo'];
        $decisionValue = (float) $_POST['decisionValue'];
        $dailyentryid = filter_input(INPUT_POST, 'dailyID');

        $returndailyentryid = (int) $_POST['returndailyentryid'];
        $datestarting = $_POST['datestarting'];

        ##get $billTotalBeforeDiscount
        $billTotalBeforeDiscount = $sellbilltotalBill;
        ##get $billDiscountVal
        $billDiscountVal = $sellbillDiscount;
        if ($sellbillDiscountType == "2") {
            $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
            $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
        }
        ########################################################################
        if ($ordertype == 0) { //bill only not offer
            $clientdata = getClientDataFromClientInUseSP($sellbillclientId);
            //$clientdata = loadClientDataById($sellbillclientId);
        }
        $sellbilltotaldeptBefor = $clientdata->clientdebt; //$_POST['hidden_debt'];
        $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + ($sellbillAftertotalBill - $sellbilltotalPayed - $visa); //المتبقى$_POST['clientdebtafter'];


        $sellbilldelivery = (float) $_POST['delivery']; //قيمه الشحن / التوصيل
        $totalaafterdelivery = (float) $_POST['valdeliveryhidden']; //الاجمالي العام بعد التوصيل


        $productsBeforeValid = 1;
        $saveValuebeforeValid = 1;

        //////////////////////////////////////////////////////////////////////////
        $sellbillItr = (int) $_POST['hidden_itr'];
        $returnSellbillItr = (int) $_POST['returnhidden_itr'];
        ##curr conversion
        $billCurrInsertId = 0;
        //$saveData = $mySaveEx->loadForUpdateEx($_SESSION['saveid']);
        $saveData = $mySaveEx->loadEx($_SESSION['saveid']);
        $saveConversionFactor = $saveData->conversionFactor;
        $sellbilldiscountC = $sellbillDiscount;
        $sellbilltotalbillC = $sellbilltotalBill;
        $sellbillaftertotalbillC = $sellbillAftertotalBill;
        $sellbilltotalpayedC = $sellbilltotalPayed;
        $sellbillfinalbillC = $sellbillFinalbill;
        $sellbildirectpaymentC = $sellbildirectPayment;
        $taxValC = $taxVal;
        $deliveryC = $sellbilldelivery;
        $totalafterdeliveryC = $totalaafterdelivery;
        $cashPayedC = $sellbilltotalPayed;
        $visaPayedC = $visa;
        $totalprodiscountC = $totalprodiscount;
        $extraDiscountValC = $extraDiscountVal;
        $taxOfDiscountValC = $taxOfDiscountVal;
        if ($currencyId > 1) {
            if ($sellbillDiscountType != "2")
                $sellbillDiscount = $sellbillDiscount / $cFactor;
            $sellbilltotalBill = $sellbilltotalBill / $cFactor;
            $sellbillAftertotalBill = $sellbillAftertotalBill / $cFactor;
            $sellbilltotalPayed = $sellbilltotalPayed / $cFactor;
            $sellbillFinalbill = $sellbillFinalbill / $cFactor;
            $sellbildirectPayment = 1;
            $taxVal = $taxVal / $cFactor;
            $sellbilldelivery = $sellbilldelivery / $cFactor;
            $totalaafterdelivery = $totalaafterdelivery / $cFactor;
            $cashPayed = $sellbilltotalPayed / $cFactor;
            $visa = $visa / $cFactor;
            $extraDiscountVal = $extraDiscountVal / $cFactor;
            $taxOfDiscountVal = $taxOfDiscountVal / $cFactor;
            $totalprodiscount = $totalprodiscount / $cFactor;
            $manage_ex = $manage_ex / $cFactor;
            $med_hallmark = $med_hallmark / $cFactor;
            $pay_rec_no = $pay_rec_no / $cFactor;
            $pay_rec_val = $pay_rec_val / $cFactor;
        }
        ###################################################
        if ($ordertype == 0) { //bill
            //check storerdetail value
            //check product quantity
            $settingQuantityAlert = (int) $_POST['settingQuantityAlert'];
            if ($sellbillPrice >= 0 && $settingQuantityAlert == 0) {
                $h = 1;
                for ($h = 1; $h <= $sellbillItr; $h++) {
                    $productId = $_POST['product' . $h . ''];
                    $productQuantity = $_POST['pronum' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    if (isset($productId) && $productId != '-1' && $productId != "") {

                        //get storefrom productquantity before change
                        $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                        $allStoredetailData = $storedetailData[0];
                        $storedetailId = $storedetailData[1];
                        $productquantityBefore = $storedetailData[2];
                        $isService = (int) $storedetailData[3];

                        //check if productquantityFromBefore greater than 0 or not
                        if ($isService == 0) { //product
                            $productsBeforeValid = 1;
                            if ($productquantityBefore > 0 && count($allStoredetailData) > 0) {
                                $productsAfterValid = $productquantityBefore - $productQuantity;

                                if ($productsAfterValid >= 0) {
                                    $productsBeforeValid = 1;
                                } else {
                                    $productsBeforeValid = 0;
                                    //return $productsBeforeValid;
                                }
                            } else {
                                $productsBeforeValid = 0;
                                //return $productsBeforeValid;
                            }
                        } else {
                            //service
                            $productsBeforeValid = 1;
                        }
                    }
                }
            }

            /////////////////check savefrom value before transfer//////////////////////
            if ($returnsellbillPrice > 0 && ($sellbillPrice <= 0 || $sellbillAftertotalBill)) {
                $saveValueafterValid;

                //get save value
                $saveValueBefore = getSaveValueBefore($saveid);

                $saveValueafterValid = $saveValueBefore - $sellbilltotalPayed;

                if ($saveValueafterValid >= 0) {
                    $saveValuebeforeValid = 1;
                } else {
                    $saveValuebeforeValid = 0;
                    //return $saveValuebeforeValid;
                }
            }

            $billtype;
            // مبيعات و ومردودات
            //insert data into Sellbillandrutern tbl
            if (isset($sellbillPrice) && $sellbillPrice > 0 && $returnsellbillPrice > 0) {

                $billtype = 3; // مبيعات و ومردودات


                $mySellbillandrutern->deletedsellid = $oldid;
                $mySellbillandrutern->controlname = $controlname;

                $mySellbillandrutern->billnameid = $billnameId;
                $mySellbillandrutern->conditions = 0;
                $mySellbillandrutern->sellbildirectpayment = $sellbildirectPayment;
                $mySellbillandrutern->sellbillaftertotalbill = $sellbillAftertotalBill;
                $mySellbillandrutern->sellbillclientid = $sellbillclientId;
                $mySellbillandrutern->sellbillclientname = $clientName;
                $mySellbillandrutern->sellbilldate = $sellbillDate;
                $mySellbillandrutern->sellbilldiscount = $sellbillDiscount;
                $mySellbillandrutern->sellbilldiscounttype = $sellbillDiscountType;
                $mySellbillandrutern->tempclientName = $tempClientName;
                $mySellbillandrutern->sellQuantity = $sellQuantity;
                $mySellbillandrutern->returnsellQuantity = $returnsellQuantity;
                $mySellbillandrutern->tax = $tax;
                $mySellbillandrutern->totalprodiscount = $totalprodiscount;
                $mySellbillandrutern->manage_ex = $manage_ex;
                $mySellbillandrutern->med_hallmark = $med_hallmark;
                $mySellbillandrutern->pay_rec_no = $pay_rec_no;
                $mySellbillandrutern->pay_rec_val = $pay_rec_val;
                $mySellbillandrutern->decisionNo = $decisionNo;
                $mySellbillandrutern->decisionValue = $decisionValue;

                if ($sellbilltotalBill < 0) {
                    //$sellbillFinalbill = $sellbillAftertotalBill + $sellbilltotalPayed;
                    $sellbillFinalbill = $sellbillAftertotalBill + abs($sellbilltotalPayed) + abs($visa);
                    //$sellbilltotaldeptAfter = $sellbilltotaldeptBefor - (($sellbillAftertotalBill - $sellbilltotalPayed) * -1);
                    $sellbilltotaldeptAfter = $sellbilltotaldeptBefor - (($sellbillAftertotalBill + $sellbilltotalPayed + $visa) * -1);
                }
                $mySellbillandrutern->sellbillfinalbill = $sellbillFinalbill;
                $mySellbillandrutern->sellbillsaveid = $saveid;
                $mySellbillandrutern->sellbillserial = $sellbillSerial;
                $mySellbillandrutern->sellbillstoreid = $sellbillstoreId;
                $mySellbillandrutern->sellbillsysdate = $sellbillDate; //date("Y-m-d H:i:s");
                $mySellbillandrutern->sellbilltotalbill = $sellbilltotalBill;
                $mySellbillandrutern->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
                $mySellbillandrutern->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                $mySellbillandrutern->sellbilltotalpayed = $sellbilltotalPayed + $visa;
                $mySellbillandrutern->sellerid = $sellerId;
                $mySellbillandrutern->userid = $_SESSION['userid'];
                $mySellbillandrutern->sellbillprice = $sellbillPrice;
                $mySellbillandrutern->returnsellbillprice = $returnsellbillPrice;
                $mySellbillandrutern->carnumber = $sellbillcarnumber;
                $mySellbillandrutern->cartype = $sellbillcartype;
                $mySellbillandrutern->carchase = $sellbillcarchase;
                $mySellbillandrutern->carmotor = $sellbillcarmotor;
                $mySellbillandrutern->costcenterid = $Costcenterid;
                $mySellbillandrutern->dailyentryid = 0;
                $mySellbillandrutern->comment = $comment;
                $mySellbillandrutern->billReservation = $billReservation;
                $mySellbillandrutern->billReservationDate = $billReservationDate;
                $mySellbillandrutern->cashPayed = $sellbilltotalPayed;
                $mySellbillandrutern->visaPayed = $visa;
                $mySellbillandrutern->visaAccountId = $visaAccount;
                $mySellbillandrutern->isBankAccountTransfer = $isBankAccountTransfer;
                $mySellbillandrutern->extraDiscountPer = $extraDiscountPer;
                $mySellbillandrutern->extraDiscountVal = $extraDiscountVal;
                $mySellbillandrutern->taxOfDiscountPer = $taxOfDiscountPer;
                $mySellbillandrutern->taxOfDiscountVal = $taxOfDiscountVal;
                $mySellbillandrutern->obgyBillType = (int) $_POST['obgyBillType'];
                $mySellbillandrutern->billoperationid = (int) $_POST['billoperationid'];
                $mySellbillandrutern->pricetype = $priceType;
                $mySellbillandrutern->currencyId = $currencyId;
                $mySellbillandrutern->sellbillno = $sellbillno;

                $sellbillId = $mySellbillandruternEx->insertupdate($mySellbillandrutern);
                ##curr conversion
                if ($currencyId > 1) {
                    $sellBillAndRuternCurr->sellbillid = $sellbillId;
                    $sellBillAndRuternCurr->conversionFactor = $cFactor;
                    $sellBillAndRuternCurr->sellbilldiscountC = $sellbilldiscountC;
                    $sellBillAndRuternCurr->sellbilltotalbillC = $sellbilltotalbillC;
                    $sellBillAndRuternCurr->sellbillaftertotalbillC = $sellbillaftertotalbillC;
                    $sellBillAndRuternCurr->sellbilltotalpayedC = $sellbilltotalpayedC;
                    $sellBillAndRuternCurr->sellbillfinalbillC = $sellbillfinalbillC;
                    $sellBillAndRuternCurr->sellbildirectpaymentC = 1;
                    $sellBillAndRuternCurr->taxC = $taxC;
                    //                        $sellBillAndRuternCurr->deliveryC = $deliveryC;
                    //                        $sellBillAndRuternCurr->totalafterdeliveryC = $totalafterdeliveryC;
                    $sellBillAndRuternCurr->cashPayedC = $cashPayedC;
                    $sellBillAndRuternCurr->visaPayedC = $visaPayedC;
                    $sellBillAndRuternCurr->extraDiscountValC = $extraDiscountValC;
                    $sellBillAndRuternCurr->taxOfDiscountValC = $taxOfDiscountValC;
                    $sellBillAndRuternCurr->saveConversionFactor = $saveConversionFactor;
                    $sellBillAndRuternCurr->totalprodiscountC = $totalprodiscountC;
                    $billCurrInsertId = $sellBillAndRuternCurrDAO->insert($sellBillAndRuternCurr);
                }

                if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                    //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                    //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                    {

                        //update rawmaterialssupplierdebt
                        updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                        if ($sellbilltotalBill < 0) {
                            $sellbillFinalbill = $sellbillFinalbill * -1;
                            insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 1, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillAftertotalBill, $sellbillDate, $visa, $visaAccount, $sellbilltotalPayed);
                        } else {
                            insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, $sellbilltotalPayed);
                        }
                        markClientAsNOTInUse($sellbillclientId);
                    }
                }

                $Costcenterdetail->costamount = $sellbillAftertotalBill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $sellbillId;
                $Costcenterdetail->processname = 'فاتوره مبيعات ومردودات';
                $Costcenterdetail->tablename = 'sellbillandruternController.php';
                $Costcenterdetail->type = 2;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }

                //insert Sell Data into Sellandruternbilldetail tbl
                $sellbillItr = $_POST['hidden_itr'];
                $h = 1;
                for ($h = 1; $h <= $sellbillItr; $h++) {
                    ## if input are encoded in json put it again in post
                    if (isset($_POST["obj" . $h])) {
                        foreach (json_decode(str_replace("'", '"', $_POST["obj" . $h]), true) as $key => $value) {
                            $_POST[$key . $h] = $value;
                        }
                    }
                    $parcode = $_POST['parcode' . $h . ''];
                    $parcodeType = $_POST['parcodeType' . $h . ''];
                    $productserailId = $_POST['productserailid' . $h . ''];
                    $productId = $_POST['product' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $productunitId = $_POST['productunit' . $h . ''];
                    $proHeight = (float) $_POST['proHeight' . $h . ''];
                    $proWidth = (float) $_POST['proWidth' . $h . ''];
                    $quantity = $_POST['pronum' . $h . ''];
                    $price = $_POST['proprice' . $h . ''];
                    $catdis = $_POST['catdis' . $h . ''];
                    $discountValue = $_POST['prodis' . $h . ''];
                    $discounttype = $_POST['discounttype' . $h . ''];
                    $totalPrice = $_POST['hidden_prototal' . $h . ''];
                    $comment = $_POST['comment' . $h . ''];
                    $prstorid = $_POST['prstorid' . $h . ''];
                    $scunitname = $_POST['scunitname' . $h . ''];
                    $pricetypepro = $_POST['pricetypepro' . $h . ''];
                    $proSerials = $_POST['proSerials' . $h . ''];

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

                        $sellbillstoreId = $prstorid;
                    } else {
                        $sellbillstoreId = $_POST['storeid'];
                        //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                    }

                    if ($productunitId == "") {
                        $productunitId = 0;
                    }

                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        if ($firstProductId == 0) {
                            $firstProductId = $productId;
                        }

                        $productData = loadProductById($productId);
                        //
                        $productnumber = (float) $_POST['proNum' . $h];
                        if ($productnumber <= 0) {
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                            $productnumber = $productunitData->productnumber;
                        }
                        $finalquantity = $quantity * $productnumber;
                        //
                        $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($sellbillstoreId, $productId, $sizeId, $colorId, $productData->productBuyPrice, $finalquantity, 0);
                        $theBuyPrice = $comingData[0];
                        $buyPricesHistoryBookIdQuantity = $comingData[1];

                        $mySellandruternbilldetail->buyprice = $theBuyPrice; //$productData->productBuyPrice;
                        $mySellandruternbilldetail->buyPricesHistoryBookIdQuantity = $buyPricesHistoryBookIdQuantity;
                        $mySellandruternbilldetail->discountvalue = $discountValue;
                        $mySellandruternbilldetail->note = $comment;
                        $mySellandruternbilldetail->parcode = $parcode;
                        $mySellandruternbilldetail->pricetype = $priceType;
                        $mySellandruternbilldetail->productunitid = $productunitId;
                        $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                        $mySellandruternbilldetail->sellbilldetaildate = $sellbillDate; //date("Y-m-d H:i:s");
                        $mySellandruternbilldetail->sellbilldetailprice = $price;
                        $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                        $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                        $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                        $mySellandruternbilldetail->sellbillid = $sellbillId;
                        $mySellandruternbilldetail->selltype = 0; //مبيعات
                        $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                        $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                        $mySellandruternbilldetail->storeid = $sellbillstoreId;
                        $mySellandruternbilldetail->discounttype = $discounttype;
                        $mySellandruternbilldetail->otherdetailquantity = $scunitname;
                        $mySellandruternbilldetail->sizeid = $sizeId;
                        $mySellandruternbilldetail->colorid = $colorId;
                        $mySellandruternbilldetail->pricetypepro = $pricetypepro;
                        $mySellandruternbilldetail->proHeight = $proHeight;
                        $mySellandruternbilldetail->proWidth = $proWidth;
                        $mySellandruternbilldetail->soldSerialsInDetails = $proSerials;
                        ##curr conversion
                        $mySellandruternbilldetail->sellbilldetailpriceC = $mySellandruternbilldetail->sellbilldetailprice;
                        $mySellandruternbilldetail->sellbilldetailtotalpriceC = $mySellandruternbilldetail->sellbilldetailtotalprice;
                        $mySellandruternbilldetail->discountvalueC = $mySellandruternbilldetail->discountvalue;
                        $mySellandruternbilldetail->proSellTrackingSerial = $_POST['proSellTrackingSerial' . $h];
                        if ($currencyId > 1) {
                            $price = $price / $cFactor;
                            $totalPrice = $totalPrice / $cFactor;
                            $discountValue = $discountValue / $cFactor;

                            $mySellandruternbilldetail->sellbilldetailprice = $price;
                            $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                            $mySellandruternbilldetail->discountvalue = $discountValue;
                        }
                        ##################################

                        $detailId = $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);

                        //update DON if is Serial
                        if (!empty($proSerials)) {
                            decreaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillId, $sellbillclientId, $detailId, 1, 'add');
                        } else if ($parcodeType == "serialnumber") {
                            //update don column (quantity) in productserial table
                            updateSerailQty($productserailId, $finalquantity);
                            insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 1, $sellbillclientId);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get store productquantity before change
                            $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات ومردودات (معدله)", "sellbillandruternController.php", $sellbillDate, $sizeId, $colorId);
                            } else {
                                $specialQuantityAfter = $finalquantity * -1;

                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, $sellbillDate, "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات ومردودات (معدله)", "sellbillandruternController.php", $sellbillDate, $sizeId, $colorId);
                            }

                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother - $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", $sellbillDate, 0);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname) * -1, $sellbillDate, 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname) * -1, 1, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", $sellbillDate, 0);
                                    }
                                }
                            }
                        }
                    }
                }

                //insert Return Data into Sellandruternbilldetail tbl
                $returnSellbillItr = $_POST['returnhidden_itr'];
                $h = 1;
                for ($h = 1; $h <= $returnSellbillItr; $h++) {
                    ## if input are encoded in json put it again in post
                    if (isset($_POST["objRet" . $h])) {
                        foreach (json_decode(str_replace("'", '"', $_POST["objRet" . $h]), true) as $key => $value) {
                            $_POST[$key . $h] = $value;
                        }
                    }
                    $parcode = $_POST['returnparcode' . $h . ''];
                    $parcodeType = $_POST['returnparcodeType' . $h . ''];
                    $productserailId = $_POST['returnproductserailid' . $h . ''];
                    $productId = $_POST['returnproduct' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $productunitId = $_POST['returnproductunit' . $h . ''];
                    $proHeight = (float) $_POST['returnproHeight' . $h . ''];
                    $proWidth = (float) $_POST['proWidth' . $h . ''];
                    $quantity = $_POST['returnpronum' . $h . ''];
                    $price = $_POST['returnproprice' . $h . ''];
                    $discountValue = $_POST['returnprodis' . $h . ''];
                    $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
                    $comment = $_POST['returncomment' . $h . ''];
                    $reprstorid = $_POST['reprstorid' . $h . ''];
                    $returndiscounttype = $_POST['returndiscounttype' . $h . ''];
                    $scunitname = $_POST['returnscunitname' . $h . ''];
                    $retpricetypepro = $_POST['retpricetypepro' . $h . ''];
                    $proSerials = $_POST['proSerialsRet' . $h . ''];

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

                        $sellbillstoreId = $reprstorid;
                    } else {
                        $sellbillstoreId = $_POST['storeid'];
                        //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                    }
                    if ($productunitId == "") {
                        $productunitId = 0;
                    }

                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        $productData = loadProductById($productId);

                        $mySellandruternbilldetail->buyprice = $productData->productBuyPrice;
                        $mySellandruternbilldetail->buyPricesHistoryBookIdQuantity = '';
                        $mySellandruternbilldetail->discountvalue = $discountValue;
                        $mySellandruternbilldetail->note = $comment;
                        $mySellandruternbilldetail->parcode = $parcode;
                        $mySellandruternbilldetail->pricetype = $priceType;
                        $mySellandruternbilldetail->productunitid = $productunitId;
                        $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                        $mySellandruternbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                        $mySellandruternbilldetail->sellbilldetailprice = $price;
                        $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                        $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                        $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                        $mySellandruternbilldetail->sellbillid = $sellbillId;
                        $mySellandruternbilldetail->selltype = 1; //مردودات
                        $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                        $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                        $mySellandruternbilldetail->storeid = $sellbillstoreId;
                        $mySellandruternbilldetail->discounttype = $returndiscounttype;
                        $mySellandruternbilldetail->otherdetailquantity = $scunitname;
                        $mySellandruternbilldetail->sizeid = $sizeId;
                        $mySellandruternbilldetail->colorid = $colorId;
                        $mySellandruternbilldetail->pricetypepro = $retpricetypepro;
                        $mySellandruternbilldetail->proHeight = $proHeight;
                        $mySellandruternbilldetail->proWidth = $proWidth;
                        $mySellandruternbilldetail->soldSerialsInDetails = $proSerials;
                        ##curr conversion
                        $mySellandruternbilldetail->sellbilldetailpriceC = $mySellandruternbilldetail->sellbilldetailprice;
                        $mySellandruternbilldetail->sellbilldetailtotalpriceC = $mySellandruternbilldetail->sellbilldetailtotalprice;
                        $mySellandruternbilldetail->discountvalueC = $mySellandruternbilldetail->discountvalue;
                        $mySellandruternbilldetail->proSellTrackingSerial = $_POST['retproSellTrackingSerial' . $h];
                        if ($currencyId > 1) {
                            $price = $price / $cFactor;
                            $totalPrice = $totalPrice / $cFactor;
                            $discountValue = $discountValue / $cFactor;

                            $mySellandruternbilldetail->sellbilldetailprice = $price;
                            $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                            $mySellandruternbilldetail->discountvalue = $discountValue;
                        }
                        ##################################

                        $detailId = $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);

                        $productnumber = (float) $_POST['retProNum' . $h];
                        if ($productnumber <= 0) {
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                            $productnumber = $productunitData->productnumber;
                        }
                        $finalquantity = $quantity * $productnumber;

                        //update DON if is Serial
                        if (!empty($proSerials)) {
                            increaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillId, $sellbillclientId, $detailId, 4, 'add');
                        } else if ($parcodeType == "serialnumber") {
                            //update don column (quantity) in productserial table
                            updateSerailQty_ForReturn($productserailId, $finalquantity);
                            insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 4, $sellbillclientId);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get storeto productquantity before change
                            $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, "اضافة فاتورة مبيعات ومردودات (معدله)", "sellbillandruternController.php", $sellbillDate, $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate, "sellbilldetailid", $detailId, $productId, "sellandruternbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "اضافة فاتورة مبيعات ومردودات (معدله)", "sellbillandruternController.php", $sellbillDate, $sizeId, $colorId);
                            }

                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother + $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", $sellbillDate, 1);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, $scunitname, $sellbillDate, 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, $scunitname, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", $sellbillDate, 1);
                                    }
                                }
                            }
                        }
                    }
                }

                //check if payed or not to change save value
                if ($sellbilltotalPayed != 0) {
                    if ($sellbillAftertotalBill > 0) {

                        //get saveValue before and saveValue after Plus lPayed
                        $saveData = getSaveValueAndPlus($saveid, $sellbilltotalPayed, $saveConversionFactor);
                        $saveId = $saveData[0];
                        $saveValuebefore = $saveData[1];
                        $saveValueafter = $saveData[2];
                        ##curr conversion
                        $sellbilltotalPayedSaveCurr = $saveData[3];
                        $saveConversionFactor = $saveData[4];
                        if ($currencyId > 1 && $billCurrInsertId > 0) {
                            $sellBillAndRuternCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                        }

                        //update save value after add sellbill
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl from save
                        $_SESSION['client_id'] = $sellbillclientId;
                        insertSavedailyupdate($saveValuebefore, $sellbilltotalPayedSaveCurr, 0, $saveId, "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
                        unset($_SESSION['client_id']);
                    } else {
                        //get saveValue before and saveValue after Plus lPayed
                        $saveData = getSaveValueAndMins($saveid, abs($sellbilltotalPayed), $saveConversionFactor);
                        $saveId = $saveData[0];
                        $saveValuebefore = $saveData[1];
                        $saveValueafter = $saveData[2];
                        ##curr conversion
                        $sellbilltotalPayedSaveCurr = $saveData[3];
                        $saveConversionFactor = $saveData[4];
                        if ($currencyId > 1 && $billCurrInsertId > 0) {
                            $sellBillAndRuternCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                        }

                        //update save value after add sellbill
                        updateSave($saveId, $saveValueafter);

                        $specialSellbilltotalPayed = $sellbilltotalPayed * -1;

                        //insert into savedaily tbl from save
                        $_SESSION['client_id'] = $sellbillclientId;
                        insertSavedailyupdate($saveValuebefore, $sellbilltotalPayedSaveCurr, 1, $saveId, "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
                        unset($_SESSION['client_id']);
                    }
                }
                if ($visa != 0 && $visaAccount > 0) {
                    if ($sellbillAftertotalBill > 0) {
                        $visaAccountData = $bankAccountDAO->load($visaAccount);
                        if ($isBankAccountTransfer == 1) {
                            $visaDisPerVal = 0;
                        } else {
                            $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                        }
                        $accountBefore = $visaAccountData->accountbeginingbalance;
                        $visaAccountData->accountbeginingbalance = $accountBefore + $visa - $visaDisPerVal;
                        $visaAccountData->accountdate = date('Y-m-d');
                        $visaAccountData->accountid = $visaAccount;
                        $bankAccountEX->updateacount($visaAccountData);

                        //Insert in accountmovement table the payment
                        $afterVal = $accountBefore + $visa;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 0, "سداد فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));

                        //Insert in accountmovement table the disount per
                        if ($isBankAccountTransfer != 1) {
                            $afterVal_AfterDisc = $afterVal - $visaDisPerVal;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 1, "نسبة خصم الفيزا من تحصيل فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));
                        }
                    } else {
                        $visaAccountData = $bankAccountDAO->load($visaAccount);
                        if ($isBankAccountTransfer == 1) {
                            $visaDisPerVal = 0;
                        } else {
                            $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                        }
                        $accountBefore = $visaAccountData->accountbeginingbalance;
                        $visaAccountData->accountbeginingbalance = $accountBefore - $visa + $visaDisPerVal;
                        $visaAccountData->accountdate = date('Y-m-d');
                        $visaAccountData->accountid = $visaAccount;
                        $bankAccountEX->updateacount($visaAccountData);

                        //Insert in accountmovement table the payment
                        $afterVal = $accountBefore - $visa;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 1, "سداد فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));

                        //Insert in accountmovement table the disount per
                        if ($isBankAccountTransfer != 1) {
                            $afterVal_AfterDisc = $afterVal + $visaDisPerVal;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 0, "نسبة خصم الفيزا من تحصيل فاتورة", "sellbillandruternController.php", $sellbillId, date('Y-m-d H:i:s'));
                        }
                    }
                }
            }

            //مبيعات
            //insert data into Sellbill tbl
            elseif ($sellbillPrice >= 0 && $returnsellbillPrice <= 0) {
                $billtype = 1; //مبيعات


                $mySellbill->billnameid = $billnameId;
                $mySellbill->conditions = 0;
                $mySellbill->sellbildirectpayment = $sellbildirectPayment;
                $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
                $mySellbill->sellbillclientid = $sellbillclientId;
                $mySellbill->sellbillclientname = $clientName;
                $mySellbill->sellbilldate = $sellbillDate; //date("Y-m-d H:i:s");
                $mySellbill->sellbilldiscount = $sellbillDiscount;
                $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
                $mySellbill->sellbillfinalbill = $sellbillFinalbill;
                $mySellbill->sellbillsaveid = $saveid;
                $mySellbill->sellbillserial = $sellbillSerial;
                $mySellbill->sellbillstoreid = $sellbillstoreId;
                $mySellbill->sellbillsysdate = $sellbillDate; //date("Y-m-d H:i:s");
                $mySellbill->sellbilltotalbill = $sellbilltotalBill;
                $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
                $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                $mySellbill->sellbilltotalpayed = $sellbilltotalPayed + $visa;
                $mySellbill->sellerid = $sellerId;
                $mySellbill->userid = $_SESSION['userid'];
                $mySellbill->tempclientName = $tempClientName;
                $mySellbill->sellQuantity = $sellQuantity;
                $mySellbill->tax = $tax;
                $mySellbill->carnumber = $sellbillcarnumber;
                $mySellbill->cartype = $sellbillcartype;
                $mySellbill->carchase = $sellbillcarchase;
                $mySellbill->carmotor = $sellbillcarmotor;
                $mySellbill->dailyentryid = $dailyentryid;
                $mySellbill->delivery = $sellbilldelivery;
                $mySellbill->cashPayed = $sellbilltotalPayed;
                $mySellbill->visaPayed = $visa;
                $mySellbill->visaAccountId = $visaAccount;
                $mySellbill->isBankAccountTransfer = $isBankAccountTransfer;
                $mySellbill->extraDiscountPer = $extraDiscountPer;
                $mySellbill->extraDiscountVal = $extraDiscountVal;
                $mySellbill->taxOfDiscountPer = $taxOfDiscountPer;
                $mySellbill->taxOfDiscountVal = $taxOfDiscountVal;
                $mySellbill->collectionType = $collectionType;
                $mySellbill->collectionDate = $collectionDate;
                $mySellbill->taxBillNumber = $taxBillNumber;
                $mySellbill->obgyBillType = (int) $_POST['obgyBillType'];
                $mySellbill->billoperationid = (int) $_POST['billoperationid'];
                $mySellbill->pricetype = $priceType;
                $mySellbill->currencyId = $currencyId;
                $mySellbill->knownwayId = $knownwayId;
                $mySellbill->travelBusId = $travelBusId;
                $mySellbill->travelDriverId = $travelDriverId;
                $mySellbill->travelPathId = $travelPathId;
                $mySellbill->travelTripId = $travelTripId;
                $mySellbill->travelTripTypeId = $travelTripTypeId;
                $mySellbill->travelTripDateId = $travelTripDateId;

                $mySellbill->totalafterdelivery = $totalaafterdelivery;

                $mySellbill->sellToSupplier = $sellToSupplier;
                $mySellbill->whatShippingCost = $whatShippingCost;

                $mySellbill->shipfrom = (int) $_POST['shipfrom'];
                $mySellbill->shipto = (int) $_POST['shipto'];
                $mySellbill->paymethodshipping = (int) $_POST['paymethodshipping'];

                $oldSellBill = $mySellbillRecord->load($oldid);
                $mySellbill->deletedsellid = $oldid;
                $mySellbill->controlname = $controlname;
                $mySellbill->obygyVisitId = $oldSellBill->obygyVisitId;
                $mySellbill->costcenterid = $Costcenterid;
                $mySellbill->comment = $comment;
                $mySellbill->billReservation = $billReservation;
                $mySellbill->billReservationDate = $billReservationDate;
                $mySellbill->webApiId = $oldSellBill->webApiId;
                $mySellbill->datestarting = $datestarting;
                $mySellbill->totalprodiscount = $totalprodiscount;
                $mySellbill->manage_ex = $manage_ex;
                $mySellbill->med_hallmark = $med_hallmark;
                $mySellbill->pay_rec_no = $pay_rec_no;
                $mySellbill->pay_rec_val = $pay_rec_val;
                $mySellbill->decisionNo = $decisionNo;
                $mySellbill->decisionValue = $decisionValue;

                $sellbillId = $mySellbillEx->insertupdate($mySellbill);
                ##curr conversion
                if ($currencyId > 1) {
                    $sellBillCurr->sellbillid = $sellbillId;
                    $sellBillCurr->conversionFactor = $cFactor;
                    $sellBillCurr->sellbilldiscountC = $sellbilldiscountC;
                    $sellBillCurr->sellbilltotalbillC = $sellbilltotalbillC;
                    $sellBillCurr->sellbillaftertotalbillC = $sellbillaftertotalbillC;
                    $sellBillCurr->sellbilltotalpayedC = $sellbilltotalpayedC;
                    $sellBillCurr->sellbillfinalbillC = $sellbillfinalbillC;
                    $sellBillCurr->sellbildirectpaymentC = 1;
                    $sellBillCurr->taxC = $taxC;
                    $sellBillCurr->deliveryC = $deliveryC;
                    $sellBillCurr->totalafterdeliveryC = $totalafterdeliveryC;
                    $sellBillCurr->cashPayedC = $cashPayedC;
                    $sellBillCurr->visaPayedC = $visaPayedC;
                    $sellBillCurr->extraDiscountValC = $extraDiscountValC;
                    $sellBillCurr->taxOfDiscountValC = $taxOfDiscountValC;
                    $sellBillCurr->saveConversionFactor = $saveConversionFactor;
                    $sellBillCurr->totalprodiscountC = $totalprodiscountC;
                    $billCurrInsertId = $sellBillCurrDAO->insert($sellBillCurr);
                }

                if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                    //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                    //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                    {

                        //update rawmaterialssupplierdebt
                        updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                        insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات (معدله)", $sellbillId, $sellbilltotaldeptAfter, "sellbillController.php", "اضافة فاتورة مبيعات (معدله)", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, $sellbilltotalPayed);
                        markClientAsNOTInUse($sellbillclientId);
                    }
                }

                $Costcenterdetail->costamount = $sellbillAftertotalBill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $sellbillId;
                $Costcenterdetail->processname = 'فاتوره مبيعات';
                $Costcenterdetail->tablename = 'sellbillController.php';
                $Costcenterdetail->type = 0;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }

                //insert Sell Data into Sellbilldetail tbl
                $sellbillItr = (int) $_POST['hidden_itr'];
                $h = 1;
                for ($h = 1; $h <= $sellbillItr; $h++) {
                    ## if input are encoded in json put it again in post
                    if (isset($_POST["obj" . $h])) {
                        foreach (json_decode(str_replace("'", '"', $_POST["obj" . $h]), true) as $key => $value) {
                            $_POST[$key . $h] = $value;
                        }
                    }
                    $parcode = $_POST['parcode' . $h . ''];
                    $taxesitr = $_POST['taxesitr_' . $h . ''];
                    $parcodeType = $_POST['parcodeType' . $h . ''];
                    $productserailId = $_POST['productserailid' . $h . ''];
                    $productId = $_POST['product' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $productunitId = $_POST['productunit' . $h . ''];
                    $proHeight = (float) $_POST['proHeight' . $h . ''];
                    $proWidth = (float) $_POST['proWidth' . $h . ''];
                    $quantity = $_POST['pronum' . $h . ''];
                    $price = $_POST['proprice' . $h . ''];
                    $catdis = $_POST['catdis' . $h . ''];
                    $discountValue = (float) $_POST['prodis' . $h . ''];
                    $totalPrice = $_POST['hidden_prototal' . $h . ''];
                    $comment = $_POST['comment' . $h . ''];
                    $prstorid = $_POST['prstorid' . $h . ''];
                    $discounttype = $_POST['discounttype' . $h . ''];
                    $scunitname = $_POST['scunitname' . $h . ''];
                    $pricetypepro = $_POST['pricetypepro' . $h . ''];
                    $proSerials = $_POST['proSerials' . $h . ''];
                    $travelBrokerId = (int) $_POST['travelBrokerId' . $h . ''];

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

                        //print_r('in if prstorid'.$prstorid.'<br>');
                        $sellbillstoreId = $prstorid;
                    } else {
                        $sellbillstoreId = $_POST['storeid'];
                        //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                    }
                    if ($productunitId == "") {
                        $productunitId = 0;
                    }
                    //print_r('the final'.$sellbillstoreId.'<br>');
                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        if ($firstProductId == 0) {
                            $firstProductId = $productId;
                        }

                        $productData = loadProductById($productId);
                        //
                        $productnumber = (float) $_POST['proNum' . $h];
                        if ($productnumber <= 0) {
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                            //print_r($productunitData);
                            $productnumber = $productunitData->productnumber;
                        }
                        $finalquantity = $quantity * $productnumber;
                        //
                        $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($sellbillstoreId, $productId, $sizeId, $colorId, $productData->productBuyPrice, $finalquantity, 0);
                        $theBuyPrice = $comingData[0];
                        $buyPricesHistoryBookIdQuantity = $comingData[1];

                        $mySellbilldetail->buyprice = $theBuyPrice; //$productData->productBuyPrice;
                        $mySellbilldetail->buyPricesHistoryBookIdQuantity = $buyPricesHistoryBookIdQuantity;
                        $mySellbilldetail->discountvalue = $discountValue;
                        $mySellbilldetail->note = $comment;
                        $mySellbilldetail->parcode = $parcode;
                        $mySellbilldetail->pricetype = $priceType;
                        $mySellbilldetail->productunitid = $productunitId;
                        $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                        $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s"); //date("Y-m-d H:i:s");
                        $mySellbilldetail->sellbilldetailprice = $price;
                        $mySellbilldetail->sellbilldetailproductid = $productId;
                        $mySellbilldetail->sellbilldetailquantity = $quantity;
                        $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                        $mySellbilldetail->sellbillid = $sellbillId;
                        $mySellbilldetail->buydiscount = $productData->buydiscount;
                        $mySellbilldetail->buydiscounttype = $productData->discounttype;
                        $mySellbilldetail->storeid = $sellbillstoreId;
                        $mySellbilldetail->discounttype = $discounttype;
                        $mySellbilldetail->otherdetailquantity = $scunitname;
                        $mySellbilldetail->sizeid = $sizeId;
                        $mySellbilldetail->colorid = $colorId;
                        $mySellbilldetail->pricetypepro = $pricetypepro;
                        $mySellbilldetail->proHeight = $proHeight;
                        $mySellbilldetail->proWidth = $proWidth;
                        $mySellbilldetail->soldSerialsInDetails = $proSerials;
                        $mySellbilldetail->travelBrokerId = $travelBrokerId;
                        $mySellbilldetail->categorydiscount = $catdis;

                        ##curr conversion
                        $mySellbilldetail->sellbilldetailpriceC = $mySellbilldetail->sellbilldetailprice;
                        $mySellbilldetail->sellbilldetailtotalpriceC = $mySellbilldetail->sellbilldetailtotalprice;
                        $mySellbilldetail->discountvalueC = $mySellbilldetail->discountvalue;
                        $mySellbilldetail->prosellDiscountPer = (float) $_POST['prosellDiscountPer' . $h];
                        $mySellbilldetail->prosellDiscountPerType = (int) $_POST['prosellDiscountPerType' . $h];
                        $mySellbilldetail->prosellDiscountVal = (float) $_POST['prosellDiscountVal' . $h];
                        $mySellbilldetail->proSellTrackingSerial = $_POST['proSellTrackingSerial' . $h];
                        if ($currencyId > 1) {
                            $price = $price / $cFactor;
                            $totalPrice = $totalPrice / $cFactor;
                            $discountValue = $discountValue / $cFactor;

                            $mySellbilldetail->sellbilldetailprice = $price;
                            $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                            $mySellbilldetail->discountvalue = $discountValue;
                        }
                        ##################################


                        $detailId = $mySellbilldetailRecord->insert($mySellbilldetail);
                        $e = 1;

                        for ($e = 1; $e <= $taxesitr; $e++) {
                            if (!$_POST['type_' . $h . '_' . $e]) {
                                continue;
                            }
                            $sellbilldetailtax = R::dispense('sellbilldetailtax');
                            $sellbilldetailtax->sellbilldetailid = $detailId;
                            $sellbilldetailtax->conditions = 0;
                            $sellbilldetailtax->type = $_POST['type_' . $h . '_' . $e];
                            $sellbilldetailtax->subtype = $_POST['subtype_' . $h . '_' . $e];
                            $sellbilldetailtax->rate = $_POST['rate_' . $h . '_' . $e];
                            $sellbilldetailtax->amount = $_POST['amount_' . $h . '_' . $e];
                            R::store($sellbilldetailtax);
                        }
                        //print("qty: ".$quantity.'<br>');
                        //print("<br>productserailId: ".$productserailId);
                        //update DON if is Serial
                        if (!empty($proSerials)) {
                            decreaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillId, $sellbillclientId, $detailId, 0, 'add');
                        } else if ($parcodeType == "serialnumber") {
                            //updateSerailDon($productserailId, 1, $sellbillId);
                            updateSerailQty($productserailId, $finalquantity);
                            insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 0, $sellbillclientId);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get store productquantity before change
                            $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            //print("qty: ".$finalquantity.'<br>');
                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //print("productquantityAfter: ".$productquantityAfter.'<br>');
                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات (معدله)", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            } else {
                                $specialQuantityAfter = $finalquantity * -1;

                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات (معدله)", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            }

                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother - $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname) * -1, date("Y-m-d H:i:s"), 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname) * -1, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                    }
                                }
                            }
                        }
                    }
                }

                //check if payed or not to change save value
                if ($sellbilltotalPayed > 0) {
                    //get saveValue before and saveValue after Plus lPayed
                    $saveData = getSaveValueAndPlus($saveid, $sellbilltotalPayed, $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $sellbilltotalPayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];
                    if ($currencyId > 1 && $billCurrInsertId > 0) {
                        $sellBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                    }


                    //update save value after add sellbill
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from save
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedailyupdate($saveValuebefore, $sellbilltotalPayedSaveCurr, 0, $saveId, "اضافة فاتورة مبيعات (معدله)", $sellbillId, $saveValueafter, "sellbillController.php", date("Y-m-d H:i:s"));
                    unset($_SESSION['client_id']);
                }
                if ($visa != 0 && $visaAccount > 0) {
                    $visaAccountData = $bankAccountDAO->load($visaAccount);
                    if ($isBankAccountTransfer == 1) {
                        $visaDisPerVal = 0;
                    } else {
                        $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                    }
                    $accountBefore = $visaAccountData->accountbeginingbalance;
                    $visaAccountData->accountbeginingbalance = $accountBefore + $visa - $visaDisPerVal;
                    $visaAccountData->accountdate = date('Y-m-d');
                    $visaAccountData->accountid = $visaAccount;
                    $bankAccountEX->updateacount($visaAccountData);

                    //Insert in accountmovement table the payment
                    $afterVal = $accountBefore + $visa;
                    insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 0, "سداد فاتورة", "sellbillController.php", $sellbillId, date('Y-m-d H:i:s'));

                    //Insert in accountmovement table the disount per
                    if ($isBankAccountTransfer != 1) {
                        $afterVal_AfterDisc = $afterVal - $visaDisPerVal;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 1, "نسبة خصم الفيزا من تحصيل فاتورة", "sellbillController.php", $sellbillId, date('Y-m-d H:i:s'));
                    }
                }

                $oldbillStatus = R::findAll('sellbillstatus', 'where sellbillid = ' . $oldid);
                if (!empty($oldbillStatus)) {
                    foreach ($oldbillStatus as $status) {
                        $billStatus = R::dispense("sellbillstatus");
                        $billStatus->sellbillid = $sellbillId;
                        $billStatus->status = $status->status;
                        $billStatus->userid = $status->userid;
                        $billStatus->sysdate = $status->sysdate;
                        $billStatusId = R::store($billStatus);
                    }
                }
            }

            //مردودات مبيعات
            //insert data into returnSellbill tbl
            elseif ($sellbillPrice <= 0 && $returnsellbillPrice > 0) {
                $billtype = 2; //مردودات مبيعات


                $myReturnsellbill->billnameid = $billnameId;
                $myReturnsellbill->conditions = 0;
                $myReturnsellbill->returnsellbildirectpayment = $sellbildirectPayment;
                $myReturnsellbill->returnsellbillaftertotalbill = $sellbillAftertotalBill * -1;
                $myReturnsellbill->returnsellbillclientid = $sellbillclientId;
                $myReturnsellbill->returnsellbillclientname = $clientName;
                $myReturnsellbill->returnsellbilldate = $sellbillDate; //date("Y-m-d H:i:s");
                $myReturnsellbill->returnsellbilldiscount = $sellbillDiscount;
                $myReturnsellbill->returnsellbilldiscounttype = $sellbillDiscountType;
                $myReturnsellbill->tax = $tax;

                //$sellbillFinalbill = ($sellbillAftertotalBill * -1 ) - $sellbilltotalPayed;
                //$sellbilltotaldeptAfter = $sellbilltotaldeptBefor - (($sellbillAftertotalBill - $sellbilltotalPayed) * -1);
                //$sellbilltotaldeptAfter = $sellbilltotaldeptBefor - (($sellbillAftertotalBill + $sellbilltotalPayed) * -1);
                $sellbillFinalbill = $sellbillAftertotalBill + abs($sellbilltotalPayed) + abs($visa);
                $gen4totalinput = $sellbillAftertotalBill + abs($sellbilltotalPayed) + abs($visa);
                $sellbilltotaldeptAfter = $sellbilltotaldeptBefor - ($gen4totalinput * -1);

                $myReturnsellbill->returnsellbillfinalbill = abs($sellbillFinalbill) * -1;
                $myReturnsellbill->returnsellbillsaveid = $saveid;
                $myReturnsellbill->returnsellbillserial = $sellbillSerial;
                $myReturnsellbill->returnsellbillstoreid = $sellbillstoreId;
                $myReturnsellbill->returnsellbillsysdate = $sellbillDate; //date("Y-m-d H:i:s");
                $myReturnsellbill->returnsellbilltotalbill = $sellbilltotalBill * -1;
                $myReturnsellbill->returnsellbilltotaldeptafter = $sellbilltotaldeptAfter;
                $myReturnsellbill->returnsellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                $myReturnsellbill->returnsellbilltotalpayed = $sellbilltotalPayed + $visa;
                $myReturnsellbill->sellerid = $sellerId;
                $myReturnsellbill->userid = $_SESSION['userid'];
                $myReturnsellbill->tempclientName = $tempClientName;
                $myReturnsellbill->returnsellQuantity = $returnsellQuantity;

                $myReturnsellbill->deletedsellid = $oldid;
                $myReturnsellbill->controlname = $controlname;
                $mySellbill->carnumber = $sellbillcarnumber;
                $myReturnsellbill->cartype = $sellbillcartype;
                $myReturnsellbill->carchase = $sellbillcarchase;
                $myReturnsellbill->carmotor = $sellbillcarmotor;
                $myReturnsellbill->costcenterid = $Costcenterid;
                $myReturnsellbill->dailyentryid = $returndailyentryid;
                $myReturnsellbill->comment = $comment;
                $myReturnsellbill->billReservation = $billReservation;
                $myReturnsellbill->billReservationDate = $billReservationDate;
                $myReturnsellbill->cashPayed = $sellbilltotalPayed;
                $myReturnsellbill->visaPayed = $visa;
                $myReturnsellbill->visaAccountId = $visaAccount;
                $myReturnsellbill->isBankAccountTransfer = $isBankAccountTransfer;
                $myReturnsellbill->extraDiscountPer = $extraDiscountPer;
                $myReturnsellbill->extraDiscountVal = $extraDiscountVal;
                $myReturnsellbill->taxOfDiscountPer = $taxOfDiscountPer;
                $myReturnsellbill->taxOfDiscountVal = $taxOfDiscountVal;
                $myReturnsellbill->obgyBillType = (int) $_POST['obgyBillType'];
                $myReturnsellbill->billoperationid = (int) $_POST['billoperationid'];
                $myReturnsellbill->pricetype = $priceType;
                $myReturnsellbill->currencyId = $currencyId;
                $myReturnsellbill->sellbillno = $sellbillno;

                $sellbillId = $returnsellbillId = $myReturnsellbillEx->insertupdate($myReturnsellbill);
                ##curr conversion
                if ($currencyId > 1) {
                    $returnSellBillCurr->returnsellbillid = $sellbillId;
                    $returnSellBillCurr->conversionFactor = $cFactor;
                    $returnSellBillCurr->returnsellbilldiscountC = $sellbilldiscountC;
                    $returnSellBillCurr->returnsellbilltotalbillC = $sellbilltotalbillC;
                    $returnSellBillCurr->returnsellbillaftertotalbillC = $sellbillaftertotalbillC;
                    $returnSellBillCurr->returnsellbilltotalpayedC = $sellbilltotalpayedC;
                    $returnSellBillCurr->returnsellbillfinalbillC = $sellbillfinalbillC;
                    $returnSellBillCurr->returnsellbildirectpaymentC = 1;
                    $returnSellBillCurr->taxC = $taxC;
                    //                        $returnSellBillCurr->deliveryC = $deliveryC;
                    //                        $returnSellBillCurr->totalafterdeliveryC = $totalafterdeliveryC;
                    $returnSellBillCurr->cashPayedC = $cashPayedC;
                    $returnSellBillCurr->visaPayedC = $visaPayedC;
                    $returnSellBillCurr->extraDiscountValC = $extraDiscountValC;
                    $returnSellBillCurr->taxOfDiscountValC = $taxOfDiscountValC;
                    $returnSellBillCurr->saveConversionFactor = $saveConversionFactor;
                    $billCurrInsertId = $returnSellBillCurrDAO->insert($returnSellBillCurr);
                }

                if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                    //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                    //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                    {

                        //update rawmaterialssupplierdebt
                        updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                        insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, abs($sellbillFinalbill), 1, "اضافة فاتورة مردوات مبيعات (معدله)", $returnsellbillId, $sellbilltotaldeptAfter, "returnsellbillController.php", "اضافة فاتورة مردوات مبيعات (معدله)", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, $sellbilltotalPayed);
                        markClientAsNOTInUse($sellbillclientId);
                    }
                }

                $Costcenterdetail->costamount = $sellbillAftertotalBill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $returnsellbillId;
                $Costcenterdetail->processname = 'فاتوره مردودات مبيعات';
                $Costcenterdetail->tablename = 'returnsellbillController.php';
                $Costcenterdetail->type = 0;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }

                //insert Return Data into returnsellbilldetail tbl
                $returnSellbillItr = $_POST['returnhidden_itr'];
                $h = 1;
                for ($h = 1; $h <= $returnSellbillItr; $h++) {
                    ## if input are encoded in json put it again in post
                    if (isset($_POST["objRet" . $h])) {
                        foreach (json_decode(str_replace("'", '"', $_POST["objRet" . $h]), true) as $key => $value) {
                            $_POST[$key . $h] = $value;
                        }
                    }
                    $parcode = $_POST['returnparcode' . $h . ''];
                    $parcodeType = $_POST['returnparcodeType' . $h . ''];
                    $productserailId = $_POST['returnproductserailid' . $h . ''];
                    $productId = $_POST['returnproduct' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $productunitId = $_POST['returnproductunit' . $h . ''];
                    $quantity = $_POST['returnpronum' . $h . ''];
                    $proHeight = (float) $_POST['returnproHeight' . $h . ''];
                    $proWidth = (float) $_POST['returnproWidth' . $h . ''];
                    $price = $_POST['returnproprice' . $h . ''];
                    $discountValue = $_POST['returnprodis' . $h . ''];
                    $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
                    $comment = $_POST['returncomment' . $h . ''];
                    $returndiscounttype = $_POST['returndiscounttype' . $h . ''];
                    $scunitname = $_POST['returnscunitname' . $h . ''];
                    $retpricetypepro = $_POST['retpricetypepro' . $h . ''];
                    $proSerials = $_POST['proSerialsRet' . $h . ''];

                    $reprstorid = $_POST['reprstorid' . $h . ''];
                    if (isset($reprstorid) && $reprstorid != -1 && $reprstorid != '') {

                        $sellbillstoreId = $reprstorid;
                    } else {
                        $sellbillstoreId = $_POST['storeid'];
                        //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                    }

                    if ($productunitId == "") {
                        $productunitId = 0;
                    }

                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        if ($firstProductId == 0) {
                            $firstProductId = $productId;
                        }
                        $productData = loadProductById($productId);
                        //                        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                        $myReturnsellbilldetail->buyprice = $productData->productBuyPrice;
                        $myReturnsellbilldetail->conditions = 0;
                        $myReturnsellbilldetail->discountvalue = $discountValue;
                        $myReturnsellbilldetail->note = $comment;
                        $myReturnsellbilldetail->parcode = $parcode;
                        $myReturnsellbilldetail->pricetype = $priceType;
                        $myReturnsellbilldetail->productunitid = $productunitId;
                        $myReturnsellbilldetail->returnsellbilldetailcatid = $productData->productCatId;
                        $myReturnsellbilldetail->returnsellbilldetailprice = $price;
                        $myReturnsellbilldetail->returnsellbilldetailproductid = $productId;
                        $myReturnsellbilldetail->returnsellbilldetailquantity = $quantity;
                        $myReturnsellbilldetail->returnsellbilldetailtotalprice = $totalPrice;
                        $myReturnsellbilldetail->returnsellbillid = $returnsellbillId;
                        $myReturnsellbilldetail->buydiscount = $productData->buydiscount;
                        $myReturnsellbilldetail->buydiscounttype = $productData->discounttype;
                        $myReturnsellbilldetail->storeid = $sellbillstoreId;
                        $myReturnsellbilldetail->discounttype = $returndiscounttype;
                        $myReturnsellbilldetail->otherdetailquantity = $scunitname;
                        $myReturnsellbilldetail->sizeid = $sizeId;
                        $myReturnsellbilldetail->colorid = $colorId;
                        $myReturnsellbilldetail->pricetypepro = $retpricetypepro;
                        $myReturnsellbilldetail->proHeight = $proHeight;
                        $myReturnsellbilldetail->proWidth = $proWidth;
                        $myReturnsellbilldetail->soldSerialsInDetails = $proSerials;
                        ##curr conversion
                        $myReturnsellbilldetail->returnsellbilldetailpriceC = $myReturnsellbilldetail->returnsellbilldetailprice;
                        $myReturnsellbilldetail->returnsellbilldetailtotalpriceC = $myReturnsellbilldetail->returnsellbilldetailtotalprice;
                        $myReturnsellbilldetail->discountvalueC = $myReturnsellbilldetail->discountvalue;
                        $myReturnsellbilldetail->proSellTrackingSerial = $_POST['retproSellTrackingSerial' . $h];
                        if ($currencyId > 1) {
                            $price = $price / $cFactor;
                            $totalPrice = $totalPrice / $cFactor;
                            $discountValue = $discountValue / $cFactor;

                            $myReturnsellbilldetail->returnsellbilldetailprice = $price;
                            $myReturnsellbilldetail->returnsellbilldetailtotalprice = $totalPrice;
                            $myReturnsellbilldetail->discountvalue = $discountValue;
                        }
                        ##################################

                        $detailId = $myReturnsellbilldetailRecord->insert($myReturnsellbilldetail);

                        $productnumber = (float) $_POST['retProNum' . $h];
                        if ($productnumber <= 0) {
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                            $productnumber = $productunitData->productnumber;
                        }
                        $finalquantity = $quantity * $productnumber;

                        //update DON if is Serial
                        if (!empty($proSerials)) {
                            increaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $returnsellbillId, $sellbillclientId, $detailId, 3, 'add');
                        } else if ($parcodeType == "serialnumber") {
                            //updateSerailDon($productserailId, 0, 0);
                            updateSerailQty_ForReturn($productserailId, $finalquantity);
                            insertIntoSoldSerialProduct($productserailId, $finalquantity, $returnsellbillId, 3, $sellbillclientId);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get storeto productquantity before change
                            $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "returnsellbilldetailid", $detailId, $productId, "returnsellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات (معدله)", "returnsellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, date("Y-m-d H:i:s"), "returnsellbilldetailid", $detailId, $productId, "returnsellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات (معدله)", "returnsellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            }

                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother + $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات ", "returnsellbillController.php", date("Y-m-d H:i:s"), 1);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname), date("Y-m-d H:i:s"), 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname), 0, $returnsellbillId, "اضافة فاتورة مردودات ", "returnsellbillController.php", date("Y-m-d H:i:s"), 1);
                                    }
                                }
                            }
                        }
                    }
                }

                //check if payed or not to change save value
                if ($sellbilltotalPayed != 0) {

                    //get saveValue before and saveValue after mins sellbilltotalPayed
                    $saveData = getSaveValueAndMins($saveid, abs($sellbilltotalPayed), $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $sellbilltotalPayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];
                    if ($currencyId > 1 && $billCurrInsertId > 0) {
                        $returnSellBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                    }


                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $specialSellbilltotalPayed = $sellbilltotalPayedSaveCurr * -1;
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedailyupdate($saveValuebefore, $specialSellbilltotalPayed, 1, $saveId, "اضافة فاتورة مردوات مبيعات (معدله)", $returnsellbillId, $saveValueafter, "returnsellbillController.php", date("Y-m-d H:i:s"));
                    unset($_SESSION['client_id']);
                }
                if ($visa != 0 && $visaAccount > 0) {
                    $visaAccountData = $bankAccountDAO->load($visaAccount);
                    if ($isBankAccountTransfer == 1) {
                        $visaDisPerVal = 0;
                    } else {
                        $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                    }
                    $accountBefore = $visaAccountData->accountbeginingbalance;
                    $visaAccountData->accountbeginingbalance = $accountBefore - $visa + $visaDisPerVal;
                    $visaAccountData->accountdate = date('Y-m-d');
                    $visaAccountData->accountid = $visaAccount;
                    $bankAccountEX->updateacount($visaAccountData);

                    //Insert in accountmovement table the payment
                    $afterVal = $accountBefore - $visa;
                    insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 1, "سداد فاتورة", "returnsellbillController.php", $sellbillId, date('Y-m-d H:i:s'));

                    //Insert in accountmovement table the disount per
                    if ($isBankAccountTransfer != 1) {
                        $afterVal_AfterDisc = $afterVal + $visaDisPerVal;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 0, "نسبة خصم الفيزا من تحصيل فاتورة", "returnsellbillController.php", $sellbillId, date('Y-m-d H:i:s'));
                    }
                }

                if ($sellerId > 0) {
                    $clientEX->updateClientDelegateid($sellbillclientId, $sellerId);
                }
            }

            /*             * **************************************************تعديل مردودات المبيعات********************************************************** */
            //قيود اليومية
            foreach (explode(',', $dailyentryid) as $entryid) {
                reverseEntryWithItsID($entryid, 1);
            }
            doBillDailyEntry($billtype, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $saveid, $visa, $visaAccount, $sellbillFinalbill, $clientdata->treeId, $taxOfDiscountVal, $billDiscountVal, $sellbilltotalBill, $sellbillAftertotalBill, $taxVal, $sellCostsArray, $sellbillstoreId, $firstProductId, (int) $_POST['billoperationid']);
            writePaymentToRoyalFinancialReport($sellbillclientId, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $visa, $saveid, $visaAccount, (int) $_POST['obgyBillType'], $billtype, 'add');
            /*             * **************************************************تعديل مردودات المبيعات********************************************************** */



            quickProfitBill($sellbillPrice, $returnsellbillPrice, $billDiscountVal, $sellbillclientId, 1);
        } elseif ($ordertype == 1) {
            $billtype = 1; //مبيعات


            $mySellbill->billnameid = $billnameId;
            $mySellbill->conditions = 0;
            $mySellbill->sellbildirectpayment = $sellbildirectPayment;
            $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
            $mySellbill->sellbillclientid = $sellbillclientId;
            $mySellbill->sellbillclientname = $clientName;
            $mySellbill->sellbilldate = $sellbillDate; //date("Y-m-d H:i:s");
            $mySellbill->sellbilldiscount = $sellbillDiscount;
            $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
            $mySellbill->sellbillfinalbill = $sellbillFinalbill;
            $mySellbill->sellbillsaveid = $saveid;
            $mySellbill->sellbillserial = $sellbillSerial;
            $mySellbill->sellbillstoreid = $sellbillstoreId;
            $mySellbill->sellbillsysdate = $sellbillDate; //date("Y-m-d H:i:s");
            $mySellbill->sellbilltotalbill = $sellbilltotalBill;
            $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
            $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
            $mySellbill->sellbilltotalpayed = $sellbilltotalPayed;
            $mySellbill->sellerid = $sellerId;
            $mySellbill->userid = $_SESSION['userid'];
            $mySellbill->tempclientName = $tempClientName;
            $mySellbill->sellQuantity = $sellQuantity;
            $mySellbill->tax = $tax;
            $mySellbill->carnumber = $sellbillcarnumber;
            $mySellbill->cartype = $sellbillcartype;
            $mySellbill->carchase = $sellbillcarchase;
            $mySellbill->carmotor = $sellbillcarmotor;
            $mySellbill->dailyentryid = $dailyentryid;
            $mySellbill->delivery = $sellbilldelivery;
            $mySellbill->totalafterdelivery = $totalaafterdelivery;
            $mySellbill->totalprodiscount = $totalprodiscount;
            $mySellbill->manage_ex = $manage_ex;
            $mySellbill->med_hallmark = $med_hallmark;
            $mySellbill->pay_rec_no = $pay_rec_no;
            $mySellbill->pay_rec_val = $pay_rec_val;
            $mySellbill->decisionNo = $decisionNo;
            $mySellbill->decisionValue = $decisionValue;

            //$oldSellBill = $mySellbillRecord->load($oldid);
            $mySellbill->deletedsellid = 0;
            $mySellbill->controlname = $controlname;
            $mySellbill->obygyVisitId = 0;
            $mySellbill->costcenterid = 0;
            $mySellbill->billReservation = $billReservation;
            $mySellbill->billReservationDate = $billReservationDate;
            $mySellbill->comment = $comment;

            $sellbillId = $sellBillOfferEX->insertupdate($mySellbill);

            $detailsArr = array();
            //insert Sell Data into Sellbilldetail tbl
            $sellbillItr = $_POST['hidden_itr'];
            $h = 1;
            for ($h = 1; $h <= $sellbillItr; $h++) {
                ## if input are encoded in json put it again in post
                if (isset($_POST["obj" . $h])) {
                    foreach (json_decode(str_replace("'", '"', $_POST["obj" . $h]), true) as $key => $value) {
                        $_POST[$key . $h] = $value;
                    }
                }
                $parcode = $_POST['parcode' . $h . ''];
                $parcodeType = $_POST['parcodeType' . $h . ''];
                $productserailId = $_POST['productserailid' . $h . ''];
                $productId = $_POST['product' . $h . ''];
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                }
                $productunitId = $_POST['productunit' . $h . ''];
                $quantity = $_POST['pronum' . $h . ''];
                $price = $_POST['proprice' . $h . ''];
                $catdis = $_POST['catdis' . $h . ''];
                $discountValue = $_POST['prodis' . $h . ''];
                $totalPrice = $_POST['hidden_prototal' . $h . ''];
                $comment = $_POST['comment' . $h . ''];
                $prstorid = $_POST['prstorid' . $h . ''];
                $discounttype = $_POST['discounttype' . $h . ''];
                $scunitname = $_POST['scunitname' . $h . ''];
                $pricetypepro = $_POST['pricetypepro' . $h . ''];

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

                    //print_r('in if prstorid'.$prstorid.'<br>');
                    $sellbillstoreId = $prstorid;
                } else {
                    $sellbillstoreId = $_POST['storeid'];
                    //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                }
                if ($productunitId == "") {
                    $productunitId = 0;
                }
                //print_r('the final'.$sellbillstoreId.'<br>');
                if (isset($productId) && $productId != '-1' && $productId != "") {
                    $productData = loadProductById($productId);

                    $mySellbilldetail->buyprice = $productData->productBuyPrice;
                    $mySellbilldetail->discountvalue = $discountValue;
                    $mySellbilldetail->note = $comment;
                    $mySellbilldetail->parcode = $parcode;
                    $mySellbilldetail->pricetype = $priceType;
                    $mySellbilldetail->productunitid = $productunitId;
                    $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                    $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s"); //date("Y-m-d H:i:s");
                    $mySellbilldetail->sellbilldetailprice = $price;
                    $mySellbilldetail->sellbilldetailproductid = $productId;
                    $mySellbilldetail->sellbilldetailquantity = $quantity;
                    $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                    $mySellbilldetail->sellbillid = $sellbillId;
                    $mySellbilldetail->buydiscount = $productData->buydiscount;
                    $mySellbilldetail->buydiscounttype = $productData->discounttype;
                    $mySellbilldetail->storeid = $sellbillstoreId;
                    $mySellbilldetail->discounttype = $discounttype;
                    $mySellbilldetail->otherdetailquantity = $scunitname;
                    $mySellbilldetail->sizeid = $sizeId;
                    $mySellbilldetail->colorid = $colorId;
                    $mySellbilldetail->pricetypepro = $pricetypepro;
                    $mySellbilldetail->scunitqty = 0;
                    $mySellbilldetail->onlineOrderId = 0;
                    $mySellbilldetail->categorydiscount = $catdis;

                    $detailId = $sellBillDetailOfferDAO->insert($mySellbilldetail);
                    array_push($detailsArr, $mySellbilldetail);

                    $taxesitr = $_POST['taxesitr_' . $h . ''];
                    $e = 1;

                    for ($e = 1; $e <= $taxesitr; $e++) {
                        if (!$_POST['type_' . $h . '_' . $e]) {
                            continue;
                        }

                        $sellbilldetailtax = R::dispense('sellbilldetailtax');
                        $sellbilldetailtax->sellbilldetailid = $detailId;
                        $sellbilldetailtax->is_offer = 1; //mean to use sellbilldetailid in sellbilldetailoffer table
                        $sellbilldetailtax->conditions = 0;
                        $sellbilldetailtax->type = $_POST['type_' . $h . '_' . $e];
                        $sellbilldetailtax->subtype = $_POST['subtype_' . $h . '_' . $e];
                        $sellbilldetailtax->rate = $_POST['rate_' . $h . '_' . $e];
                        $sellbilldetailtax->amount = $_POST['amount_' . $h . '_' . $e];
                        R::store($sellbilldetailtax);
                    }

                    if ($productData->isService == 0 && $Programsettingdata->preparingStore != $sellbillstoreId) { //if product && stores are not same
                        $productnumber = (float) $_POST['proNum' . $h];
                        if ($productnumber <= 0) {
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                            $productnumber = $productunitData->productnumber;
                        }
                        $finalquantity = $quantity * $productnumber;


                        /* -- decrease from stroe --------------------------- */
                        //get store productquantity before change
                        $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                        $allStoredetailData = $storedetailData[0];
                        $storedetailId = $storedetailData[1];
                        $productquantityBefore = $storedetailData[2];
                        $billTotalBeforeDiscount = $sellbilltotalBill;
                        $billDiscountVal = 0;

                        //print("qty: ".$finalquantity.'<br>');
                        if (count($allStoredetailData) > 0) {

                            //update productquantity in storedetail
                            $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                            //insert in storereport
                            insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", date("Y-m-d H:i:s"), $sizeId, $colorId);
                        } else {
                            $specialQuantityAfter = $finalquantity * -1;

                            //insert in storedetail tbl
                            insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                            //insert in storereport
                            insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", date("Y-m-d H:i:s"), $sizeId, $colorId);
                        }

                        /* -- increase from stroe --------------------------- */
                        //get storeto productquantity before change
                        $sellbillstoreId = $Programsettingdata->preparingStore;
                        $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);

                        $allStoredetailData = $storedetailData[0];
                        $storedetailId = $storedetailData[1];
                        $productquantityBefore = $storedetailData[2];

                        if (count($allStoredetailData) > 0) {

                            //update productquantity in storedetail
                            $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                            //insert in storereport
                            insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", $sellbillDate, $sizeId, $colorId);
                        } else {
                            //insert in storedetail tbl
                            insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                            //insert in storereport
                            insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", $sellbillDate, $sizeId, $colorId);
                        }
                    }
                }
            }
            doOfferDailyEntry($sellbillId, $mySellbill, $detailsArr);
        }
        if ($_GET['do'] != "update") {
            $mytransactions->commit();
        }
    } catch (Exception $ex) {
        if ($_GET['do'] != "update") {
            $mytransactions->rollback();
            $sellbillclientId = $_POST['supplier'];
            markClientAsNOTInUse($sellbillclientId);
        }
    }

    return array(
        $sellbillId,
        $returnsellbillId,
        $productsBeforeValid,
        $saveValuebeforeValid,
        $billtype,
        $ordertype
    );
}

function showBySriral($serial) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithSerail($serial);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }

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

function showBySellbillId($sellbillId) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithSellbillId($sellbillId);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }

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

function showByDate($startDate, $endDate) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithDate($startDate, $endDate);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }

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

function delete($sellbillid, $savePaymentDateWithBillDate = 0) {
    global $mySellbill;

    global $mySellbillRecord;
    global $mySellbillEx;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    global $soldSerialProductDAO;
    global $soldSerialProductExt;
    global $soldSerialProduct;
    global $myProductserialEx;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;
    global $CostcenterdetailEX;

    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $sellBillOfferDAO;
    global $sellBillDetailOfferDAO;

    global $bankAccountDAO;
    global $bankAccountEX;

    //
    global $sellBillCurr;
    global $sellBillCurrDAO;
    global $sellBillCurrEX;

    global $noOfDecimalPlaces;
    global $sellbillId; //nedded for collective product##fatma
    global $sellbillDate;
    global $ordertype;

    $sellbillId = $sellbillid;

    liveBackupComment("-- bill delete start - sellbill with id = $sellbillid");
    //Transaction
    $mytransactions = new Transaction();

    $dailyentryid = $_GET['action'];
    $ordertype = (int) $_GET['ordertype'];
    try {
        if ($ordertype == 0) { //bill
            $sellbillData = $mySellbillRecord->load($sellbillid);
            if ($sellbillData->conditions == 0) {
                $CostcenterdetailEX->updatedellbytypeandmodelid(0, $sellbillid, 1);

                $dailyentryid = $sellbillData->dailyentryid;
                $sellbilltotalPayed = $sellbillData->sellbilltotalpayed;
                $sellbillstoreId = $sellbillData->sellbillstoreid;
                $sellbilltotaldeptAfter = $sellbillData->sellbilltotaldeptafter;
                $sellbilltotaldeptBefor = $sellbillData->sellbilltotaldeptbefor;
                $sellbillclientId = $sellbillData->sellbillclientid;
                $sellbillFinalbill = $sellbillData->sellbillfinalbill;
                $sellbillsaveId = $sellbillData->sellbillsaveid;
                $currencyId = $sellbillData->currencyId;

                $cash = $sellbillData->cashPayed;
                $visa = $sellbillData->visaPayed;
                $visaAccount = $sellbillData->visaAccountId;
                $isBankAccountTransfer = $sellbillData->isBankAccountTransfer;

                $totalOperationCost = $sellbillData->sellbillaftertotalbill;
                $sellbilltotalBill = $sellbillData->sellbilltotalbill;
                $sellbillDiscount = $sellbillData->sellbilldiscount;
                $sellbillDiscountType = $sellbillData->sellbilldiscounttype;
                $sellbillaftertotalbill = $sellbillData->sellbillaftertotalbill;
                $sellbillDate = $sellbillData->sellbilldate;
                ##get $billTotalBeforeDiscount
                $billTotalBeforeDiscount = $sellbilltotalBill;
                ##get $billDiscountVal
                $billDiscountVal = $sellbillDiscount;
                if ($sellbillDiscountType == "2") {
                    $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
                    $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
                }
                ########################################################################
                $note;
                $saveValuebeforeValid = 1;


                foreach (explode(',', $dailyentryid) as $entryid) {
                    reverseEntryWithItsID($entryid, 1);
                }
                /////////////////check save value before //////////////
                //get save value
                $saveValueBefore = getSaveValueBefore($sellbillsaveId);
                $saveValueafterValid = $saveValueBefore - $sellbilltotalPayed;
                if ($saveValueafterValid >= 0) {
                    $saveValuebeforeValid = 1;

                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "تمت بنجاح";
                    } else {
                        $note = "success";
                    }
                } else {
                    $saveValuebeforeValid = 0;
                    //return $saveValuebeforeValid;
                    if ($_SESSION['erp_lang'] == 'ar') {
                        $note = "لا يوجد بالخزنة المبلغ الكافى لحذف الفاتورة";
                    } else {
                        $note = "There is not enough money in the safe to delete the bill";
                    }
                }

                $mySellbill->conditions = 1;
                $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
                //$mySellbill->userid = $_SESSION['userid'];
                $mySellbill->userid = $sellbillData->userid;
                $mySellbill->delbyuserid = $_SESSION['userid'];
                $mySellbill->sellbillid = $sellbillid;

                $billReservation = $sellbillData->billReservation;
                if (isset($_GET["reservation"]) && (int) $_GET["reservation"] == 4) {
                    $billReservation = 4;
                }

                $mySellbillEx->updateConditions($mySellbill, " ,billReservation= $billReservation,billReservationDate='0000-00-00' ");

                $sellbilldetailData = $mySellbilldetailRecord->queryBySellbillid($sellbillid);

                foreach ($sellbilldetailData as $sellbilldetail) {
                    $sellbillstoreId = $sellbilldetail->storeid;
                    $productId = $sellbilldetail->sellbilldetailproductid;
                    $quantity = $sellbilldetail->sellbilldetailquantity;
                    $productunitId = $sellbilldetail->productunitid;
                    $scunitname = $sellbilldetail->otherdetailquantity;

                    $detailId = $sellbilldetail->sellbilldetailid;
                    $totlPrice = $sellbilldetail->sellbilldetailtotalprice;

                    $sizeId = $sellbilldetail->sizeid;
                    $colorId = $sellbilldetail->colorid;
                    $proSerials = $sellbilldetail->soldSerialsInDetails;

                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);

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

                        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                        $productnumber = $productunitData->productnumber;
                        $finalquantity = $quantity * $productnumber;

                        //
                        decreaseSellQuantityHandleBuyPricesHistoryBook($sellbilldetail->buyPricesHistoryBookIdQuantity);


                        if (!empty($proSerials)) {
                            increaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillid, $sellbillclientId, $detailId, 0, 'del');
                        } else {
                            $parcode = $sellbilldetail->parcode;
                            $issold = $myProductserialEx->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");

                            if (count($issold) > 0) {

                                $soldSerialProduct->quantity = $finalquantity;
                                $soldSerialProduct->sellbilltype = 0;
                                $soldSerialProduct->sellbillid = $sellbillid;
                                $soldSerialProduct->del = 1;
                                $soldSerialProduct->productserailid = $issold->productserailid;

                                //$mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial($soldSerialProduct);
                                $mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial2($soldSerialProduct);
                                //print_r($mysoldSerialProduct);
                                if (count($mysoldSerialProduct) > 0) {

                                    //$soldSerialProductExt->updatedel($soldSerialProduct);
                                    $soldSerialProductExt->updatedel2($soldSerialProduct);
                                    $productserailid = $mysoldSerialProduct->productserailid;

                                    updateSerailQty_ForReturn($productserailid, $finalquantity);
                                }
                            }
                        }


                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get storeto productquantity before change
                            $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totlPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereport($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillid, "حذف فاتورة مبيعات", "sellbillController.php", $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetail($sellbillstoreId, $productId, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereport($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillid, "حذف فاتورة مبيعات", "sellbillController.php", $sizeId, $colorId);
                            }
                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother + $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 0, $sellbillid, "حذف فاتورة مبيعات", "sellbillController.php", date("Y-m-d"), 1);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname), date("Y-m-d"), 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname), 0, $sellbillid, "حذف فاتورة مبيعات", "sellbillController.php", date("Y-m-d"), 1);
                                    }
                                }
                            }
                        }
                    }
                }

                if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                    //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                    //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                    {
                        $clientData = getClientDataFromClientInUseSP($sellbillclientId);
                        //$clientData = loadClientDataById($sellbillclientId);
                        $clientdeptBefor = $clientData->clientdebt;
                        $clientdeptAfter = ($clientData->clientdebt) - $sellbillFinalbill;

                        //update rawmaterialssupplierdebt
                        updateClientDebt($sellbillclientId, $clientdeptAfter);

                        insertClientdebtchange($sellbillclientId, $clientdeptBefor, $sellbillFinalbill, 1, "حذف فاتورة مبيعات", $sellbillid, $clientdeptAfter, "sellbillController.php", "حذف فاتورة مبيعات", $totalOperationCost, $visa, $visaAccount, $cash);
                        markClientAsNOTInUse($sellbillclientId);
                    }
                }

                //check if payed or not to change save value
                $payDateToRecord = date('Y-m-d H:i:s');
                if ($savePaymentDateWithBillDate == 1) {
                    $payDateToRecord = $sellbillDate;
                }
                //1-visa payment
                if ($cash > 0 || ($visa > 0 && $visaAccount > 0)) {
                    $sellbilltotalPayed = $cash;
                    if ($visa != 0 && $visaAccount > 0) {
                        $visaAccountData = $bankAccountDAO->load($visaAccount);
                        if ($isBankAccountTransfer == 1) {
                            $visaDisPerVal = 0;
                        } else {
                            $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                        }
                        $accountBefore = $visaAccountData->accountbeginingbalance;
                        $visaAccountData->accountbeginingbalance = $accountBefore - $visa + $visaDisPerVal;
                        $visaAccountData->accountdate = date('Y-m-d');
                        $visaAccountData->accountid = $visaAccount;
                        $bankAccountEX->updateacount($visaAccountData);

                        //Insert in accountmovement table the payment
                        $afterVal = $accountBefore - $visa;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 1, "الغاء سداد فاتورة", "sellbillController.php", $sellbillid, $payDateToRecord);

                        //Insert in accountmovement table the disount per
                        if ($isBankAccountTransfer != 1) {
                            $afterVal_AfterDisc = $afterVal + $visaDisPerVal;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 0, "الغاء نسبة خصم الفيزا من تحصيل فاتورة", "sellbillController.php", $sellbillid, $payDateToRecord);
                        }
                    }
                }
                //2-cash payment
                if ($sellbilltotalPayed > 0) {
                    ##curr conversion
                    $saveConversionFactor = 0;
                    if ($currencyId > 1) {
                        $billCurrData = $sellBillCurrEX->queryOneBySellbillid($sellbillid);
                        $saveConversionFactor = (float) $billCurrData->saveConversionFactor;
                    }

                    //get saveValue before and saveValue after mins sellbilltotalPayed
                    $saveData = getSaveValueAndMins($sellbillsaveId, $sellbilltotalPayed, $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $sellbilltotalPayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedaily($saveValuebefore, $sellbilltotalPayedSaveCurr, 1, $saveId, "حذف فاتورة مبيعات", $sellbillid, $saveValueafter, "sellbillController.php", $payDateToRecord);
                    unset($_SESSION['client_id']);
                }
                quickProfitBill($sellbilltotalBill, 0, $billDiscountVal, $sellbillclientId, 0);
                writePaymentToRoyalFinancialReport($sellbillclientId, $sellbillid, 0, $sellbilltotalPayed, $visa, $sellbillsaveId, $visaAccount, $sellbillData->obgyBillType, 1, 'del');
            }
        } elseif ($ordertype == 1) { //offer
            $sellBillOfferDAO->delete($sellbillid);
            $sellBillDetailOfferDAO->deleteBySellbillid($sellbillid);
            reverseOfferStoreMovement($sellbillid);
        }
        $mytransactions->commit();
        ##
        delbuyTheSellBill($sellbillData, $ordertype);
        ## also del bill payments
        delSellBillPayments($sellbillid, $ordertype);
        $flag = 1;
    } catch (Exception $e) {
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "حدث خطأ اثناء حذف الفاتورة";
        } else {
            $note = "An error occurred while deleting the invoice";
        }
        $mytransactions->rollback();
        $flag = 2;
        if ($ordertype == 0) { //bill
            $sellbillData = $mySellbillRecord->load($sellbillid);
            $sellbillclientId = $sellbillData->sellbillclientid;
            markClientAsNOTInUse($sellbillclientId);
        }
    }
    liveBackupComment("-- bill delete end - sellbill with id = $sellbillid");
    return array(
        $saveValuebeforeValid,
        $note,
        $flag
    );
}

function executeOperation() {
    //to use the variable out side the funcion
    global $mySellbillRecord;
    global $smarty;
    global $sellbillId; //nedded for collective product##fatma
    $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $sellbillId) {

            //get store name
            $sellbillData = $mySellbillRecord->load($sellbillId);
            $sellbillSerial = $sellbillData->sellbillserial;

            if ($operationType == '1') {
                //tempdelete
                $note = delete($sellbillId);
                if ($note[1] != "success") {
                    $outputString .= $sellbillSerial . ": " . $note[1] . "<br/>";
                } else {
                    $outputString .= $sellbillSerial . ": تمت العملية بنجاح <br/>";
                }
            }
        }

        $smarty->assign("outputString", $outputString);
    }
}

function loadProductCat() {
    global $myProductEx;

    $allParents = $myProductEx->queryAllCategories();

    return $allParents;
}

function loadUnit() {
    global $myUnitRecord;

    $unitsData = $myUnitRecord->queryByCondition(0);
    return $unitsData;
}

////////////////////////////save///////////////////////////
// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid) {

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

    $saveData = $mySaveRecord->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged, $saveConversionFactor = 0) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;
    $saveConversionFactor = 0; //get saveconversion factor from db

    $saveData = getSaveDataFromSaveInUseSP($saveid); //$mySaveEx->loadForUpdateEx($saveid);

    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array(
        $saveId,
        $saveValuebefore,
        $saveValueafter,
        $savevaluechanged,
        $saveConversionFactor
    );
}

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged, $saveConversionFactor = 0) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;
    $saveConversionFactor = 0; //get saveconversion factor from db

    $saveData = getSaveDataFromSaveInUseSP($saveid); //$mySaveEx->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array(
        $saveId,
        $saveValuebefore,
        $saveValueafter,
        $savevaluechanged,
        $saveConversionFactor
    );
}

// update in Save tbl
function updateSave($saveid, $savevalueafter) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    //update initialvalue in Save tbl
    $mySave->savecurrentvalue = $savevalueafter;
    $mySave->userid = $_SESSION['userid'];
    $mySave->saveid = $saveid;

    $mySaveEx->updateSaveValue($mySave);
    markSaveAsNOTInUse($saveid);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename, $theDate) {

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = $theDate;
    $mySavedaily->userid = $_SESSION['userid'];
    $mySavedaily->savedailysavebefore = $savedailysavebefore;
    $mySavedaily->savedailychangeamount = $savedailychangeamount;
    $mySavedaily->savedailychangetype = $savedailychangetype;
    $mySavedaily->saveid = $saveid;
    $mySavedaily->processname = $processname;
    $mySavedaily->savedailymodelid = $savedailymodelid;
    $mySavedaily->savedailysaveafter = $savedailysaveafter;
    $mySavedaily->tablename = $tablename;
    if (isset($_SESSION['client_id']) && !empty($_SESSION['client_id'])) {
        $mySavedaily->clientid = $_SESSION['client_id'];
    } else {
        $mySavedaily->clientid = 0;
    }
    $mySavedailyRecord->insert($mySavedaily);
}

/////////////////////supplier///////////////////////
// update in rawmaterialssuppliers tbl
function updateSupplierDebt($supplierid, $supplierdebtAfter) {

    //to use the variable out side the funcion
    global $myRawmaterialssuppliers;
    global $myRawmaterialssuppliersEx;

    //update rawmaterialssupplierdebt in rawmaterialssuppliers tbl
    $myRawmaterialssuppliers->userid = $_SESSION['userid'];
    $myRawmaterialssuppliers->rawmaterialssupplierdebt = $supplierdebtAfter;
    $myRawmaterialssuppliers->rawmaterialssupplierid = $supplierid;

    $myRawmaterialssuppliersEx->updateSupplierDebt($myRawmaterialssuppliers);
}

/////////////////////////////////store////////////////////////////
// get productquantity from storedetail tbl
function getStoredetailData($storeid, $productid, $sizeColorStoreDetailId) {

    //to use the variable out side the funcion
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;

    $isService = 0;
    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) { //sizecolor product
        $storedetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $storedetailId = $storedetailData->id;
        $productquantityBefore = $storedetailData->quantity;
    } else {

        //select data from storerawmaterialdetails by storeid and rawmaterialid
        $storedetailData = $myStoredetailEx->queryWithStoreAndProduct($productid, $storeid);

        $storedetailId = $storedetailData->storedetailid;
        $productquantityBefore = $storedetailData->productquantity;
        $isService = $storedetailData->isService;
    }

    return array(
        $storedetailData,
        $storedetailId,
        $productquantityBefore,
        $isService
    );
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $colName, $detailId, $productId, $tableName, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $sizeColorStoreDetailId, $sizeId, $colorId) {

    //to use the variable out side the funcion
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;

    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $myStoredetail->storeid;
        $sizeColorStoreDetail->quantity = 0;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }

    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);

        $storeId = $sizecolorstoredetail->storeid;
        $retDataArr = lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $storeId);
        $isCollectiveFlag = $retDataArr['isCollectiveFlag'];

        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, abs($productChangeAmount), 1);
        //affect product to make it have total quantity
        $storeDetailData = $myStoredetailEx->queryWithStoreAndProductandunit($productId, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $productId, $productChangeAmount, $colName, $detailId, $productId, $tableName, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //$myStoredetailEx->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 0);
            $myStoredetailEx->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        $storeId = $myStoredetailEx->getStoreidByStoredetailid($storedetailId);
        $retDataArr = lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $storeId);
        $isCollectiveFlag = $retDataArr['isCollectiveFlag'];

        //update productquantity in storedetail tbl
        if ($isCollectiveFlag == 0) { //not collective affect its store deetail as collective affect ingridients only
            $myStoredetail->storedetailid = $storedetailId;
            $myStoredetail->userid = $_SESSION['userid'];
            $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
            $myStoredetail->productquantity = $productquantityAfter;

            $myStoredetailEx->updateProductquantity($myStoredetail);
            onlineTempStoreDetailFunc($storeId, $productId, 0, 0, abs($productChangeAmount), 1);
        }
    }

    return $productquantityAfter;
}

//update and decrease Rawmaterialamount in storerawmaterialdetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $colName, $detailId, $productId, $tableName, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $sizeColorStoreDetailId, $sizeId, $colorId) {

    //to use the variable out side the funcion
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //increase productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;

    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $myStoredetail->storeid;
        $sizeColorStoreDetail->quantity = 0;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }

    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);

        $storeId = $sizecolorstoredetail->storeid;
        $retDataArr = lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $storeId);
        $isCollectiveFlag = $retDataArr['isCollectiveFlag'];

        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, (abs($productChangeAmount) * -1), 1);
        //affect product to make it have total quantity
        $storeDetailData = $myStoredetailEx->queryWithStoreAndProductandunit($productId, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $productId, $productChangeAmount, $colName, $detailId, $productId, $tableName, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //$myStoredetailEx->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 1);
            $myStoredetailEx->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        $storeId = $myStoredetailEx->getStoreidByStoredetailid($storedetailId);
        $retDataArr = lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $storeId);
        $isCollectiveFlag = $retDataArr['isCollectiveFlag'];

        if ($isCollectiveFlag == 0) { //not collective affect its store deetail as collective affect ingridients only
            //update productquantity in storedetail tbl
            $myStoredetail->storedetailid = $storedetailId;
            $myStoredetail->userid = $_SESSION['userid'];
            $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
            $myStoredetail->productquantity = $productquantityAfter;

            $myStoredetailEx->updateProductquantity($myStoredetail);
            onlineTempStoreDetailFunc($storeId, $productId, 0, 0, (abs($productChangeAmount) * -1), 1);
        }
    }

    return $productquantityAfter;
}

//add in storerawmaterialdetails tbl
function insertStoredetail($storeid, $productid, $productChangeAmount, $colName, $detailId, $productId, $tableName, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $sizeColorStoreDetailId, $sizeId, $colorId) {

    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //increase productquantity
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $storeid;
        $sizeColorStoreDetail->quantity = $productChangeAmount;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }
    $row = $myStoredetailEx->queryByStoreidAndProductid($productid, $storeid);
    if (!isset($row->storedetailid) || $row->storedetailid < 1) {
        $myStoredetail->userid = $_SESSION['userid'];
        $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
        $myStoredetail->productquantity = $productChangeAmount;
        $myStoredetail->storeid = $storeid;
        $myStoredetail->productid = $productid;

        $detailId = $myStoredetailRecord->insert($myStoredetail);
    } else {
        $myStoredetailEx->updateQuantityWithSumChild($row->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $storeid, $productid);
    }
    lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, 0, $productChangeAmount, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $storeid);
}

//add in Storemovement tbl
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $sizeId, $colorId) {
    global $myStorereport;
    global $myStorereportRecord;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = date("Y-m-d H:i:s");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];
    $myStorereport->sizeid = $sizeId;
    $myStorereport->colorid = $colorId;

    $id = $myStorereportRecord->insert($myStorereport);
    $myStorereport->storereportid = $id;
    onlineTempStoreReportFunc($myStorereport);
}

///////////////////////////////////clients//////////////////////
// update in rawmaterialssuppliers tbl
function updateClientDebt($clientid, $clientdebtAfter) {

    //to use the variable out side the funcion
    global $myClient;
    global $myClientEx;

    //update clientdebt in client tbl
    $myClient->userid = $_SESSION['userid'];
    $myClient->clientdebt = $clientdebtAfter;
    $myClient->clientid = $clientid;

    $myClientEx->updateClientdebt($myClient);
}

function updatewebStoreType($sellbillclientId) {
    global $myClientEx;
    $webStoreType = (int) R::getCell('select webStoreType from client where clientid=' . $sellbillclientId);
    if ($webStoreType == 1) {
        $myClientEx->updatewebStoreType(2, $sellbillclientId);
    }
}

// insert data into Clientdebtchange tbl
function insertClientdebtchange($clientid, $clientdebtchangebefore, $clientdebtchangeamount, $clientdebtchangetype, $processname, $clientdebtchangemodelid, $clientdebtchangeafter, $tablename, $comment, $totalOperationCost, $visa = 0, $visaAccount = 0, $cash = 0) {

    //to use the variable out side the funcion
    global $myClientdebtchange;
    global $myClientdebtchangeRecord;
    global $sellbillDate;

    $myClientdebtchange->clientdebtchangeafter = $clientdebtchangeafter;
    $myClientdebtchange->clientdebtchangeamount = $clientdebtchangeamount;
    $myClientdebtchange->clientdebtchangebefore = $clientdebtchangebefore;
    $myClientdebtchange->clientdebtchangedate = date("Y-m-d H:i:s");
    $myClientdebtchange->clientdebtchangemodelid = $clientdebtchangemodelid;
    $myClientdebtchange->clientdebtchangetype = $clientdebtchangetype;
    $myClientdebtchange->clientid = $clientid;
    $myClientdebtchange->comment = $comment;
    if ($visa != 0 && $visaAccount > 0) {
        $processname .= " ( نقدى :$cash, فيزا :$visa )";
    }
    $myClientdebtchange->processname = $processname;
    $myClientdebtchange->tablename = $tablename;
    $myClientdebtchange->userid = $_SESSION['userid'];
    $myClientdebtchange->totalOperationCost = abs($totalOperationCost);
    $myClientdebtchange->dailyentryid = 0;
    $myClientdebtchange->userSelectedDate = $sellbillDate;

    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

function updateSerailDon($productserailid, $don, $billId) {
    global $myProductserial;
    global $myProductserialEx;

    $myProductserial->productserailid = $productserailid;
    $myProductserial->don = $don;
    $myProductserial->sellbillid = $billId;

    $myProductserialEx->updateDonExt($myProductserial);
}

function updateSerailQty($productserailId, $soldQuantity) {
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);
    //    if ($productQuantity > 0) {
    $availableQty = $productQuantity - $soldQuantity;
    //if(isset($availableQty) && $availableQty < 0)
    //          {
    //              //في حالة بيع منتج بكمية أكبر من عدد السريالات
    //          }
    //          else
    //          {
    //
    //          }
    $myProductserial->productserailid = $productserailId;
    $myProductserial->don = $availableQty;
    //print_r($myProductserial);
    $myProductserialEx->updateDon($myProductserial);
    //    }
}

function updateSerailQty_ForReturn($productserailId, $returnedQuantity) {
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);

    //print_r('<br>returnedQuantity'.$returnedQuantity);
    //print_r('<br>productQuantity'.$productQuantity);
    //    if ($productQuantity > 0) {
    $availableQty = $productQuantity + $returnedQuantity;

    //print_r('<br>availableQty'.$availableQty);
    $myProductserial->productserailid = $productserailId;
    $myProductserial->don = $availableQty;
    //print_r('<br>cccccccccccccccccccc'.$productserailId);
    $myProductserialEx->updateDon($myProductserial);
    //    }
}

function insertIntoSoldSerialProduct($productserailId, $soldQuantity, $sellbillId, $sellbilltype, $clientid) {
    global $soldSerialProduct;
    global $soldSerialProductDAO;

    $soldSerialProduct->productserailid = $productserailId;
    $soldSerialProduct->quantity = $soldQuantity;
    $soldSerialProduct->sellbilltype = $sellbilltype;
    $soldSerialProduct->sellbillid = $sellbillId;
    $soldSerialProduct->del = 0;
    $soldSerialProduct->clientid = $clientid;
    //print("<br>");
    //print_r($soldSerialProduct);
    $soldSerialProductDAO->insert($soldSerialProduct);
}

function showDetailreturn($sellbillid) {
    global $mySellbillandruternEx;
    global $mySellandruternbilldetailEx;
    global $sellBillAndRuternCurrEX;

    //load Sellbillandrutern data by id
    $sellbillandruternData = $mySellbillandruternEx->loadSellbillandruternById($sellbillid);
    $billCurrData = $sellBillAndRuternCurrEX->queryOneBySellbillid($sellbillid);

    $sellbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 0);

    $sellQuantity = 0;
    foreach ($sellbilldetailData as $sellbilldetail) {
        $sellQuantity = $sellQuantity + $sellbilldetail->sellbilldetailquantity;
    }

    $ruternbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 1);

    $returnQuantity = 0;
    foreach ($ruternbilldetailData as $ruternbilldetail) {
        $returnQuantity = $returnQuantity + $ruternbilldetail->sellbilldetailquantity;
    }

    /* ##use currency values
      if (isset($billCurrData)) {
      $sellbillandruternData->sellbilldiscount = $billCurrData->sellbilldiscountC;
      $sellbillandruternData->sellbilltotalbill = $billCurrData->sellbilltotalbillC;
      $sellbillandruternData->sellbillaftertotalbill = $billCurrData->sellbillaftertotalbillC;
      $sellbillandruternData->sellbilltotalpayed = $billCurrData->sellbilltotalpayedC;
      $sellbillandruternData->sellbillfinalbill = $billCurrData->sellbillfinalbillC;
      $sellbillandruternData->sellbildirectpayment = $billCurrData->sellbildirectpaymentC;
      $sellbillandruternData->sellbillprice = $billCurrData->sellbillpriceC;
      $sellbillandruternData->returnsellbillprice = $billCurrData->returnsellbillpriceC;
      $sellbillandruternData->cashPayed = $billCurrData->cashPayedC;
      $sellbillandruternData->visaPayed = $billCurrData->visaPayedC;
      $sellbillandruternData->extraDiscountVal = $billCurrData->extraDiscountValC;
      $sellbillandruternData->taxOfDiscountVal = $billCurrData->taxOfDiscountValC;
      ##
      $sellbillandruternData->sellbilltotaldeptbefor = $sellbillandruternData->sellbilltotaldeptbefor * $billCurrData->conversionFactor;
      $sellbillandruternData->sellbilltotaldeptafter = $sellbillandruternData->sellbilltotaldeptafter * $billCurrData->conversionFactor;
      foreach ($sellbilldetailData as $value) {
      $value->sellbilldetailprice = $value->sellbilldetailpriceC;
      $value->sellbilldetailtotalprice = $value->sellbilldetailtotalpriceC;
      $value->discountvalue = $value->discountvalueC;
      }
      foreach ($ruternbilldetailData as $value) {
      $value->sellbilldetailprice = $value->sellbilldetailpriceC;
      $value->sellbilldetailtotalprice = $value->sellbilldetailtotalpriceC;
      $value->discountvalue = $value->discountvalueC;
      }
      } */

    return array(
        $sellbillandruternData,
        $sellbilldetailData,
        $ruternbilldetailData,
        $sellQuantity,
        $returnQuantity,
        $billCurrData
    );
}

function addtocostcenter($costamount, $costcenterid, $modelid, $processname, $tablename, $type) {

    $Costcenterdetail->costamount = $costamount;
    $Costcenterdetail->costcenterid = $costcenterid;
    $Costcenterdetail->costdate = date('Y-m-d');
    $Costcenterdetail->del = 0;
    $Costcenterdetail->modelid = $modelid;
    $Costcenterdetail->processname = $processname;
    $Costcenterdetail->tablename = $tablename;
    $Costcenterdetail->type = $type;
    $Costcenterdetail->uesrid = $_SESSION['userid'];

    if ($Costcenterid != -1 && $Costcenterid != '-1') {
        $CostcenterdetailDAO->insert($Costcenterdetail);
    }
}

function lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $isreturn, $isadd, $storeId) {

    global $productDAO;
    global $buyBillDetailExt;
    global $sellbillId; //nedded for collective product##fatma
    global $ordertype;

    if ($ordertype == 0) {
        ##the differance
        ## use $buyProduct->lastbuyprice and $buyProduct->meanbuyprice and put them in sell table
        $buyProduct = new Product();

        ##1- get mean
        $buyProduct = $productDAO->load($productId);
        if ($buyProduct->meanbuyprice == NULL || $buyProduct->meanbuyprice == 0) {
            $buyProduct->meanbuyprice = $buyProduct->productBuyPrice;
        }
        if ($buyProduct->lastbuyprice == NULL || $buyProduct->lastbuyprice == 0) {
            $buyProduct->lastbuyprice = $buyProduct->productBuyPrice;
        }
        if ($buyProduct->lastbuyprice_withDiscount == NULL || $buyProduct->lastbuyprice_withDiscount == 0) {
            $buyProduct->lastbuyprice_withDiscount = $buyProduct->productBuyPrice;
        }
        if ($buyProduct->meanbuyprice_withDiscount == NULL || $buyProduct->meanbuyprice_withDiscount == 0) {
            $buyProduct->meanbuyprice_withDiscount = $buyProduct->productBuyPrice;
        }
        if (empty($buyProduct->overAllAveragePrice) || $buyProduct->overAllAveragePrice === NULL) {
            $buyProduct->overAllAveragePrice = $buyProduct->productBuyPrice;
        }
        $buyProduct = ifCollectiveProductReCalculateCost($buyProduct);
        if (isset($detailId) && !empty($detailId)) {
            $buyBillDetailExt->updatePrices_f($tableName, $buyProduct->lastbuyprice, $buyProduct->meanbuyprice, $buyProduct->lastbuyprice_withDiscount, $buyProduct->meanbuyprice_withDiscount, (float) $buyProduct->lastbuyprice_withTax, (float) $buyProduct->meanbuyprice_withTax, (float) $buyProduct->lastbuyprice_withDiscountAndTax, $colName, $detailId);
        }
        quickProfitRow($buyProduct, $productChangeAmount, $isreturn, $isadd, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $storeId);
        if ($isreturn == 0 && $isadd == 0) {
            //ret sell - increase
            $isCollectiveFlag = ifCollectiveIncreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $storeId, $tableName);
        } elseif ($isreturn == 0 && $isadd == 1) {
            //sell - decrease
            $isCollectiveFlag = ifCollectiveDecreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $storeId, $tableName);
        } elseif ($isreturn == 1 && $isadd == 0) {
            //sell - decrease
            $isCollectiveFlag = ifCollectiveDecreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $storeId, $tableName);
        } elseif ($isreturn == 1 && $isadd == 1) {
            //ret sell - increase
            $isCollectiveFlag = ifCollectiveIncreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $storeId, $tableName);
        }
        return array('isCollectiveFlag' => $isCollectiveFlag);
    }
}

function quickProfitRow($myproduct, $finalQuantity, $isreturn, $isadd, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $storeId) {
    //$isreturn = 1 is return part ,0 is sell part
    //$isadd = 1 is add ,0 is del
    global $quickProfitStoreEX;
    global $quickProfitProductEX;
    global $sellCostsArray;
    $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
    $obj->productId = $myproduct->productId;
    $obj->theDate = date('Y-m-d'); //date("Y-m-d", strtotime("+1 day"));
    if ($isreturn == 0) {
        $obj->sellVal = $prototalWithDiscount;
        $obj->sellCostBuyPrice = $myproduct->productBuyPrice * $finalQuantity;
        $obj->sellCostLastBuyPrice = $myproduct->lastbuyprice * $finalQuantity;
        $obj->sellCostMeanBuyPrice = $myproduct->meanbuyprice * $finalQuantity;
        $obj->sellCostLastBuyPricewithDiscount = $myproduct->lastbuyprice_withDiscount * $finalQuantity;
        $obj->sellCostMeanBuyPricewithDiscount = $myproduct->meanbuyprice_withDiscount * $finalQuantity;
        $obj->sellCostOverAllAveragePrice = $myproduct->overAllAveragePrice * $finalQuantity;
        $obj->sellCostLastBuyPricewithTax = $myproduct->lastbuyprice_withTax * $finalQuantity;
        $obj->sellCostMeanBuyPricewithTax = $myproduct->meanbuyprice_withTax * $finalQuantity;
        $obj->sellCostLastBuyPricewithDiscountAndTax = $myproduct->lastbuyprice_withDiscountAndTax * $finalQuantity;
        $obj->returnSellVal = 0;
        $obj->returnSellCostBuyPrice = 0;
        $obj->returnSellCostLastBuyPrice = 0;
        $obj->returnSellCostMeanBuyPrice = 0;
        $obj->returnSellCostLastBuyPricewithDiscount = 0;
        $obj->returnSellCostMeanBuyPricewithDiscount = 0;
        $obj->returnSellCostOverAllAveragePrice = 0;
        $obj->returnSellCostLastBuyPricewithTax = 0;
        $obj->returnSellCostLastBuyPricewithDiscountAndTax = 0;
        $obj->returnSellCostMeanBuyPricewithTax = 0;
        $obj->netQuantity = $finalQuantity;
        $obj->netQuantityRet = 0;
    } elseif ($isreturn == 1) {
        $obj->sellVal = 0;
        $obj->sellCostBuyPrice = 0;
        $obj->sellCostLastBuyPrice = 0;
        $obj->sellCostMeanBuyPrice = 0;
        $obj->sellCostLastBuyPricewithDiscount = 0;
        $obj->sellCostLastBuyPricewithDiscountAndTax = 0;
        $obj->sellCostMeanBuyPricewithDiscount = 0;
        $obj->sellCostOverAllAveragePrice = 0;
        $obj->sellCostLastBuyPricewithTax = 0;
        $obj->sellCostMeanBuyPricewithTax = 0;
        $obj->returnSellVal = $prototalWithDiscount;
        $obj->returnSellCostBuyPrice = $myproduct->productBuyPrice * $finalQuantity;
        $obj->returnSellCostLastBuyPrice = $myproduct->lastbuyprice * $finalQuantity;
        $obj->returnSellCostMeanBuyPrice = $myproduct->meanbuyprice * $finalQuantity;
        $obj->returnSellCostLastBuyPricewithDiscount = $myproduct->lastbuyprice_withDiscount * $finalQuantity;
        $obj->returnSellCostMeanBuyPricewithDiscount = $myproduct->meanbuyprice_withDiscount * $finalQuantity;
        $obj->returnSellCostOverAllAveragePrice = $myproduct->overAllAveragePrice * $finalQuantity;
        $obj->returnSellCostLastBuyPricewithTax = $myproduct->lastbuyprice_withTax * $finalQuantity;
        $obj->returnSellCostMeanBuyPricewithTax = $myproduct->meanbuyprice_withTax * $finalQuantity;
        $obj->returnSellCostLastBuyPricewithDiscountAndTax = $myproduct->lastbuyprice_withDiscountAndTax * $finalQuantity;
        $obj->netQuantity = 0;
        $obj->netQuantityRet = $finalQuantity;
    }

    $obj->storeId = $storeId;
    if ($isadd == 1) {
        $quickProfitProductEX->insertOrUpdatePlusEX($obj);
        $quickProfitStoreEX->insertOrUpdatePlusEX($obj);
    } else {
        $quickProfitProductEX->insertOrUpdateMinusEX($obj);
        $quickProfitStoreEX->insertOrUpdateMinusEX($obj);
    }
    //for totals
    $sellCostsArray["sellCostBuyPrice"] += $obj->sellCostBuyPrice;
    $sellCostsArray["sellCostLastBuyPrice"] += $obj->sellCostLastBuyPrice;
    $sellCostsArray["sellCostMeanBuyPrice"] += $obj->sellCostMeanBuyPrice;
    $sellCostsArray["sellCostLastBuyPricewithDiscount"] += $obj->sellCostLastBuyPricewithDiscount;
    $sellCostsArray["sellCostMeanBuyPricewithDiscount"] += $obj->sellCostMeanBuyPricewithDiscount;
    $sellCostsArray["sellCostOverAllAveragePrice"] += $obj->sellCostOverAllAveragePrice;
    $sellCostsArray["sellCostLastBuyPricewithTax"] += $obj->sellCostLastBuyPricewithTax;
    $sellCostsArray["sellCostMeanBuyPricewithTax"] += $obj->sellCostMeanBuyPricewithTax;
    $sellCostsArray["returnSellCostBuyPrice"] += $obj->returnSellCostBuyPrice;
    $sellCostsArray["returnSellCostLastBuyPrice"] += $obj->returnSellCostLastBuyPrice;
    $sellCostsArray["returnSellCostMeanBuyPrice"] += $obj->returnSellCostMeanBuyPrice;
    $sellCostsArray["returnSellCostLastBuyPricewithDiscount"] += $obj->returnSellCostLastBuyPricewithDiscount;
    $sellCostsArray["returnSellCostMeanBuyPricewithDiscount"] += $obj->returnSellCostMeanBuyPricewithDiscount;
    $sellCostsArray["returnSellCostOverAllAveragePrice"] += $obj->returnSellCostOverAllAveragePrice;
    $sellCostsArray["returnSellCostLastBuyPricewithTax"] += $obj->returnSellCostLastBuyPricewithTax;
    $sellCostsArray["returnSellCostMeanBuyPricewithTax"] += $obj->returnSellCostMeanBuyPricewithTax;
}

function quickProfitBill($sellbillPrice, $returnsellbillPrice, $billDiscountVal, $clientId, $isadd) {
    //$isadd = 1 is add ,0 is del
    global $quickProfitDayEX;
    global $quickProfitClientEX;
    global $quickProfitGeneralEX;
    global $sellCostsArray;
    //
    $obj->theDate = date('Y-m-d'); //date("Y-m-d", strtotime("+1 day"));
    $obj->sellVal = abs($sellbillPrice);
    $obj->returnSellVal = abs($returnsellbillPrice);
    if ($obj->sellVal >= $obj->returnSellVal) {
        $obj->sellVal = $obj->sellVal - $billDiscountVal;
    } else {
        $obj->returnSellVal = $obj->returnSellVal - $billDiscountVal;
    }

    $obj->sellCostBuyPrice = (float) $sellCostsArray["sellCostBuyPrice"];
    $obj->sellCostLastBuyPrice = (float) $sellCostsArray["sellCostLastBuyPrice"];
    $obj->sellCostMeanBuyPrice = (float) $sellCostsArray["sellCostMeanBuyPrice"];
    $obj->sellCostLastBuyPricewithDiscount = (float) $sellCostsArray["sellCostLastBuyPricewithDiscount"];
    $obj->sellCostMeanBuyPricewithDiscount = (float) $sellCostsArray["sellCostMeanBuyPricewithDiscount"];
    $obj->sellCostOverAllAveragePrice = (float) $sellCostsArray["sellCostOverAllAveragePrice"];
    $obj->sellCostLastBuyPricewithTax = (float) $sellCostsArray["sellCostLastBuyPricewithTax"];
    $obj->sellCostMeanBuyPricewithTax = (float) $sellCostsArray["sellCostMeanBuyPricewithTax"];
    $obj->returnSellCostBuyPrice = (float) $sellCostsArray["returnSellCostBuyPrice"];
    $obj->returnSellCostLastBuyPrice = (float) $sellCostsArray["returnSellCostLastBuyPrice"];
    $obj->returnSellCostMeanBuyPrice = (float) $sellCostsArray["returnSellCostMeanBuyPrice"];
    $obj->returnSellCostLastBuyPricewithDiscount = (float) $sellCostsArray["returnSellCostLastBuyPricewithDiscount"];
    $obj->returnSellCostMeanBuyPricewithDiscount = (float) $sellCostsArray["returnSellCostMeanBuyPricewithDiscount"];
    $obj->returnSellCostOverAllAveragePrice = (float) $sellCostsArray["returnSellCostOverAllAveragePrice"];
    $obj->returnSellCostLastBuyPricewithTax = (float) $sellCostsArray["returnSellCostLastBuyPricewithTax"];
    $obj->returnSellCostMeanBuyPricewithTax = (float) $sellCostsArray["returnSellCostMeanBuyPricewithTax"];
    $obj->clientId = $clientId;

    //quickProfitGeneral
    $objGeneral->netSellVal = $obj->sellVal - $obj->returnSellVal;
    $objGeneral->netSellCostBuyPrice = $obj->sellCostBuyPrice - $obj->returnSellCostBuyPrice;
    $objGeneral->netSellCostLastBuyPrice = $obj->sellCostLastBuyPrice - $obj->returnSellCostLastBuyPrice;
    $objGeneral->netSellCostMeanBuyPrice = $obj->sellCostMeanBuyPrice - $obj->returnSellCostMeanBuyPrice;
    $objGeneral->netSellCostLastBuyPricewithDiscount = $obj->sellCostLastBuyPricewithDiscount - $obj->returnSellCostLastBuyPricewithDiscount;
    $objGeneral->netSellCostMeanBuyPricewithDiscount = $obj->sellCostMeanBuyPricewithDiscount - $obj->returnSellCostMeanBuyPricewithDiscount;
    $objGeneral->netSellCostOverAllAveragePrice = $obj->sellCostOverAllAveragePrice - $obj->returnSellCostOverAllAveragePrice;
    $objGeneral->netSellCostLastBuyPricewithTax = $obj->sellCostLastBuyPricewithTax - $obj->returnSellCostLastBuyPricewithTax;
    $objGeneral->netSellCostMeanBuyPricewithTax = $obj->sellCostMeanBuyPricewithTax - $obj->returnSellCostMeanBuyPricewithTax;
    if ($isadd == 1) {
        $quickProfitDayEX->insertOrUpdatePlusEX($obj);
        $quickProfitClientEX->insertOrUpdatePlusEX($obj);
        $quickProfitGeneralEX->insertOrUpdatePlusEX($objGeneral);
    } else {
        $quickProfitDayEX->insertOrUpdateMinusEX($obj);
        $quickProfitClientEX->insertOrUpdateMinusEX($obj);
        $quickProfitGeneralEX->insertOrUpdateMinusEX($objGeneral);
    }
}

function getCategoryChilds($parentid = 0) {
    global $productCatExt;
    global $productCatDAO;
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid);

    return array(
        $parentobject,
        $childsArray
    );
}

function getStoreDetails($storeId, $productId, $unittype, $sizeColorStoreDetailId, $sizeId, $colorId) {
    // get productquantity from storedetail tbl
    global $StoredetailEX;

    global $sizeColorStoreDetailDAO;

    if ((isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) || ($sizeId > 0 && $colorId > 0)) { //sizecolor product
        if ((!isset($sizeColorStoreDetailId) || empty($sizeColorStoreDetailId)) && ($sizeId > 0 && $colorId > 0)) {
            $storeDetailId = 0;
            $productQuantityBefore = 0;
        } else {
            $storeDetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
            $storeDetailId = $storeDetailData->id;
            $productQuantityBefore = $storeDetailData->quantity;
        }
    } else {

        //select data from storedetails by storeid and productid
        $storeDetailData = $StoredetailEX->queryWithStoreAndProductandunit($productId, $storeId, $unittype);

        $storeDetailId = $storeDetailData->storedetailid;
        $productQuantityBefore = $storeDetailData->productquantity;
    }
    return array(
        $storeDetailData,
        $storeDetailId,
        $productQuantityBefore
    );
}

function getNextIdStoreMovement() {
    global $myStoremovementEx;
    $nextId = $myStoremovementEx->queryAlloperationnum();
    $last_val = $nextId[0];
    $last = $last_val->operationnum + 1;
    return $last;
}

function moveProductFromStoreToAnother($productId, $transferproductAmount, $storeidfrom, $storeidto, $operationnum) {
    global $myStoremovementRecord;

    //add in storemovement tbl
    $myStoremovement->conditions = 0;
    $myStoremovement->storeidfrom = $storeidfrom;
    $myStoremovement->storeidto = $storeidto;
    $myStoremovement->transferproductdate = date("Y-m-d");
    $myStoremovement->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoremovement->productid = $productId;
    $myStoremovement->transferproductamount = $transferproductAmount;
    $myStoremovement->operationnum = $operationnum;
    $myStoremovement->storetype = 0; //#تحويل بين المخازن
    if (isset($productId) && $productId != '-1') {
        //insert data in stormovement
        $transferproductId = $myStoremovementRecord->insert($myStoremovement);

        //////////////**Store From**///////////////////////////
        //get storefrom productquantity before change
        $storedetailFromData = getStoredetailData($storeidfrom, $productId, 0);

        $allStoredetailFromData = $storedetailFromData[0];
        $storedetailFromId = $storedetailFromData[1];
        $productquantityFromBefore = $storedetailFromData[2];

        //update productquantity in storedetail
        $productquantityFromAfter = decreaseProductQuantityOnly($storedetailFromId, $productquantityFromBefore, $transferproductAmount);

        //insert in storereport
        insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 1, $transferproductId, "تحويل منتجات من المخزن", "storemovementController.php");

        //////////////**Store To**///////////////////////////
        //get storeto productquantity before change
        $storedetailToData = getStoredetailData($storeidto, $productId, 0);

        $allStoredetailToData = $storedetailToData[0];
        $storedetailToId = $storedetailToData[1];
        $productquantityToBefore = $storedetailToData[2];

        if (count($allStoredetailToData) > 0) {

            //update productquantity in storedetail
            $productquantityToAfter = increaseProductQuantityOnly($storedetailToId, $productquantityToBefore, $transferproductAmount);

            //insert in storereport
            insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php");
        } else {
            //insert in storedetail tbl
            insertStoredetailOnly($storeidto, $productId, $transferproductAmount);

            //insert in storereport
            insertStorereport($productId, $storeidto, $transferproductAmount, 0, $transferproductAmount, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php");
        }
    }
}

// add restaurant bill in sellbill tbl
function addRestaurantBill($restaurantOrder, $restaurantOrderDetails) {
    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    //Temsellbill
    global $Temsellbill;
    global $TemsellbillDAO;
    //Temsellbilldetail
    global $Temsellbilldetail;
    global $TemsellbilldetailDAO;

    global $ProductunitDAO;
    global $Productunit;
    global $myProductunitEx;

    global $myClientRecord;
    global $userDAO;
    global $myStoreRecord;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    global $dailyEntryDebtor2;
    global $dailyEntryDebtorDAO2;

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

    global $accountsTreeDAO;
    global $accountsTree;

    global $mySave;
    global $mySaveRecord;

    global $myBillsettingEx;
    global $myProductRecord;

    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $ProgramsettingDAO;
    global $Programsettingdata;
    global $sellbillId; //nedded for collective product##fatma
    global $noOfDecimalPlaces;
    global $sellCostsArray;

    $billnameId = 3; //$_POST['billnameid'];
    $sellbillclientId = 1; //$_POST['supplier'];
    if ($restaurantOrder->tableId == -2 || $restaurantOrder->tableId == -1 || $Programsettingdata->clientShowTawla == 1) {
        if (isset($_POST["client"]) && !empty($_POST["client"])) {
            $sellbillclientId = $_POST["client"];
        }
    }

    $sellbilltotaldeptBefor = 0;
    $sellbilltotaldeptAfter = 0;
    //$tax = 0;
    $thereIsRestTax = (int) $_POST["thereIsRestTax"];
    if ($thereIsRestTax == 1) {
        $restTaxVal = (float) $_POST["restTaxVal_hidden"]; //this is value but it is needed as percentage
        $restTaxVal = ($restTaxVal / ((float) $_POST['netBill_hidden'] - $restTaxVal)) * 100;
        $restTaxVal = round($restTaxVal, 2);
    } else {
        $restTaxVal = 0;
    }

    $sellbillcarnumber = '';
    $sellbillcartype = '';
    $sellbillcarchase = '';
    $sellbillcarmotor = '';

    $Costcenterid = -1;
    $billReservation = (int) $_POST["billReservation"];
    $billReservationDate = $_POST["billReservationDate"];

    $clientdata = getClientDataFromClientInUseSP($sellbillclientId);
    //$clientdata = $myClientRecord->load($sellbillclientId);
    $tempClientName = $_POST['tempclientName'] = $clientName = $clientdata->clientname;
    //client
    $sellbildirectPayment = 0;
    //Date
    $sellbillDate = date('Y-m-d H:i:s'); // $restaurantOrder->sysdate;
    //Store "of user"
    $userdata = $userDAO->load($_SESSION['userid']);
    $sellbillstoreId = $userdata->userstoreid;
    //store of restaurant
    //    $ProgramsettingData = $ProgramsettingDAO->load(1);
    //    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    //    $sellbillstoreId = $ProgramsettingData->restaurantStoreId;
    if ($sellbillstoreId == 0) {
        //user has all stores
        //choose first store
        $sellbillstoreId = 1;
    }
    //seller
    $sellerId = 0;

    $comment = '';

    $sellbillSerial = uniqid("0");
    //$priceType = $_POST['hiddenpricetype'];
    $priceType = (int) $restaurantOrder->hallPrice;

    $sellbilltotalBill = (float) $_POST['totalBill_hidden']; //اجمالى الفاتورة قبل الخصم
    $sellbillDiscountType = 0; //نوع الخصم
    $sellbillDiscount = (float) $_POST['discount']; //قيمة الخصم
    $sellbillAftertotalBill = (float) $_POST['netBill_hidden']; //القيمة بعد الخصم
    $sellbilltotalPayed = (float) $_POST['payed']; //المدفوع
    $sellbillFinalbill = $sellbillAftertotalBill - $sellbilltotalPayed; //المتبقى
    $sellbillPrice = (float) $_POST['netBill_hidden']; //اجمالى المبيعات
    $returnsellbillPrice = 0; //اجمالى مردودات المبيعات
    /////////////////
    $sellQuantity = (float) $_POST['totalQuantity'];
    $returnsellQuantity = 0;

    $sellbilltotaldeptBefor = $clientdata->clientdebt; //$_POST['hidden_debt'];
    $gen4totalinput = 0; //$_POST["gen4totalinput"];
    $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + ($sellbillAftertotalBill - $sellbilltotalPayed);
    $sellbillaftertotalbill = $billTotalBeforeDiscount;
    ##get $billTotalBeforeDiscount
    $billTotalBeforeDiscount = $sellbilltotalBill;
    ##get $billDiscountVal
    $billDiscountVal = $sellbillDiscount;
    if ($sellbillDiscountType == "2") {
        $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
        $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
    }
    ########################################################################
    //////////////////////////////////////////////////////////////////////////
    $productsBeforeValid = 1;
    $saveValuebeforeValid = 1;
    /* ----------------------------- */
    $sellbillId;
    $returnsellbillId;
    $billtype;
    /* ------------------------ */

    if ($billnameId != 11) {
        //check storerdetail value
        //check product quantity
        if ($sellbillPrice >= 0) {
            foreach ($restaurantOrderDetails as $resDetail) {
                $productId = $resDetail->productId;
                $productQuantity = $resDetail->quantity;
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                }
                if (isset($productId) && $productId != '-1' && $productId != "") {

                    //get storefrom productquantity before change
                    $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                    $allStoredetailData = $storedetailData[0];
                    $storedetailId = $storedetailData[1];
                    $productquantityBefore = $storedetailData[2];
                    $isService = (int) $storedetailData[3];

                    //check if productquantityFromBefore greater than 0 or not
                    if ($isService == 0) { //product
                        $productsBeforeValid = 1;
                        if ($productquantityBefore > 0 && count($allStoredetailData) > 0) {
                            $productsAfterValid = $productquantityBefore - $productQuantity;

                            if ($productsAfterValid >= 0) {
                                $productsBeforeValid = 1;
                            } else {
                                $productsBeforeValid = 0;
                                //return $productsBeforeValid;
                            }
                        } else {
                            $productsBeforeValid = 0;
                            //return $productsBeforeValid;
                        }
                    } else {
                        //service
                        $productsBeforeValid = 1;
                    }
                }
            }
        }

        //use it if value of bill is 0 only
        $bill_is = 'sell';
        //مبيعات
        //insert data into Sellbill tbl
        if (($sellbillPrice > 0 && $returnsellbillPrice <= 0) || $bill_is == 'sell') {
            $billtype = 1; //مبيعات


            $mySellbill->billnameid = $billnameId;
            $mySellbill->conditions = 0;
            $mySellbill->sellbildirectpayment = $sellbildirectPayment;
            $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
            $mySellbill->sellbillclientid = $sellbillclientId;
            $mySellbill->sellbillclientname = $clientName;
            $mySellbill->sellbilldate = $sellbillDate;
            $mySellbill->sellbilldiscount = $sellbillDiscount;
            $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
            $mySellbill->sellbillfinalbill = $sellbillFinalbill;
            $mySellbill->sellbillsaveid = $_SESSION['saveid'];
            $mySellbill->sellbillserial = $sellbillSerial;
            $mySellbill->sellbillstoreid = $sellbillstoreId;
            $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
            $mySellbill->sellbilltotalbill = $sellbilltotalBill;
            $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
            $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
            $mySellbill->sellbilltotalpayed = $sellbilltotalPayed;
            $mySellbill->sellerid = $sellerId;
            $mySellbill->userid = $_SESSION['userid'];
            $mySellbill->tempclientName = $tempClientName;
            $mySellbill->sellQuantity = $sellQuantity;
            $mySellbill->tax = $restTaxVal;
            $mySellbill->carnumber = $sellbillcarnumber;
            $mySellbill->cartype = $sellbillcartype;
            $mySellbill->carchase = $sellbillcarchase;
            $mySellbill->carmotor = $sellbillcarmotor;
            $mySellbill->costcenterid = $Costcenterid;
            $mySellbill->dailyentryid = 0;
            $mySellbill->comment = $comment;
            $mySellbill->billReservation = $billReservation;
            $mySellbill->billReservationDate = $billReservationDate;

            $sellbillId = $mySellbillRecord->insert($mySellbill);

            if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                {

                    //update rawmaterialssupplierdebt
                    updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                    insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات", $sellbillId, $sellbilltotaldeptAfter, "sellbillController.php", "اضافة فاتورة مبيعات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), 0, 0, $sellbilltotalPayed);
                    markClientAsNOTInUse($sellbillclientId);
                }
            }

            $Costcenterdetail->costamount = $sellbillAftertotalBill;
            $Costcenterdetail->costcenterid = $Costcenterid;
            $Costcenterdetail->costdate = date('Y-m-d');
            $Costcenterdetail->del = 0;
            $Costcenterdetail->modelid = $sellbillId;
            $Costcenterdetail->processname = 'فاتوره مبيعات';
            $Costcenterdetail->tablename = 'sellbillController.php';
            $Costcenterdetail->type = '0';
            $Costcenterdetail->uesrid = $_SESSION['userid'];

            if ($Costcenterid != -1 && $Costcenterid != '-1') {
                $CostcenterdetailDAO->insert($Costcenterdetail);
            }

            //insert Sell Data into Sellbilldetail tbl
            foreach ($restaurantOrderDetails as $orderDetail) {
                if (isset($productId) && $productId != '-1' && $productId != "") {
                    //
                    $productData = $myProductRecord->load($orderDetail->productId);
                    $parcode = $productData->parcode;
                    $parcodeType = 'parcode';
                    $productserailId = 0; //$_POST['productserailid' . $h . ''];
                    $productId = $orderDetail->productId;
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $Productunit = $myProductunitEx->getfirstunittWithProductNumberEQ1($productId);
                    if (count($Productunit) < 1) {
                        $Productunit->productunitid = 1;
                    }
                    $productunitId = $Productunit->productunitid; //$_POST['productunit' . $h . ''];
                    $quantity = $orderDetail->quantity;
                    $price = $orderDetail->price;
                    $discountValue = 0;
                    $totalPrice = $orderDetail->quantity * $orderDetail->price;
                    $comment = '';
                    $prstorid = 0;
                    $discounttype = 0;
                    $scunitname = 0;
                    //
                    $sellbillstoreId = $sellbillstoreId;
                    if ($productunitId == "") {
                        $productunitId = 0;
                    }

                    // $mySellbilldetail->buyprice = $productData->productBuyPrice;
                    $mySellbilldetail->buyprice = $productData->productBuyPrice;

                    $mySellbilldetail->discountvalue = $discountValue;
                    $mySellbilldetail->note = $comment;
                    $mySellbilldetail->parcode = $parcode;
                    $mySellbilldetail->pricetype = $priceType;
                    $mySellbilldetail->productunitid = $productunitId;
                    $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                    $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                    $mySellbilldetail->sellbilldetailprice = $price;
                    $mySellbilldetail->sellbilldetailproductid = $productId;
                    $mySellbilldetail->sellbilldetailquantity = $quantity;
                    $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                    $mySellbilldetail->sellbillid = $sellbillId;
                    $mySellbilldetail->buydiscount = $productData->buydiscount;
                    $mySellbilldetail->buydiscounttype = $productData->discounttype;
                    $mySellbilldetail->storeid = $sellbillstoreId;
                    $mySellbilldetail->discounttype = $discounttype;
                    $mySellbilldetail->otherdetailquantity = $scunitname;
                    $mySellbilldetail->buydiscount = 0;
                    $mySellbilldetail->buydiscounttype = 0;
                    $mySellbilldetail->pricetype = $priceType;
                    $mySellbilldetail->sizeid = $sizeId;
                    $mySellbilldetail->colorid = $colorId;

                    $detailId = $mySellbilldetailRecord->insert($mySellbilldetail);
                    //print("qty: ".$quantity.'<br>');
                    //print("<br>productserailId: ".$productserailId);
                    //update DON if is Serial
                    $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                    //print_r($productunitData);
                    $productnumber = $productunitData->productnumber;
                    $finalquantity = $quantity * $productnumber;
                    /*  print("productnumber: ".$productnumber.'<br>');
                      print("quantity: ".$quantity.'<br>');
                      print("finalquantity: ".$finalquantity.'<br>'); */
                    if ($parcodeType == "serialnumber") {
                        //print("<br>serialnumber<br>");
                        //updateSerailDon($productserailId, 1, $sellbillId);
                        updateSerailQty($productserailId, $finalquantity);
                        insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 0, $sellbillclientId);
                    }

                    $isService = isService($productId);
                    if ($isService == 0) { //if product
                        //get store productquantity before change
                        $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                        $allStoredetailData = $storedetailData[0];
                        $storedetailId = $storedetailData[1];
                        $productquantityBefore = $storedetailData[2];

                        //print("qty: ".$finalquantity.'<br>');
                        if (count($allStoredetailData) > 0) {

                            //update productquantity in storedetail
                            $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                            //insert in storereport
                            insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                        } else {
                            $specialQuantityAfter = $finalquantity * -1;

                            //insert in storedetail tbl
                            insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                            //insert in storereport
                            insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                        }

                        //other unit
                        if ($scunitname > 0) {
                            $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];

                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                $finalquantityother = $productQuantityBeforeother - $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname) * -1, date("Y-m-d H:i:s"), 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname) * -1, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                }
                            }
                        }
                    }
                }
            }

            //check if payed or not to change save value
            if ($sellbilltotalPayed > 0) {
                //get saveValue before and saveValue after Plus lPayed
                $saveData = getSaveValueAndPlus($_SESSION['saveid'], $sellbilltotalPayed);
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

                //update save value after add sellbill
                updateSave($saveId, $saveValueafter);

                //insert into savedaily tbl from save
                $_SESSION['client_id'] = $sellbillclientId;
                insertSavedailyupdate($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "اضافة فاتورة مبيعات", $sellbillId, $saveValueafter, "sellbillController.php", date("Y-m-d H:i:s"));
                unset($_SESSION['client_id']);
            }
        }
    }

    /* ---------------------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------- بداية القيود اليومية ------------------------------------------------------ */
    //var_dump($restTaxVal);
    ##there is problem in tax calculation
    doBillDailyEntry($billtype, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $saveId, 0, 0, $sellbillFinalbill, $clientdata->treeId, 0, $billDiscountVal, $sellbilltotalBill, $sellbillAftertotalBill, $restTaxVal, $sellCostsArray, $sellbillstoreId);


    quickProfitBill($sellbilltotalBill, 0, $billDiscountVal, $sellbillclientId, 1);
    return array(
        $sellbillId,
        $returnsellbillId,
        $productsBeforeValid,
        $saveValuebeforeValid,
        $billtype
    );
}

function addOnlineOrderAsSellBill($onlineOrderId, $onlineStoreId, $clientChoosen, $onlineStoreSetting) {
    global $onlineTempOrder;
    global $onlineTempOrderDAO;
    global $onlineTempOrderProduct;
    global $onlineTempOrderProductDAO;

    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    //Temsellbill
    global $Temsellbill;
    global $TemsellbillDAO;
    //Temsellbilldetail
    global $Temsellbilldetail;
    global $TemsellbilldetailDAO;

    global $ProductunitDAO;
    global $Productunit;
    global $myProductunitEx;

    global $myClientRecord;
    global $userDAO;
    global $myStoreRecord;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    global $dailyEntryDebtor2;
    global $dailyEntryDebtorDAO2;

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

    global $accountsTreeDAO;
    global $accountsTree;

    global $mySave;
    global $mySaveRecord;

    global $myBillsettingEx;
    global $myProductRecord;

    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $ProgramsettingDAO;
    global $sellbillId; //nedded for collective product##fatma
    global $onlineTempOrderClient;
    global $onlineTempOrderClientDAO;

    global $noOfDecimalPlaces;
    global $sellCostsArray;
    //Transaction
    $mytransactions = new Transaction();
    try {
        $onlineTempOrder = $onlineTempOrderDAO->queryByOnlineorderid($onlineOrderId);
        $onlineTempOrderProducts = $onlineTempOrderProductDAO->queryByOrderid($onlineTempOrder->onlineorderid);
        $onlineTempOrderClient = $onlineTempOrderClientDAO->queryByOrderid($onlineTempOrder->onlineorderid);
        //handle client first
        $clientId = getclientId($onlineTempOrderClient, $clientChoosen, $onlineStoreSetting);

        $orderPrice = $onlineTempOrder->fulltotal;

        $billnameId = 3; //$_POST['billnameid'];
        $sellbillclientId = $clientId;

        $sellbilltotaldeptBefor = 0;
        $sellbilltotaldeptAfter = 0;
        //$tax = 0;
        $thereIsRestTax = $onlineTempOrder->tax_value;

        $sellbillcarnumber = '';
        $sellbillcartype = '';
        $sellbillcarchase = '';
        $sellbillcarmotor = '';

        $Costcenterid = -1;
        $billReservation = (int) $_POST["billReservation"];
        $billReservationDate = $_POST["billReservationDate"];

        $clientdata = getClientDataFromClientInUseSP($sellbillclientId);
        //$clientdata = $myClientRecord->load($sellbillclientId);
        $tempClientName = $_POST['tempclientName'] = $clientName = $clientdata->clientname;
        //client
        $sellbildirectPayment = 0;
        //Date
        $sellbillDate = $onlineTempOrder->createdatetime;
        //Store
        //        $userdata = $userDAO->load($_SESSION['userid']);
        //        $sellbillstoreId = $userdata->userstoreid;
        $ProgramsettingData = $ProgramsettingDAO->load(1);
        $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
        $sellbillstoreId = $onlineStoreId;

        //seller
        $sellerId = 0;

        $comment = '';

        $sellbillSerial = uniqid("0");
        //$priceType = $_POST['hiddenpricetype'];
        $priceType = 1;

        $sellbilltotalBill = $orderPrice; //اجمالى الفاتورة قبل الخصم
        $sellbillDiscountType = 0; //نوع الخصم
        $sellbillDiscount = 0; //قيمة الخصم
        $sellbillAftertotalBill = $orderPrice; //القيمة بعد الخصم
        $sellbilltotalPayed = 0; //المدفوع
        $sellbillFinalbill = $orderPrice; //$sellbillAftertotalBill - $sellbilltotalPayed; //المتبقى
        $sellbillPrice = $orderPrice; //اجمالى المبيعات
        $returnsellbillPrice = 0; //اجمالى مردودات المبيعات
        $totalprodiscount = 0; // خصومات المنتج
        $manage_ex = 0;
        $med_hallmark = 0;
        $pay_rec_no = 0;
        $pay_rec_val = 0;
        /////////////////
        $sellQuantity = (float) $_POST['totalQuantity']; //later
        $returnsellQuantity = 0;

        $sellbilltotaldeptBefor = $clientdata->clientdebt; //$_POST['hidden_debt'];
        $gen4totalinput = $orderPrice; //$_POST["gen4totalinput"];//المتبقى
        $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + $gen4totalinput;

        ##get $billTotalBeforeDiscount
        $billTotalBeforeDiscount = $sellbilltotalBill;
        ##get $billDiscountVal
        $billDiscountVal = $sellbillDiscount;
        if ($sellbillDiscountType == "2") {
            $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
            $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
        }
        ########################################################################
        //////////////////////////////////////////////////////////////////////////
        $productsBeforeValid = 1;
        $saveValuebeforeValid = 1;
        /* ----------------------------- */
        $sellbillId;
        $returnsellbillId;
        $billtype;
        /* ------------------------ */

        if ($billnameId != 11) {
            //check storerdetail value
            //check product quantity
            if ($sellbillPrice >= 0) {
                foreach ($onlineTempOrderProducts as $aProduct) {
                    $productId = $aProduct->productid;
                    $productQuantity = $aProduct->quantity;
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    if (isset($productId) && $productId != '-1' && $productId != "") {

                        //get storefrom productquantity before change
                        $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

                        $allStoredetailData = $storedetailData[0];
                        $storedetailId = $storedetailData[1];
                        $productquantityBefore = $storedetailData[2];
                        $isService = (int) $storedetailData[3];

                        //check if productquantityFromBefore greater than 0 or not
                        if ($isService == 0) { //product
                            $productsBeforeValid = 1;
                            if ($productquantityBefore > 0 && count($allStoredetailData) > 0) {
                                $productsAfterValid = $productquantityBefore - $productQuantity;

                                if ($productsAfterValid >= 0) {
                                    $productsBeforeValid = 1;
                                } else {
                                    $productsBeforeValid = 0;
                                    //return $productsBeforeValid;
                                }
                            } else {
                                $productsBeforeValid = 0;
                                //return $productsBeforeValid;
                            }
                        } else {
                            //service
                            $productsBeforeValid = 1;
                        }
                    }
                }
            }

            //use it if value of bill is 0 only
            $bill_is = 'sell';
            //مبيعات
            //insert data into Sellbill tbl
            if (($sellbillPrice > 0 && $returnsellbillPrice <= 0) || $bill_is == 'sell') {
                $billtype = 1; //مبيعات


                $mySellbill->billnameid = $billnameId;
                $mySellbill->conditions = 0;
                $mySellbill->sellbildirectpayment = $sellbildirectPayment;
                $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
                $mySellbill->sellbillclientid = $sellbillclientId;
                $mySellbill->sellbillclientname = $clientName;
                $mySellbill->sellbilldate = $sellbillDate;
                $mySellbill->sellbilldiscount = $sellbillDiscount;
                $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
                $mySellbill->sellbillfinalbill = $sellbillFinalbill;
                $mySellbill->sellbillsaveid = isset($_SESSION['saveid']) ? $_SESSION['saveid'] : 1;
                $mySellbill->sellbillserial = $sellbillSerial;
                $mySellbill->sellbillstoreid = $sellbillstoreId;
                $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
                $mySellbill->sellbilltotalbill = $sellbilltotalBill;
                $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
                $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                $mySellbill->sellbilltotalpayed = $sellbilltotalPayed;
                $mySellbill->sellerid = $sellerId;
                $mySellbill->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
                $mySellbill->tempclientName = $tempClientName;
                $mySellbill->sellQuantity = $sellQuantity;
                $mySellbill->tax = $restTaxVal;
                $mySellbill->carnumber = $sellbillcarnumber;
                $mySellbill->cartype = $sellbillcartype;
                $mySellbill->carchase = $sellbillcarchase;
                $mySellbill->carmotor = $sellbillcarmotor;
                $mySellbill->costcenterid = $Costcenterid;
                $mySellbill->dailyentryid = 0;
                $mySellbill->comment = $comment;
                $mySellbill->onlineOrderId = $onlineOrderId; //for shop 2
                $mySellbill->billReservation = $billReservation;
                $mySellbill->billReservationDate = $billReservationDate;
                $mySellbill->totalprodiscount = $totalprodiscount;
                $mySellbill->manage_ex = $manage_ex;
                $mySellbill->med_hallmark = $med_hallmark;
                $mySellbill->pay_rec_no = $pay_rec_no;
                $mySellbill->pay_rec_val = $pay_rec_val;
                $mySellbill->decisionNo = $decisionNo;
                $mySellbill->decisionValue = $decisionValue;

                $sellbillId = $mySellbillRecord->insert($mySellbill);

                if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                    //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                    //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                    {

                        //update rawmaterialssupplierdebt
                        updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                        insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات", $sellbillId, $sellbilltotaldeptAfter, "sellbillController.php", "اضافة فاتورة مبيعات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), 0, 0, $sellbilltotalPayed);
                        markClientAsNOTInUse($sellbillclientId);
                    }
                }

                $Costcenterdetail->costamount = $sellbillAftertotalBill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $sellbillId;
                $Costcenterdetail->processname = 'فاتوره مبيعات';
                $Costcenterdetail->tablename = 'sellbillController.php';
                $Costcenterdetail->type = '0';
                $Costcenterdetail->uesrid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }

                //insert Sell Data into Sellbilldetail tbl
                foreach ($onlineTempOrderProducts as $aProduct) {
                    $productId = $aProduct->productid;
                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        //
                        $productData = $myProductRecord->load($productId);
                        $parcode = $productData->parcode;
                        $parcodeType = 'parcode';
                        $productserailId = 0; //$_POST['productserailid' . $h . ''];
                        $productId = $aProduct->productid;
                        $sizeId = 0;
                        $colorId = 0;
                        $sizeColorStoreDetailId = 0;
                        if (strpos($productId, "hasSizeColor") !== false) {
                            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                            $productId = $productIdComplex[0];
                            $sizeId = $productIdComplex[1];
                            $colorId = $productIdComplex[2];
                            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                        }
                        $Productunit = $myProductunitEx->getfirstunittWithProductNumberEQ1($productId);
                        if (count($Productunit) < 1) {
                            $Productunit->productunitid = 1;
                        }
                        $productunitId = $Productunit->productunitid; //$_POST['productunit' . $h . ''];
                        $quantity = $aProduct->quantity;
                        $price = $aProduct->price;
                        $discountValue = 0;
                        $totalPrice = $quantity * $price;
                        $comment = '';
                        $prstorid = 0;
                        $discounttype = 0;
                        $scunitname = 0;
                        //
                        $sellbillstoreId = $sellbillstoreId;
                        if ($productunitId == "") {
                            $productunitId = 0;
                        }

                        // $mySellbilldetail->buyprice = $productData->productBuyPrice;
                        $mySellbilldetail->buyprice = $productData->productBuyPrice;

                        $mySellbilldetail->discountvalue = $discountValue;
                        $mySellbilldetail->note = $comment;
                        $mySellbilldetail->parcode = $parcode;
                        $mySellbilldetail->pricetype = $priceType;
                        $mySellbilldetail->productunitid = $productunitId;
                        $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                        $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                        $mySellbilldetail->sellbilldetailprice = $price;
                        $mySellbilldetail->sellbilldetailproductid = $productId;
                        $mySellbilldetail->sellbilldetailquantity = $quantity;
                        $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                        $mySellbilldetail->sellbillid = $sellbillId;
                        $mySellbilldetail->buydiscount = $productData->buydiscount;
                        $mySellbilldetail->buydiscounttype = $productData->discounttype;
                        $mySellbilldetail->storeid = $sellbillstoreId;
                        $mySellbilldetail->discounttype = $discounttype;
                        $mySellbilldetail->otherdetailquantity = $scunitname;
                        $mySellbilldetail->buydiscount = 0;
                        $mySellbilldetail->buydiscounttype = 0;
                        $mySellbilldetail->pricetype = $priceType;
                        $mySellbilldetail->sizeid = $sizeId;
                        $mySellbilldetail->colorid = $colorId;
                        $mySellbilldetail->onlineOrderId = $onlineOrderId; //for shop 2
                        $detailId = $mySellbilldetailRecord->insert($mySellbilldetail);
                        //print("qty: ".$quantity.'<br>');
                        //print("<br>productserailId: ".$productserailId);
                        //update DON if is Serial
                        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                        //print_r($productunitData);
                        $productnumber = $productunitData->productnumber;
                        $finalquantity = $quantity * $productnumber;
                        /*  print("productnumber: ".$productnumber.'<br>');
                          print("quantity: ".$quantity.'<br>');
                          print("finalquantity: ".$finalquantity.'<br>'); */
                        if ($parcodeType == "serialnumber") {
                            //print("<br>serialnumber<br>");
                            //updateSerailDon($productserailId, 1, $sellbillId);
                            updateSerailQty($productserailId, $finalquantity);
                            insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 0, $sellbillclientId);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get store productquantity before change
                            $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            //print("qty: ".$finalquantity.'<br>');
                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            } else {
                                $specialQuantityAfter = $finalquantity * -1;

                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            }

                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother - $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname) * -1, date("Y-m-d H:i:s"), 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname) * -1, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                    }
                                }
                            }
                        }
                    }
                }

                //check if payed or not to change save value
                if ($sellbilltotalPayed > 0) {
                    //get saveValue before and saveValue after Plus lPayed
                    $saveData = getSaveValueAndPlus($_SESSION['saveid'], $sellbilltotalPayed);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update save value after add sellbill
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from save
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedailyupdate($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "اضافة فاتورة مبيعات", $sellbillId, $saveValueafter, "sellbillController.php", date("Y-m-d H:i:s"));
                    unset($_SESSION['client_id']);
                }
            }
        }

        /* ---------------------------------------------------------------------------------------------------------- */
        /* ---------------------------------------------------- بداية القيود اليومية ------------------------------------------------------ */

        doBillDailyEntry($billtype, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $saveId, 0, 0, $gen4totalinput, $clientdata->treeId, 0, $billDiscountVal, $sellbilltotalBill, $sellbillAftertotalBill, $taxVal, $sellCostsArray, $sellbillstoreId);

        quickProfitBill($sellbilltotalBill, 0, $billDiscountVal, $sellbillclientId, 1);
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $clientId = getclientId($onlineTempOrderClient, $clientChoosen, $onlineStoreSetting);
        $sellbillclientId = $clientId;
        markClientAsNOTInUse($sellbillclientId);
    }
    return array(
        $sellbillId,
        $returnsellbillId,
        $productsBeforeValid,
        $saveValuebeforeValid,
        $billtype
    );
}

function getclientId($client_data, $clientChoosen, $onlineStoreSetting) {
    global $client;
    global $clientDAO;
    global $clientEX;
    global $clientDeptChangeDAO;

    $clientid = (int) $client_data->erpid;
    if ($clientid < 1) {
        if ($clientChoosen > 0) {
            //choose existing client
            $clientid = $clientChoosen;
        } else {
            //insert new client
            $clientdebt = $client_data->clientdebt;
            //save new client
            $client->clientname = $client_data->clientname;
            $client->clientcode = $client_data->clientcode;
            $client->clientmobile = $client_data->clientmobile;
            $client->clientdebt = $client_data->clientdebt;
            $client->clientaddress = $client_data->clientaddress;

            $client->clientphone = '';
            $client->clientdetails = '';
            $client->conditions = 0;
            $client->clientdate = date('Y-m-d');
            $client->userid = 1;
            $client->branchId = 0;
            $client->clientareaid = $onlineStoreSetting->onlineclientareaid;
            $client->dailyentryid = 0;
            $client->rondomtxt = '';
            $client->clientStoreIds = -1; //later
            $client->obygyPatientId = 0;
            $client->debtLimit = 0;

            $clientid = $clientDAO->insert($client);

            if (!empty($clientid)) {
                //insert into clientdeptchange
                $clientDeptChange->clientdebtchangeafter = $clientdebt;
                $clientDeptChange->clientdebtchangeamount = $clientdebt;
                $clientDeptChange->totalOperationCost = $clientdebt;
                $clientDeptChange->clientdebtchangebefore = 0;
                $clientDeptChange->clientdebtchangedate = date('Y-m-d H:i:s');
                $clientDeptChange->clientdebtchangemodelid = $clientid;
                $clientDeptChange->clientdebtchangetype = 0;
                $clientDeptChange->clientid = $clientid;
                $clientDeptChange->comment = "";
                $clientDeptChange->processname = "إضافة عميل جديد";
                $clientDeptChange->tablename = "clientController.php";
                $clientDeptChange->userid = 1; //$clientareaid;
                $clientDeptChange->clientareaid = 1; //$_SESSION['userid'];
                $clientDeptChange->dailyentryid = 0;
                $clientDeptChangeDAO->insert($clientDeptChange);
            }
        }
        //save client erpid in shop"online"
        $allclients = $clientEX->queryAllOrderedLimitedSimpleForCurlNormal(0, 1, ' and clientid =  ' . $clientid);
        $allclients[0]->onlineid = $client_data->customer_id;
        CURL_IT($allclients, $onlineStoreSetting->url . '/api_erp/updateClientErpidCURL');
    }
    return $clientid;
}

// add addObgyVisit bill in sellbill tbl
function addObgyVisit($oldid) {
    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;
    global $mySellbillEx;


    global $myReturnsellbillRecord;
    global $myReturnsellbilldetailRecord;

    //Temsellbill
    global $Temsellbill;
    global $TemsellbillDAO;
    //Temsellbilldetail
    global $Temsellbilldetail;
    global $TemsellbilldetailDAO;

    global $ProductunitDAO;
    global $Productunit;
    global $myProductunitEx;

    global $myClientRecord;
    global $userDAO;
    global $myStoreRecord;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    global $dailyEntryDebtor2;
    global $dailyEntryDebtorDAO2;

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

    global $accountsTreeDAO;
    global $accountsTree;

    global $mySave;
    global $mySaveRecord;

    global $myBillsettingEx;
    global $myProductRecord;

    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $bankAccountEX;
    global $bankAccountDAO;
    global $bankAccount;

    global $clientEX;

    global $ProgramsettingDAO;
    global $sellbillId; //nedded for collective product##fatma
    global $noOfDecimalPlaces;
    global $sellCostsArray;

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

        $isRefund = (int) $_POST['isRefund'];
        $obygyVisitId = $_POST['visitId'];
        $cash = (float) $_POST['cash'];
        $visa = (float) $_POST['visa'];
        $visaAccount = (int) $_POST['visaAccount'];
        $isBankAccountTransfer = (int) $_POST['isBankAccountTransfer'];
        ;
        $billnameId = 3; //$_POST['billnameid'];
        $sellbillclientId = $_POST['supplier'];

        $sellbilltotaldeptBefor = 0;
        $sellbilltotaldeptAfter = 0;
        $tax = 0;

        $sellbillcarnumber = '';
        $sellbillcartype = '';
        $sellbillcarchase = '';
        $sellbillcarmotor = '';

        $Costcenterid = -1;
        //        $billReservation = (int) $_POST["billReservation"];
        //        $billReservationDate = $_POST["billReservationDate"];
        $clientdata = getClientDataFromClientInUseSP($sellbillclientId);
        //$clientdata = $myClientRecord->load($sellbillclientId);
        $tempClientName = $_POST['tempclientName'] = $clientName = $clientdata->clientname;
        //client
        $sellbildirectPayment = 0;
        //Date
        $sellbillDate = $_POST['bn'] . ' ' . date("H:i:s");
        //Store
        //        $userdata = $userDAO->load($_SESSION['userid']);
        //        $sellbillstoreId = $userdata->userstoreid;
        $sellbillstoreId = 1;
        //seller
        $sellerId = (int) $_POST['sellerid'];

        $comment = isset($_POST['for_department']) ? $_POST['for_department'] : '';

        $sellbillSerial = uniqid("0");
        //$priceType = $_POST['hiddenpricetype'];
        $priceType = 0; //$restaurantOrder->hallPrice;
        $sellbilltotalBill = (float) $_POST['totalBill_hidden']; //اجمالى الفاتورة قبل الخصم
        if ($isRefund == 1) { //it is return sell bill
            $sellbilltotalBill = $cash + $visa;
        }
        $sellbillDiscountType = 1; //نوع الخصم
        $sellbillDiscount = (float) $_POST['discount']; //قيمة الخصم
        $sellbillAftertotalBill = $sellbilltotalBill - $sellbillDiscount; //(float) $_POST['netBill_hidden']; //القيمة بعد الخصم
        if ($cash > 0 || ($visa > 0 && $visaAccount > 0)) {
            $sellbilltotalPayed = $cash + $visa; //المدفوع
        }
        //        else {
        //            $sellbilltotalPayed = $sellbillAftertotalBill; //المدفوع
        //        }
        $sellbillFinalbill = $sellbillAftertotalBill - $sellbilltotalPayed; //المتبقى
        $sellbillPrice = (float) $_POST['netBill_hidden']; //اجمالى المبيعات
        $returnsellbillPrice = 0; //اجمالى مردودات المبيعات
        /////////////////
        $sellQuantity = $returnsellQuantity = (float) $_POST['totalQuantity'];
        $totalprodiscount = (float) $_POST['totalProDis']; //قيمة الخصم
        $manage_ex = (float) $_POST['manage_ex'];
        $med_hallmark = (float) $_POST['med_hallmark'];
        $pay_rec_no = (float) $_POST['pay_rec_no'];
        $pay_rec_val = (float) $_POST['pay_rec_val'];
        $decisionNo = (float) $_POST['decisionNo'];
        $decisionValue = (float) $_POST['decisionValue'];

        $sellbilltotaldeptBefor = $clientdata->clientdebt; //$_POST['hidden_debt'];
        $gen4totalinput = $sellbillAftertotalBill - $sellbilltotalPayed; //$_POST["gen4totalinput"];


        $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + $gen4totalinput;
        ##get $billTotalBeforeDiscount
        $billTotalBeforeDiscount = $sellbilltotalBill;
        ##get $billDiscountVal
        $billDiscountVal = $sellbillDiscount;
        if ($sellbillDiscountType == "2") {
            $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
            $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
        }
        ########################################################################
        //////////////////////////////////////////////////////////////////////////
        $productsBeforeValid = 1;
        $saveValuebeforeValid = 1;
        /* ----------------------------- */
        $sellbillId;
        $returnsellbillId;
        $billtype;
        /* ------------------------ */

        if ($billnameId != 11) {
            //check storerdetail value
            //check product quantity ## no as obgy coming is service "has no quantity"
            //use it if value of bill is 0 only
            $bill_is = 'sell';
            if ($isRefund == 1) {
                $bill_is = 'ret';
                $billnameId = 5;
            }
            //مبيعات
            //insert data into Sellbill tbl
            //($sellbillPrice > 0 && $returnsellbillPrice <= 0) ||
            if ($bill_is == 'sell') {
                $billtype = 1; //مبيعات


                $mySellbill->billnameid = $billnameId;
                $mySellbill->conditions = 0;
                $mySellbill->sellbildirectpayment = $sellbildirectPayment;
                $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
                $mySellbill->sellbillclientid = $sellbillclientId;
                $mySellbill->sellbillclientname = $clientName;
                $mySellbill->sellbilldate = $sellbillDate;
                $mySellbill->sellbilldiscount = $sellbillDiscount;
                $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
                $mySellbill->sellbillfinalbill = $sellbillFinalbill;
                $mySellbill->sellbillsaveid = $_SESSION['saveid'];
                $mySellbill->sellbillserial = $sellbillSerial;
                $mySellbill->sellbillstoreid = $sellbillstoreId;
                $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
                $mySellbill->sellbilltotalbill = $sellbilltotalBill;
                $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
                $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                $mySellbill->sellbilltotalpayed = $sellbilltotalPayed;
                $mySellbill->sellerid = $sellerId;
                $mySellbill->userid = $_SESSION['userid'];
                $mySellbill->tempclientName = $tempClientName;
                $mySellbill->sellQuantity = $sellQuantity;
                $mySellbill->tax = $tax;
                $mySellbill->carnumber = $sellbillcarnumber;
                $mySellbill->cartype = $sellbillcartype;
                $mySellbill->carchase = $sellbillcarchase;
                $mySellbill->carmotor = $sellbillcarmotor;
                $mySellbill->costcenterid = $Costcenterid;
                $mySellbill->cashPayed = $cash;
                $mySellbill->visaPayed = $visa;
                $mySellbill->visaAccountId = $visaAccount;
                $mySellbill->isBankAccountTransfer = $isBankAccountTransfer;
                $mySellbill->dailyentryid = 0;
                $mySellbill->comment = $comment;
                $mySellbill->obgyBillType = 3; //(int) $_POST['obgyBillType'];
                $mySellbill->billoperationid = (int) $_POST['billoperationid'];
                $mySellbill->obygyVisitId = $obygyVisitId;
                $mySellbill->deletedsellid = (int) $oldid;
                $mySellbill->controlname = "sellbillController";
                $mySellbill->totalprodiscount = $totalprodiscount;
                $mySellbill->manage_ex = $manage_ex;
                $mySellbill->med_hallmark = $med_hallmark;
                $mySellbill->pay_rec_no = $pay_rec_no;
                $mySellbill->pay_rec_val = $pay_rec_val;
                $mySellbill->decisionNo = $decisionNo;
                $mySellbill->decisionValue = $decisionValue;
                $mySellbill->sellbilltypeclientid = (int) $_POST['sellbilltypeclientid'];

                $sellbillId = $mySellbillEx->insertupdate($mySellbill);

                if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                    //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                    //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                    {

                        //update rawmaterialssupplierdebt
                        updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                        insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات", $sellbillId, $sellbilltotaldeptAfter, "sellbillController.php", "اضافة فاتورة مبيعات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, ($sellbilltotalPayed - $visa));
                        markClientAsNOTInUse($sellbillclientId);
                    }
                }

                $Costcenterdetail->costamount = $sellbillAftertotalBill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $sellbillId;
                $Costcenterdetail->processname = 'فاتوره مبيعات';
                $Costcenterdetail->tablename = 'sellbillController.php';
                $Costcenterdetail->type = '0';
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }

                //insert Sell Data into Sellbilldetail tbl
                $sellbillItr = $_POST['hidden_itr'];
                $h = 1;
                for ($h = 1; $h <= $sellbillItr; $h++) {
                    $productId = $_POST["productid" . $h];
                    $price = $_POST["price" . $h];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }

                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        //
                        $productData = $myProductRecord->load($productId);
                        $parcode = $productData->parcode;
                        $parcodeType = 'parcode';
                        $productserailId = 0; //$_POST['productserailid' . $h . ''];
                        $Productunit = $myProductunitEx->getfirstunittWithProductNumberEQ1($productId);
                        if (count($Productunit) < 1) {
                            $Productunit->productunitid = 1;
                        }
                        $productunitId = $Productunit->productunitid; //$_POST['productunit' . $h . ''];
                        $quantity = 1; //$orderDetail->quantity;
                        $discountValue = 0;
                        $totalPrice = $price * $quantity;
                        $comment = '';
                        $prstorid = 0;
                        $discounttype = 0;
                        $scunitname = 0;
                        //
                        $sellbillstoreId = $sellbillstoreId;
                        if ($productunitId == "") {
                            $productunitId = 0;
                        }

                        // $mySellbilldetail->buyprice = $productData->productBuyPrice;
                        $mySellbilldetail->buyprice = $productData->productBuyPrice;

                        $mySellbilldetail->discountvalue = $discountValue;
                        $mySellbilldetail->note = $comment;
                        $mySellbilldetail->parcode = $parcode;
                        $mySellbilldetail->pricetype = $priceType;
                        $mySellbilldetail->productunitid = $productunitId;
                        $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                        $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                        $mySellbilldetail->sellbilldetailprice = $price;
                        $mySellbilldetail->sellbilldetailproductid = $productId;
                        $mySellbilldetail->sellbilldetailquantity = $quantity;
                        $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                        $mySellbilldetail->sellbillid = $sellbillId;
                        $mySellbilldetail->buydiscount = $productData->buydiscount;
                        $mySellbilldetail->buydiscounttype = $productData->discounttype;
                        $mySellbilldetail->storeid = $sellbillstoreId;
                        $mySellbilldetail->discounttype = $discounttype;
                        $mySellbilldetail->otherdetailquantity = $scunitname;
                        $mySellbilldetail->buydiscount = 0;
                        $mySellbilldetail->buydiscounttype = 0;
                        $mySellbilldetail->sizeid = $sizeId;
                        $mySellbilldetail->colorid = $colorId;

                        $detailId = $mySellbilldetailRecord->insert($mySellbilldetail);
                        //print("qty: ".$quantity.'<br>');
                        //print("<br>productserailId: ".$productserailId);
                        //update DON if is Serial
                        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                        //print_r($productunitData);
                        $productnumber = $productunitData->productnumber;
                        $finalquantity = $quantity * $productnumber;
                        /*  print("productnumber: ".$productnumber.'<br>');
                          print("quantity: ".$quantity.'<br>');
                          print("finalquantity: ".$finalquantity.'<br>'); */
                        if ($parcodeType == "serialnumber") {
                            //print("<br>serialnumber<br>");
                            //updateSerailDon($productserailId, 1, $sellbillId);
                            updateSerailQty($productserailId, $finalquantity);
                            insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 0, $sellbillclientId);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get store productquantity before change
                            $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            //print("qty: ".$finalquantity.'<br>');
                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            } else {
                                $specialQuantityAfter = $finalquantity * -1;

                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            }

                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother - $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname) * -1, date("Y-m-d H:i:s"), 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname) * -1, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", date("Y-m-d H:i:s"), 1);
                                    }
                                }
                            }
                        }
                    }
                }

                //check if payed or not to change save value
                //1-visa payment
                if ($cash > 0 || ($visa > 0 && $visaAccount > 0)) {
                    $sellbilltotalPayed = $cash;
                    if ($visa != 0 && $visaAccount > 0) {
                        $visaAccountData = $bankAccountDAO->load($visaAccount);
                        if ($isBankAccountTransfer == 1) {
                            $visaDisPerVal = 0;
                        } else {
                            $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                        }
                        $accountBefore = $visaAccountData->accountbeginingbalance;
                        $visaAccountData->accountbeginingbalance = $accountBefore + $visa - $visaDisPerVal;
                        $visaAccountData->accountdate = date('Y-m-d');
                        $visaAccountData->accountid = $visaAccount;
                        $bankAccountEX->updateacount($visaAccountData);

                        //Insert in accountmovement table the payment
                        $afterVal = $accountBefore + $visa;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 0, "سداد فاتورة", "sellbillController.php", $sellbillId, $sellbillDate);

                        //Insert in accountmovement table the disount per
                        if ($isBankAccountTransfer != 1) {
                            $afterVal_AfterDisc = $afterVal - $visaDisPerVal;
                            insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 1, "نسبة خصم الفيزا من تحصيل فاتورة", "sellbillController.php", $sellbillId, $sellbillDate);
                        }
                    }
                }
                //2-cash payment
                if ($sellbilltotalPayed > 0) {
                    //get saveValue before and saveValue after Plus lPayed
                    $saveData = getSaveValueAndPlus($_SESSION['saveid'], $sellbilltotalPayed);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update save value after add sellbill
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from save
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedailyupdate($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "اضافة فاتورة مبيعات", $sellbillId, $saveValueafter, "sellbillController.php", $sellbillDate); //date("Y-m-d H:i:s")
                    unset($_SESSION['client_id']);
                }
            }
            //مردودات مبيعات//Refund
            //insert data into returnSellbill tbl
            //($sellbillPrice <= 0 && $returnsellbillPrice > 0) ||
            elseif ($bill_is == 'ret') {
                $billtype = 2; //مردودات مبيعات
                $sellBill = $mySellbillEx->loadByObygyVisitId($obygyVisitId);
                if (empty($sellBill->sellerid))
                    $sellBill->sellerid = (int) $_POST['sellerid'];
                if (empty($sellBill->sellQuantity))
                    $sellBill->sellQuantity = (float) $returnsellQuantity;

                $sellbillDetails = $mySellbilldetailRecord->queryBySellbillid($sellBill->sellbillid);

                $sellbilltotalPayed = $sellbilltotalPayed - $visa;


                $sellbillFinalbill = $sellbillAftertotalBill - abs($sellbilltotalPayed) - abs($visa);
                $gen4totalinput = $sellbillAftertotalBill - abs($sellbilltotalPayed) - abs($visa);
                $sellbilltotaldeptAfter = $sellbilltotaldeptBefor - $gen4totalinput;


                $myReturnsellbill->billnameid = $billnameId;
                $myReturnsellbill->conditions = 0;
                $myReturnsellbill->returnsellbildirectpayment = 1; //$sellbildirectPayment;
                $myReturnsellbill->returnsellbillaftertotalbill = $sellbillAftertotalBill;
                $myReturnsellbill->returnsellbillclientid = $sellbillclientId;
                $myReturnsellbill->returnsellbillclientname = $clientName;
                $myReturnsellbill->returnsellbilldate = $sellbillDate;
                $myReturnsellbill->returnsellbilldiscount = $sellbillDiscount;
                $myReturnsellbill->returnsellbilldiscounttype = $sellbillDiscountType;
                $myReturnsellbill->returnsellbillfinalbill = abs($sellbillFinalbill) * -1;
                $myReturnsellbill->returnsellbillsaveid = $_SESSION['saveid'];
                $myReturnsellbill->returnsellbillserial = $sellbillSerial;
                $myReturnsellbill->returnsellbillstoreid = $sellbillstoreId;
                $myReturnsellbill->returnsellbillsysdate = date("Y-m-d H:i:s");
                $myReturnsellbill->returnsellbilltotalbill = $sellbilltotalBill;
                $myReturnsellbill->returnsellbilltotaldeptafter = $sellbilltotaldeptAfter;
                $myReturnsellbill->returnsellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                $myReturnsellbill->returnsellbilltotalpayed = $sellbilltotalPayed + $visa;
                $myReturnsellbill->sellerid = (int) $sellBill->sellerid;
                $myReturnsellbill->userid = $_SESSION['userid'];
                $myReturnsellbill->tempclientName = $tempClientName;
                $myReturnsellbill->returnsellQuantity = (float) $sellBill->sellQuantity;
                $myReturnsellbill->tax = $tax;
                $myReturnsellbill->carnumber = $sellbillcarnumber;
                $myReturnsellbill->cartype = $sellbillcartype;
                $myReturnsellbill->carchase = $sellbillcarchase;
                $myReturnsellbill->carmotor = $sellbillcarmotor;
                $myReturnsellbill->costcenterid = $Costcenterid;
                $myReturnsellbill->dailyentryid = 0;
                $myReturnsellbill->comment = $comment;
                $myReturnsellbill->billReservation = $billReservation;
                $myReturnsellbill->billReservationDate = $billReservationDate;
                $myReturnsellbill->cashPayed = $sellbilltotalPayed;
                $myReturnsellbill->visaPayed = $visa;
                $myReturnsellbill->visaAccountId = $sellBill->visaAccountId;
                $myReturnsellbill->isBankAccountTransfer = $isBankAccountTransfer;
                $myReturnsellbill->obygyVisitId = (int) $_POST['insertvisitid'];
                $myReturnsellbill->obgyBillType = (int) $_POST['obgyBillType'];
                $myReturnsellbill->billoperationid = (int) $_POST['billoperationid'];

                $sellbillId = $returnsellbillId = $myReturnsellbillRecord->insert($myReturnsellbill);


                //affect client debt first so that making two bills in same time dont corrupt debt
                if ($sellbillclientId != 0) { //&& $productquantityBefore > 0
                    //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                    //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                    {

                        //update rawmaterialssupplierdebt
                        if ($sellbillclientId == 1) {

                        } else {

                        }
                        updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                        insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, abs($sellbillFinalbill), 1, "اضافة فاتورة مردوات مبيعات", $returnsellbillId, $sellbilltotaldeptAfter, "returnsellbillController.php", "اضافة فاتورة مردوات مبيعات", $sellbillAftertotalBill, date("Y-m-d H:i:s"), $visa, $visaAccount, ($sellbilltotalPayed - $payed));
                        markClientAsNOTInUse($sellbillclientId);
                    }
                }

                $Costcenterdetail->costamount = $sellbillAftertotalBill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $returnsellbillId;
                $Costcenterdetail->processname = 'فاتوره مردودات مبيعات';
                $Costcenterdetail->tablename = 'returnsellbillController.php';
                $Costcenterdetail->type = 1;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }

                //insert Return Data into returnsellbilldetail tbl
                foreach ($sellbillDetails as $billDetail) {
                    $parcode = $billDetail->parcode;
                    $productId = $billDetail->sellbilldetailproductid;
                    $sizeId = $billDetail->sizeid;
                    $colorId = $billDetail->colorid;
                    $productunitId = $billDetail->productunitid;
                    $quantity = $billDetail->sellbilldetailquantity;
                    $price = $myReturnsellbill->returnsellbilltotalpayed / count($sellbillDetails); //$billDetail->sellbilldetailprice;
                    $discountValue = $billDetail->discountvalue;
                    $totalPrice = $quantity * $price; //$billDetail->sellbilldetailtotalprice;
                    $comment = $billDetail->note;
                    $returndiscounttype = $billDetail->discounttype;
                    $scunitname = $billDetail->otherdetailquantity;
                    $retpricetypepro = $billDetail->pricetypepro;

                    $reprstorid = $billDetail->storeid;
                    if (isset($reprstorid) && $reprstorid != -1 && $reprstorid != '') {

                        $sellbillstoreId = $reprstorid;
                    } else {
                        $sellbillstoreId = $_POST['storeid'];
                        //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                    }

                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        if (empty($productunitId) || $productunitId == -1) {
                            //$productunitId = 0;
                            $productunitId = getfirstunittWithProductNumberEQ1($productId);
                        }

                        $productData = loadProductById($productId);
                        //                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                        $myReturnsellbilldetail->buyprice = $productData->productBuyPrice;
                        $myReturnsellbilldetail->conditions = 0;
                        $myReturnsellbilldetail->discountvalue = $discountValue;
                        $myReturnsellbilldetail->note = $comment;
                        $myReturnsellbilldetail->parcode = $parcode;
                        $myReturnsellbilldetail->pricetype = $priceType;
                        $myReturnsellbilldetail->productunitid = $productunitId;
                        $myReturnsellbilldetail->returnsellbilldetailcatid = $productData->productCatId;
                        $myReturnsellbilldetail->returnsellbilldetailprice = $price;
                        $myReturnsellbilldetail->returnsellbilldetailproductid = $productId;
                        $myReturnsellbilldetail->returnsellbilldetailquantity = $quantity;
                        $myReturnsellbilldetail->returnsellbilldetailtotalprice = $totalPrice;
                        $myReturnsellbilldetail->returnsellbillid = $returnsellbillId;
                        $myReturnsellbilldetail->buydiscount = $productData->buydiscount;
                        $myReturnsellbilldetail->buydiscounttype = $productData->discounttype;
                        $myReturnsellbilldetail->storeid = $sellbillstoreId;
                        $myReturnsellbilldetail->discounttype = $returndiscounttype;
                        $myReturnsellbilldetail->otherdetailquantity = $scunitname;
                        $myReturnsellbilldetail->sizeid = $sizeId;
                        $myReturnsellbilldetail->colorid = $colorId;
                        $myReturnsellbilldetail->pricetypepro = $retpricetypepro;

                        $detailId = $myReturnsellbilldetailRecord->insert($myReturnsellbilldetail);

                        $productnumber = 0; //(float) $_POST['retProNum' . $h];
                        if ($productnumber <= 0) {
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                            $productnumber = $productunitData->productnumber;
                        }
                        $finalquantity = $quantity * $productnumber;

                        //update DON if is Serial
                        if ($parcodeType == "serialnumber") {
                            //updateSerailDon($productserailId, 0, 0);
                            updateSerailQty_ForReturn($productserailId, $finalquantity);
                            insertIntoSoldSerialProduct($productserailId, $finalquantity, $returnsellbillId, 3, $sellbillclientId);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //get storeto productquantity before change
                            $storedetailData = getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                            $allStoredetailData = $storedetailData[0];
                            $storedetailId = $storedetailData[1];
                            $productquantityBefore = $storedetailData[2];

                            if (count($allStoredetailData) > 0) {

                                //update productquantity in storedetail
                                $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "returnsellbilldetailid", $detailId, $productId, "returnsellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات", "returnsellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, date("Y-m-d H:i:s"), "returnsellbilldetailid", $detailId, $productId, "returnsellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                //insert in storereport
                                insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات", "returnsellbillController.php", date("Y-m-d H:i:s"), $sizeId, $colorId);
                            }

                            //other unit
                            if ($scunitname > 0) {
                                $allStoredetailData2 = getStoreDetails($sellbillstoreId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                $allStoredetailDataother = $allStoredetailData2[0];
                                $storeDetailIdother = $allStoredetailData2[1];
                                $productQuantityBeforeother = $allStoredetailData2[2];

                                if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                    //update productquantity in storedetail
                                    $finalquantityother = $productQuantityBeforeother + $scunitname;
                                    $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات ", "returnsellbillController.php", date("Y-m-d H:i:s"), 1);
                                } else {
                                    //insert in storedetail tbl
                                    if ($scunitname > 0) {
                                        insertStoredetailupdate2($sellbillstoreId, $productId, ($scunitname), date("Y-m-d H:i:s"), 1);

                                        //insert in storereport
                                        insertStorereportupdate2($productId, $sellbillstoreId, $scunitname, 0, ($scunitname), 0, $returnsellbillId, "اضافة فاتورة مردودات ", "returnsellbillController.php", date("Y-m-d H:i:s"), 1);
                                    }
                                }
                            }
                        }
                    }
                }

                //check if payed or not to change save value
                if ($sellbilltotalPayed != 0) {

                    //get saveValue before and saveValue after mins sellbilltotalPayed
                    $saveData = getSaveValueAndMins($_SESSION['saveid'], abs($sellbilltotalPayed));
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $specialSellbilltotalPayed = $sellbilltotalPayed * -1;
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedailyupdate($saveValuebefore, $specialSellbilltotalPayed, 1, $_SESSION['saveid'], "اضافة فاتورة مردوات مبيعات", $returnsellbillId, $saveValueafter, "returnsellbillController.php", date("Y-m-d H:i:s")); //$sellbillDate
                    unset($_SESSION['client_id']);
                }
                if ($visa != 0 && $visaAccount > 0) {
                    $visaAccountData = $bankAccountDAO->load($visaAccount);
                    if ($isBankAccountTransfer == 1) {
                        $visaDisPerVal = 0;
                    } else {
                        $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                    }
                    $accountBefore = $visaAccountData->accountbeginingbalance;
                    $visaAccountData->accountbeginingbalance = $accountBefore - $visa + $visaDisPerVal;
                    $visaAccountData->accountdate = date('Y-m-d');
                    $visaAccountData->accountid = $visaAccount;
                    $bankAccountEX->updateacount($visaAccountData);

                    //Insert in accountmovement table the payment
                    $afterVal = $accountBefore - $visa;
                    insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 1, "سداد فاتورة", "returnsellbillController.php", $sellbillId, date('Y-m-d H:i:s')); //$sellbillDate
                    //Insert in accountmovement table the disount per
                    if ($isBankAccountTransfer != 1) {
                        $afterVal_AfterDisc = $afterVal + $visaDisPerVal;
                        insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 0, "نسبة خصم الفيزا من تحصيل فاتورة", "returnsellbillController.php", $sellbillId, $sellbillDate); //date('Y-m-d H:i:s')
                    }
                }
            }

            if ($sellerId > 0) {
                $clientEX->updateClientDelegateid($sellbillclientId, $sellerId);
            }
        }

        /* ---------------------------------------------------------------------------------------------------------- */
        /* ---------------------------------------------------- بداية القيود اليومية ------------------------------------------------------ */
        doBillDailyEntry($billtype, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $saveId, $visa, $visaAccount, $gen4totalinput, $clientdata->treeId, 0, $billDiscountVal, $sellbilltotalBill, $sellbillAftertotalBill, $taxVal, $sellCostsArray, $sellbillstoreId);


        quickProfitBill($sellbilltotalBill, 0, $billDiscountVal, $sellbillclientId, 1);
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $sellbillclientId = $_POST['supplier'];
        markClientAsNOTInUse($sellbillclientId);
        liveBackupComment("-- addObygyVisit: " . date('Y-m-d H:i:s') . ",vid:" . $_POST['visitId'] . "," . $ex->getTraceAsString());
    }
    return array(
        $sellbillId,
        $returnsellbillId,
        $productsBeforeValid,
        $saveValuebeforeValid,
        $billtype
    );
}

function insertBankAccountMovement($accountId, $bankId, $beforeVal, $amount, $afterVal, $type, $comment, $tablename, $modelId, $theDate) {
    global $accountMove;
    global $accountMoveDAO;

    if ($amount != 0) {
        $accountMove->accountmovementbefore = $beforeVal;
        $accountMove->accountid = $accountId;
        $accountMove->bankid = $bankId;
        $accountMove->accountmovementamount = $amount;
        $accountMove->accountmovementafter = $afterVal;
        $accountMove->accountmovementtype = $type;
        $accountMove->processname = $comment;
        $accountMove->tablename = $tablename;
        $accountMove->accountmovementmodelid = $modelId;
        $accountMove->accountmovementdate = $theDate;
        $accountMove->userid = $_SESSION['userid'];
        $accountMoveDAO->insert($accountMove);
    }
}

function printKitchen($tableId) {
    global $restaurantOrderEX;
    global $restaurantOrderDetailsDAO;
    global $restaurantOrderDetailsEX;
    global $restaurantkitchenprintDAO;
    global $restaurantkitchenprintEX;
    global $myRelusergrouppropertieExt;
    //
    $printForKitchenArr = array();
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;

        //get order details that not printed for kitchen
        $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdEX($orderId);
        if (count($restaurantOrderDetails) > 0) {
            $i = 1;
            $togetherNo = 1;
            $insert_sql = "INSERT INTO restaurantkitchenprint (`id`, `orderId`, `productId`, `quantity`, `notesPrinted`, `togetherNo`, `isPrinted`, `sysDateTime`) VALUES";
            foreach ($restaurantOrderDetails as $detail) {
                $detail->kitchenQuantity = $detail->quantity - $detail->printedQuantity;
                if ($detail->kitchenQuantity > 0) {
                    $notesDiff = getNotesDiff($detail->notes, $detail->notesPrinted);
                    $detail->notesPrinted = $notesDiff;
                    $notesStr = '';
                    if ($detail->notesPrinted != "") {
                        $notesArr = explode(',', $detail->notesPrinted);
                        if (!empty($notesArr[0])) {
                            $notesStr .= $notesArr[0] . ' زيادة عالى ';
                        }
                        if (!empty($notesArr[1])) {
                            $notesStr .= $notesArr[1] . ' زيادة ';
                        }
                        if (!empty($notesArr[2])) {
                            $notesStr .= $notesArr[2] . ' مانو ';
                        }
                        if (!empty($notesArr[3])) {
                            $notesStr .= $notesArr[3] . ' مظبوط ';
                        }
                        if (!empty($notesArr[4])) {
                            $notesStr .= $notesArr[4] . ' عالريحه ';
                        }
                        if (!empty($notesArr[5])) {
                            $notesStr .= $notesArr[5] . ' ساده ';
                        }
                    }
                    $detail->notesStr = $notesStr;
                    array_push($printForKitchenArr, $detail);
                    //restaurantkitchenprint make bulk insert as print kitchen dont wait for this foreach loop to finish what should be printed
                    $restaurantkitchenprint->orderId = $detail->orderId;
                    $restaurantkitchenprint->productId = $detail->productId;
                    $restaurantkitchenprint->quantity = $detail->kitchenQuantity;
                    $restaurantkitchenprint->notesPrinted = $detail->notesPrinted;
                    if ($i == 1) {
                        $lastTogetherNo = $restaurantkitchenprintEX->getLastTogetherNo();
                        if (isset($lastTogetherNo) && !empty($lastTogetherNo)) {
                            $togetherNo = $lastTogetherNo + 1;
                        }
                    }
                    $restaurantkitchenprint->togetherNo = $togetherNo;
                    $restaurantkitchenprint->isPrinted = 0;
                    $restaurantkitchenprint->sysDateTime = date('Y-m-d H:i:s');
                    //$restaurantkitchenprintId = $restaurantkitchenprintDAO->insert($restaurantkitchenprint);
                    $insert_sql .= "(NULL,$restaurantkitchenprint->orderId,$restaurantkitchenprint->productId,$restaurantkitchenprint->quantity,'" . $restaurantkitchenprint->notesPrinted . "',$restaurantkitchenprint->togetherNo,$restaurantkitchenprint->isPrinted,'" . $restaurantkitchenprint->sysDateTime . "'),";
                    $i++;
                }
                $detail->printedQuantity = $detail->quantity;
                //markNotPrintedOrderDetailsAsPrinted
                $detail->isPrinted = 1;
                $restaurantOrderDetailsDAO->update($detail);
            }
            //
            $insert_sql = trim($insert_sql, ',');
            $split = explode(" ", $insert_sql);
            if ($split[count($split) - 1] != "VALUES") {
                $affected_rows = $myRelusergrouppropertieExt->insertBulk($insert_sql);
            }
        }
    }
}

function printKitchenFromSellBill($sellbillId) {
    global $mySellbilldetail;
    global $mySellbilldetailRecord;
    global $restaurantkitchenprintDAO;
    global $restaurantkitchenprintEX;
    global $myRelusergrouppropertieExt;
    //
    $printForKitchenArr = array();
    //get order details that not printed for kitchen
    $restaurantOrderDetails = $mySellbilldetailRecord->queryBySellbillid($sellbillId);
    if (count($restaurantOrderDetails) > 0) {
        $i = 1;
        $togetherNo = 1;
        $insert_sql = "INSERT INTO restaurantkitchenprint (`id`, `orderId`, `productId`, `quantity`, `notesPrinted`, `togetherNo`, `isPrinted`, `sysDateTime`, `fromBillDirectWithId`) VALUES";
        foreach ($restaurantOrderDetails as $detail) {
            $detail->kitchenQuantity = $detail->sellbilldetailquantity;
            if ($detail->kitchenQuantity > 0) {
                $notesDiff = $detail->note;
                $detail->notesPrinted = $notesDiff;
                $notesStr = '';
                if ($detail->notesPrinted != "") {
                    $notesArr = explode(',', $detail->notesPrinted);
                    if (!empty($notesArr[0])) {
                        $notesStr .= $notesArr[0] . ' زيادة عالى ';
                    }
                    if (!empty($notesArr[1])) {
                        $notesStr .= $notesArr[1] . ' زيادة ';
                    }
                    if (!empty($notesArr[2])) {
                        $notesStr .= $notesArr[2] . ' مانو ';
                    }
                    if (!empty($notesArr[3])) {
                        $notesStr .= $notesArr[3] . ' مظبوط ';
                    }
                    if (!empty($notesArr[4])) {
                        $notesStr .= $notesArr[4] . ' عالريحه ';
                    }
                    if (!empty($notesArr[5])) {
                        $notesStr .= $notesArr[5] . ' ساده ';
                    }
                }
                $detail->notesStr = $notesStr;
                array_push($printForKitchenArr, $detail);
                //restaurantkitchenprint make bulk insert as print kitchen dont wait for this foreach loop to finish what should be printed
                $restaurantkitchenprint->orderId = -1;
                $restaurantkitchenprint->fromBillDirectWithId = $sellbillId;
                $restaurantkitchenprint->productId = $detail->sellbilldetailproductid;
                $restaurantkitchenprint->quantity = $detail->kitchenQuantity;
                $restaurantkitchenprint->notesPrinted = $detail->notesPrinted;
                if ($i == 1) {
                    $lastTogetherNo = $restaurantkitchenprintEX->getLastTogetherNo();
                    if (isset($lastTogetherNo) && !empty($lastTogetherNo)) {
                        $togetherNo = $lastTogetherNo + 1;
                    }
                }
                $restaurantkitchenprint->togetherNo = $togetherNo;
                $restaurantkitchenprint->isPrinted = 0;
                $restaurantkitchenprint->sysDateTime = date('Y-m-d H:i:s');
                //$restaurantkitchenprintId = $restaurantkitchenprintDAO->insert($restaurantkitchenprint);
                $insert_sql .= "(NULL,$restaurantkitchenprint->orderId,$restaurantkitchenprint->productId,$restaurantkitchenprint->quantity,'" . $restaurantkitchenprint->notesPrinted . "',$restaurantkitchenprint->togetherNo,$restaurantkitchenprint->isPrinted,'" . $restaurantkitchenprint->sysDateTime . "',$restaurantkitchenprint->fromBillDirectWithId),";
                $i++;
            }
        }
        //
        $insert_sql = trim($insert_sql, ',');
        $split = explode(" ", $insert_sql);
        if ($split[count($split) - 1] != "VALUES") {
            $affected_rows = $myRelusergrouppropertieExt->insertBulk($insert_sql);
        }
    }
}

function getNotesDiff($notes, $notesPrinted) {

    $notesDiff = $notes;
    if (!empty($notesPrinted)) {
        $notes = explode(',', $notes);
        $notesPrinted = explode(',', $notesPrinted);
        $a = $notes[0] - $notesPrinted[0];
        $b = $notes[1] - $notesPrinted[1];
        $c = $notes[2] - $notesPrinted[2];
        $d = $notes[3] - $notesPrinted[3];
        $e = $notes[4] - $notesPrinted[4];
        $f = $notes[5] - $notesPrinted[5];
        $notesDiff = $a . ',' . $b . ',' . $c . ',' . $d . ',' . $e . ',' . $f;
    }
    return $notesDiff;
}

function ifCollectiveProductReCalculateCost($buyProduct) {
    global $productIngredients;
    global $productIngredientsEX;
    global $productDAO;
    global $noOfDecimalPlaces;

    //to edit collective pro get ingridients
    $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($buyProduct->productId); //final name is product id that is collective
    if (count($ingridients) > 0) {
        //reclculate cost prices
        $buyProduct->productBuyPrice = 0;
        $buyProduct->lastbuyprice = 0;
        $buyProduct->lastbuyprice_withDiscount = 0;
        $buyProduct->meanbuyprice = 0;
        $buyProduct->meanbuyprice_withDiscount = 0;
        $buyProduct->overAllAveragePrice = 0;
        $buyProduct->lastbuyprice_withTax = 0;
        $buyProduct->meanbuyprice_withTax = 0;
        $buyProduct->lastbuyprice_withDiscountAndTax = 0;
        foreach ($ingridients as $val) {
            $buyProduct->productBuyPrice += $val->productBuyPrice * $val->quantity * $val->productnumber;
            $buyProduct->lastbuyprice += $val->lastbuyprice * $val->quantity * $val->productnumber;
            $buyProduct->lastbuyprice_withDiscount += $val->lastbuyprice_withDiscount * $val->quantity * $val->productnumber;
            $buyProduct->meanbuyprice += $val->meanbuyprice * $val->quantity * $val->productnumber;
            $buyProduct->meanbuyprice_withDiscount += $val->meanbuyprice_withDiscount * $val->quantity * $val->productnumber;
            $buyProduct->overAllAveragePrice += $val->overAllAveragePrice * $val->quantity * $val->productnumber;
            $buyProduct->lastbuyprice_withTax += $val->lastbuyprice_withTax * $val->quantity * $val->productnumber;
            $buyProduct->meanbuyprice_withTax += $val->meanbuyprice_withTax * $val->quantity * $val->productnumber;
            $buyProduct->lastbuyprice_withDiscountAndTax += $val->lastbuyprice_withDiscountAndTax * $val->quantity * $val->productnumber;
        }
        $buyProduct->productBuyPrice = round($buyProduct->productBuyPrice, $noOfDecimalPlaces);
        $buyProduct->lastbuyprice = round($buyProduct->lastbuyprice, $noOfDecimalPlaces);
        $buyProduct->lastbuyprice_withDiscount = round($buyProduct->lastbuyprice_withDiscount, $noOfDecimalPlaces);
        $buyProduct->meanbuyprice = round($buyProduct->meanbuyprice, $noOfDecimalPlaces);
        $buyProduct->meanbuyprice_withDiscount = round($buyProduct->meanbuyprice_withDiscount, $noOfDecimalPlaces);
        $buyProduct->overAllAveragePrice = round($buyProduct->overAllAveragePrice, $noOfDecimalPlaces);
        $buyProduct->lastbuyprice_withTax = round($buyProduct->lastbuyprice_withTax, $noOfDecimalPlaces);
        $buyProduct->meanbuyprice_withTax = round($buyProduct->meanbuyprice_withTax, $noOfDecimalPlaces);
        $buyProduct->lastbuyprice_withDiscountAndTax = round($buyProduct->lastbuyprice_withDiscountAndTax, $noOfDecimalPlaces);
        $productDAO->update($buyProduct);
    } else {
        //make no change to prices
    }
    return $buyProduct;
}

function ifCollectiveIncreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $sellbillstoreId, $tableName) {
    global $productIngredients;
    global $productIngredientsEX;
    global $productDAO;
    global $myStoredetail;
    global $myStoredetailEx;
    global $myStoredetailRecord;

    //to edit collective pro get ingridients
    $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($buyProduct->productId);
    foreach ($ingridients as $product) {
        $productId = $product->ingridientId;
        $ingridientChangeAmount = $productChangeAmount * $product->quantity;
        $commentCollective = '';
        $controllerLink = '';
        switch ($tableName) {
            case "sellandruternbilldetail":
                $commentCollective = "فاتورة مبيعات ومردودات بها منتج تجميعى - $buyProduct->productName";
                $controllerLink = "sellbillandruternController.php";
                break;
            case "returnsellbilldetail":
                $commentCollective = "فاتورة مردودات مبيعات بها منتج تجميعى - $buyProduct->productName";
                $controllerLink = "returnsellbillController.php";
                break;
            case "sellbilldetail":
                $commentCollective = "فاتورة مبيعات بها منتج تجميعى - $buyProduct->productName";
                $controllerLink = "sellbillController.php";
                break;
        }

        $storedetailData = getStoredetailData($sellbillstoreId, $productId, 0);

        $allStoredetailData = $storedetailData[0];
        $storedetailId = $storedetailData[1];
        $productquantityBefore = $storedetailData[2];

        if (count($allStoredetailData) > 0) {
            ################
            //update productquantity in storedetail
            //$productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);
            //increase productquantity NOWWWWWWW Only Dont Affect Prices Again so dont use increaseProductQuantity()
            $productquantityAfter = $productquantityBefore + $ingridientChangeAmount;
            //lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $ingridientChangeAmount);
            //update productquantity in storedetail tbl
            $myStoredetail->storedetailid = $storedetailId;
            $myStoredetail->userid = $_SESSION['userid'];
            $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
            $myStoredetail->productquantity = $productquantityAfter;

            $myStoredetailEx->updateProductquantity($myStoredetail);
            #########################
            //insert in storereport
            insertStorereportupdate($productId, $sellbillstoreId, $ingridientChangeAmount, $productquantityBefore, $productquantityAfter, 0, $sellbillId, $commentCollective, $controllerLink, date("Y-m-d H:i:s"));
        } else {
            ################
            //insert in storedetail tbl
            //insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, date("Y-m-d H:i:s"));
            //insertStoredetail NOWWWWWWW Only Dont Affect Prices Again so dont use insertStoredetailupdate()
            $myStoredetail->userid = $_SESSION['userid'];
            $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
            $myStoredetail->productquantity = $ingridientChangeAmount;
            $myStoredetail->storeid = $sellbillstoreId;
            $myStoredetail->productid = $productId;

            $myStoredetailRecord->insert($myStoredetail);
            #########################
            //insert in storereport
            insertStorereportupdate($productId, $sellbillstoreId, $ingridientChangeAmount, 0, $ingridientChangeAmount, 0, $sellbillId, $commentCollective, $controllerLink, date("Y-m-d H:i:s"));
        }
    }
    return count($ingridients); //as flag if collective pro
}

function ifCollectiveDecreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $sellbillstoreId, $tableName) {
    global $productIngredients;
    global $productIngredientsEX;
    global $productDAO;
    global $myStoredetail;
    global $myStoredetailEx;
    global $myStoredetailRecord;

    //to edit collective pro get ingridients
    $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($buyProduct->productId);
    foreach ($ingridients as $product) {
        $productId = $product->ingridientId;
        $ingridientChangeAmount = $productChangeAmount * $product->quantity;
        $commentCollective = '';
        $controllerLink = '';
        switch ($tableName) {
            case "sellandruternbilldetail":
                $commentCollective = "فاتورة مبيعات ومردودات بها منتج تجميعى - $buyProduct->productName";
                $controllerLink = "sellbillandruternController.php";
                break;
            case "returnsellbilldetail":
                $commentCollective = "فاتورة مردودات مبيعات بها منتج تجميعى - $buyProduct->productName";
                $controllerLink = "returnsellbillController.php";
                break;
            case "sellbilldetail":
                $commentCollective = "فاتورة مبيعات بها منتج تجميعى - $buyProduct->productName";
                $controllerLink = "sellbillController.php";
                break;
        }

        $storedetailData = getStoredetailData($sellbillstoreId, $productId, 0);

        $allStoredetailData = $storedetailData[0];
        $storedetailId = $storedetailData[1];
        $productquantityBefore = $storedetailData[2];

        if (count($allStoredetailData) > 0) {
            ################
            //update productquantity in storedetail
            //$productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);
            //decrease productquantity NOWWWWWWW Only Dont Affect Prices Again so dont use increaseProductQuantity()
            $productquantityAfter = $productquantityBefore - $ingridientChangeAmount;
            //lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $ingridientChangeAmount);
            //update productquantity in storedetail tbl
            $myStoredetail->storedetailid = $storedetailId;
            $myStoredetail->userid = $_SESSION['userid'];
            $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
            $myStoredetail->productquantity = $productquantityAfter;

            $myStoredetailEx->updateProductquantity($myStoredetail);
            #########################
            //insert in storereport
            insertStorereportupdate($productId, $sellbillstoreId, $ingridientChangeAmount, $productquantityBefore, $productquantityAfter, 1, $sellbillId, $commentCollective, $controllerLink, date("Y-m-d H:i:s"));
        } else {
            ################
            //insert in storedetail tbl
            //insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, date("Y-m-d H:i:s"));
            //insertStoredetail NOWWWWWWW Only Dont Affect Prices Again so dont use insertStoredetailupdate()
            $myStoredetail->userid = $_SESSION['userid'];
            $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
            $myStoredetail->productquantity = $ingridientChangeAmount;
            $myStoredetail->storeid = $sellbillstoreId;
            $myStoredetail->productid = $productId;

            $myStoredetailRecord->insert($myStoredetail);
            #########################
            //insert in storereport
            insertStorereportupdate($productId, $sellbillstoreId, $ingridientChangeAmount, 0, $ingridientChangeAmount, 1, $sellbillId, $commentCollective, $controllerLink, date("Y-m-d H:i:s"));
        }
    }
    return count($ingridients); //as flag if collective pro
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantityOnly($storedetailId, $productquantityBefore, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;
    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, abs($productChangeAmount), 1);

    return $productquantityAfter;
}

//update and decrease Rawmaterialamount in storerawmaterialdetails tbl
function decreaseProductQuantityOnly($storedetailId, $productquantityBefore, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;
    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, (abs($productChangeAmount) * -1), 1);

    return $productquantityAfter;
}

//add in storerawmaterialdetails tbl
function insertStoredetailOnly($storeid, $productid, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailRecord;

    $myStoredetail->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productChangeAmount;
    $myStoredetail->storeid = $storeid;
    $myStoredetail->productid = $productid;

    $myStoredetailRecord->insert($myStoredetail);
}

function getProductPriceFromSellBill($ProductId, $ClientId, $productunitid) {
    //to use the variable out side the funcion
    global $mySellbilldetailEx;
    global $mySellandruternbilldetailEx;
    global $Programsettingdatabill;
    $Programsettingdata = $Programsettingdatabill;

    $sellbilldetailPrice;
    $detailData = array();

    if ($ClientId > 1 && ($Programsettingdata->showPrevPrices == 0 || $Programsettingdata->showPrevDiscount == 1)) {
        // get rawmaterialprice by rawmaterialid
        $sellbilldetailData = R::getRow("SELECT sellbilldetail.sellbilldetailprice, sellbilldate,discountvalue,discounttype
		 FROM sellbilldetail
		 JOIN sellbill
		 ON sellbilldetail.sellbillid = sellbill.sellbillid

		 WHERE sellbilldetail.sellbilldetailproductid = $ProductId
		 AND sellbilldetail.productunitid = $productunitid
		 AND sellbill.sellbillclientid = $ClientId
		 AND sellbill.conditions = 0
		 order by sellbilldetailid desc limit 1");
        //$sellbilldetailData = $mySellbilldetailEx->queryPriceWithProductIdAndClientIdAndUnit($ProductId, $ClientId, $productunitid);
        //        $sellandruternbilldetailData = $mySellandruternbilldetailEx->queryPriceWithProductIdAndClientIdAndUnit($ProductId, $ClientId, $productunitid, 0);
        $sellandruternbilldetailData = R::getRow("SELECT sellandruternbilldetail.sellbilldetailprice, sellbilldate,discountvalue,discounttype
		 FROM sellandruternbilldetail
		 JOIN sellbillandrutern
		 ON   sellandruternbilldetail.sellbillid = sellbillandrutern.sellbillid

		 WHERE sellandruternbilldetail.sellbilldetailproductid = $ProductId
		 AND sellandruternbilldetail.productunitid = $productunitid
		 AND sellbillandrutern.sellbillclientid = $ClientId
		 AND sellbillandrutern.conditions = 0
		 AND sellandruternbilldetail.selltype =0
		 order by sellbilldetailid desc limit 1");

        if ($sellbilldetailData["sellbilldetailprice"] > 0 && $sellandruternbilldetailData["sellbilldetailprice"] > 0) {
            //number of days
            $dayNum = round(abs(strtotime($sellbilldetailData["sellbilldate"]) - strtotime($sellandruternbilldetailData["sellbilldate"])));

            if ($dayNum >= 0) {
                $sellbilldetailPrice = $sellbilldetailData["sellbilldetailprice"];
                $detailData = $sellbilldetailData;
            } else {
                $sellbilldetailPrice = $sellandruternbilldetailData["sellbilldetailprice"];
                $detailData = $sellandruternbilldetailData;
            }
        } elseif ($sellbilldetailData["sellbilldetailprice"] > 0 && $sellandruternbilldetailData["sellbilldetailprice"] <= 0) {
            $detailData = $sellbilldetailData;
            $sellbilldetailPrice = $sellbilldetailData["sellbilldetailprice"];
        } elseif ($sellbilldetailData["sellbilldetailprice"] <= 0 && $sellandruternbilldetailData["sellbilldetailprice"] > 0) {
            $detailData = $sellandruternbilldetailData;

            $sellbilldetailPrice = $sellandruternbilldetailData["sellbilldetailprice"];
        } else {
            $detailData = array();
        }
    }

    $detailData = json_decode(json_encode($detailData));
    return array(
        $detailData,
        $sellbilldetailPrice
    );
}

function getClientDataFromClientInUseSP($clientid) {
    global $clientEX;
    global $myClientRecord;
    if ($clientid == 1) {
        $client_data = $myClientRecord->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $clientEX->callClientInUseSP($clientid);
        while ($client_data->clientdebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $clientEX->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

function markClientAsNOTInUse($clientid) { //mark as not in use "free him to be able to change debt again"
    global $clientEX;
    if ($clientid == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $clientEX->markClientAsNOTInUse($clientid);
    }
}

function getSaveDataFromSaveInUseSP($saveid) {
    global $mySaveEx;

    $noOfTries = 0;
    $save_data = $mySaveEx->callSaveInUseSP($saveid);

    while ($save_data->saveid < 0) {
        sleep(1);
        $noOfTries++;
        if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
            //markSaveAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
            liveBackupComment("-- force free save=$saveid with redbean");
            R::exec('UPDATE save SET  inUse = 0 where saveid = ' . $saveid);
        }
        $save_data = $mySaveEx->callSaveInUseSP($saveid);
    }
    return $save_data;
}

function markSaveAsNOTInUse($saveid) { //mark as not in use "free him to be able to change debt again"
    global $mySaveEx;
    $mySaveEx->markSaveAsNOTInUse($saveid);
}

function getBuyPriceFromAndHandleBuyPricesHistoryBook($storeId, $productid, $sizeid, $colorid, $productBuyPrice, $soldQuantity, $type = 0) { //0 add ,1 del
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;

    $idQuantityString = '';
    $remainQuantity = $soldQuantity;
    $totalPrice = 0;
    do {
        $buyPriceFromHistoryBook = $buyPricesHistoryBookEX->getBuyPriceOfFirstAvailableSellQuantity($storeId, $productid, $sizeid, $colorid);
        if (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0) {
            $availableBuyQuantity = $buyPriceFromHistoryBook->buyQuantity - $buyPriceFromHistoryBook->sellQuantity;
            if ($availableBuyQuantity >= $remainQuantity) {
                $totalPrice += $remainQuantity * $buyPriceFromHistoryBook->buyprice;
                if ($type == 0) {
                    $buyPricesHistoryBookEX->plusSellQuantityByValue($remainQuantity, $buyPriceFromHistoryBook->id);
                } elseif ($type == 1) {
                    $buyPricesHistoryBookEX->minusSellQuantityByValue($remainQuantity, $buyPriceFromHistoryBook->id);
                }
                //
                $idQuantityString .= "$buyPriceFromHistoryBook->id-$remainQuantity,";
                $remainQuantity -= $remainQuantity; //$remainQuantity = 0;
            } elseif ($remainQuantity > $availableBuyQuantity) {
                $totalPrice += $availableBuyQuantity * $buyPriceFromHistoryBook->buyprice;
                if ($type == 0) {
                    $buyPricesHistoryBookEX->plusSellQuantityByValue($availableBuyQuantity, $buyPriceFromHistoryBook->id);
                } elseif ($type == 1) {
                    $buyPricesHistoryBookEX->minusSellQuantityByValue($availableBuyQuantity, $buyPriceFromHistoryBook->id);
                }
                //
                $idQuantityString .= "$buyPriceFromHistoryBook->id-$availableBuyQuantity,";
                $remainQuantity -= $availableBuyQuantity;
            }
        }
    } while (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0);

    if ($remainQuantity > 0) {
        $totalPrice += $remainQuantity * $productBuyPrice;
        $remainQuantity -= $remainQuantity;
    }

    $theBuyPrice = round(($totalPrice / $soldQuantity), 2);
    return array(
        $theBuyPrice,
        $idQuantityString
    );
}

function decreaseSellQuantityHandleBuyPricesHistoryBook($idQuantityString) {
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;

    foreach (explode(',', $idQuantityString) as $row) {
        $data = explode('-', $row);
        $id = $data[0];
        $quantity = $data[1];
        if ($id > 0 && $quantity != 0) {
            $buyPricesHistoryBookEX->minusSellQuantityByValue($quantity, $id);
        }
    }
}

//-- show AJAX -----------------------------------------------------------//
/* function Name : showallajax .
  Description :send data using json to datatable.
 */
function showallajax() {
    global $mySellbillEx;
    global $ProgramsettingDAO;
    global $UsergroupDAO;
    $sIndexColumn = "sellbillid";

    /* DB table to use */
    $sTable = "sellbillview";
    $aColumns = array(
        'sellbillid',
        'sellbillserial',
        'sellbillaftertotalbill',
        'sellbilldate',
        'clientname',
        'sellbilltotalpayed',
        'sellbillfinalbill',
        'conditions',
        'newSellbillidAfterEdit',
        'dailyentryid'
    );

    // Indexed column (used for fast and accurate table cardinality)
    /*
     * Paging
     */
    $sLimit = "";
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
        $sLimit = "LIMIT " . intval($_POST['start']) . ", " . intval($_POST['length']);
    }

    /*
     * Ordering
     */
    $sOrder = "";

    if (isset($_POST['order'][0])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_POST['columns']); $i++) {
            $orderByColumnIndex = $_POST['order'][0]['column'] - 1; //this - 1 is because first column is not counted as it is checkbox
            $sOrder .= $aColumns[intval($_POST['columns'][$orderByColumnIndex]['data'])] . "
                      " . ($_POST['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc') . ", ";
        }
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY ") {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    // where del =0 and aqarstatus =0 and updatestatus in(1,2,3,4) and complete=1
    $sWhere = '';
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $sWhere = " where  (";
        for ($i = 0; $i < count($aColumns); $i++) {
            if ($aColumns[$i] == "sellbilldate") {
                //to get numbers and english chars only
                ##only alpha numeric is allowed . space not allowed
                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
                if (!empty($search)) {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
                }
            } else {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
            }
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }
    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE';
    } else {
        $queryString = ' AND';
    }

    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['sellbillid'];
    $clientId = $_REQUEST['clientid'];
    $sellerid = $_REQUEST['sellerid'];
    $selleruserid = $_REQUEST['selleruserid'];
    $storeid = $_REQUEST['storeid'];
    //    $pricetype = $_REQUEST['pricetype'];
    $saveid = $_REQUEST['saveid'];

    if (isset($clientId) && $clientId != "-1") {
        $queryString .= ' sellbillclientid = ' . $clientId . ' AND';
    }
    if (isset($sellerid) && $sellerid != "-1") {
        $queryString .= ' sellerid = ' . $sellerid . ' AND';
    }
    if (isset($selleruserid) && $selleruserid != "-1") {
        $queryString .= ' userid = ' . $selleruserid . ' AND';
    }
    if (isset($sellbillSerial) && $sellbillSerial != "") {
        $queryString .= ' sellbillserial = "' . $sellbillSerial . '" AND';
    }
    if (isset($sellbillId) && $sellbillId != "") {
        $queryString .= ' sellbillid = ' . $sellbillId . ' AND';
    }
    if (isset($storeid) && $storeid != "-1") {
        $queryString .= ' sellbillstoreid = ' . $storeid . ' AND';
    }
    //    if (isset($pricetype) && $pricetype != "-1") {
    //        $queryString .= ' pricetype = ' . $pricetype . ' AND';
    //    }
    if (isset($saveid) && $saveid != "-1") {
        $queryString .= ' sellbillsaveid = ' . $saveid . ' AND';
    }
    ##needed Data
    $Programsetting = $ProgramsettingDAO->load(1);
    $Programsettingdata->vatValue = (float) $Programsettingdata->vatValue;
    $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
    $billsettingsData = loadBillProperty(3); //3 is for sell bill
    ##############
    ##fatma
    $search = $_REQUEST['searchDate'];
    if (empty($search)) {
        $search = "dateOnly";
    }
    if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
        if ($search == "dateOnly") {
            //display the converted time ##reportsPlusHours
            if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
                $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
                $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
                $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
            } else {
                $endDate = $endDate . ' 23:59:59';
                $startDate = $startDate . " 00:00:00";
            }
        }
        $queryString .= ' sellbilldate >= "' . $startDate . '" and sellbilldate <= "' . $endDate . '" AND';
    }

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

        //print("<br>queryString: ".$queryString."<br>");
    }

    $totalBills = 0;

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


    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";

    $rResult = $mySellbillEx->runSelectQuery($sQuery);

    /* Data set length after filtering */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as sellbillid  FROM  $sTable $sWhere "; //$sOrder
    $rResultFilterTotal = $mySellbillEx->runSelectQuery($sQuery);
    foreach ($rResultFilterTotal as $oneis) {
        $countis = $oneis->sellbillid;
    }
    $iFilteredTotal = $countis;
    /* Total data set length */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as sellbillid FROM  $sTable";
    $rResultTotal = $mySellbillEx->runSelectQuery($sQuery);

    foreach ($rResultTotal as $oneis) {
        $countit = $oneis->sellbillid;
    }
    //$aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $countit;

    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
    $sellQuantity = 0; //$piecesCount
    $sellbilltotalpayed = 0; //payedTotal
    $sellbillfinalbill = 0; //remainTotal
    $sellbillaftertotalbill = 0; //totalBills//totalBills2
    foreach ($rResult as $aRow) {
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            switch ($aColumns[$i]) {
                case "sellbillid":
                    if (isset($aRow->newSellbillidAfterEdit) && $aRow->newSellbillidAfterEdit > 0) { //<!--this bill is deleted for editing-->
                        $class = "danger";
                    } elseif ($aRow->conditions != 0) {
                        $class = "dark";
                    } elseif ($aRow->conditions == 0) {
                        $class = "";
                    }

                    $row[] = "<span classOftr='" . $class . "'>$rowno</span>";
                    $row[] = $aRow->$aColumns[0];
                    break;
                case "sellbillserial":
                    //if ($Programsetting->billid == 0)
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "sellbillaftertotalbill":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "sellbilldate":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "clientname":
                    if ($aRow->$aColumns[$i] == "")
                        $aRow->$aColumns[$i] = "نقدى";
                    //
                    $row[] = $aRow->$aColumns[$i];
                    break;
                default:
                    break;
            }
        }
        $row[] = '<a href="sellbillController.php?do=showDetail&sellbillid=' . $aRow->sellbillid . '" type="button" class="btn btn-default btn-lg editicon"></a>';
        if ($usergroup->allowEditDelInBills == 0) {
            if ($aRow->conditions == 0) {
                $row[] = '<a href="sellbillController.php?do=editsellBill&sellbillid=' . $aRow->sellbillid . '" type="button" class="btn btn-default btn-lg editicon"></a>';
                $row[] = '<a href="sellbillController.php?do=delete&sellbillid=' . $aRow->sellbillid . '&action=' . $aRow->dailyentryid . '" type="button" class="btn btn-default btn-lg removeicon"></a>';
            } else {
                if (isset($aRow->newSellbillidAfterEdit) && $aRow->newSellbillidAfterEdit > 0) { //<!--this bill is deleted for editing-->
                    $row[] = 'حذف للتعديل';
                    $row[] = 'حذف للتعديل';
                } else {
                    $row[] = 'تم حذف الفاتورة';
                    $row[] = 'تم حذف الفاتورة';
                }
            }
        }

        if ($aRow->conditions == 0) {
            $sellQuantity += $aRow->sellQuantity;
            $sellbilltotalpayed += $aRow->sellbilltotalpayed;
            $sellbillfinalbill += $aRow->sellbillfinalbill;
            $sellbillaftertotalbill += $aRow->sellbillaftertotalbill;
        }
        $output['data'][] = $row;
        $rowno++;
    }
    $output['totals']["piecesCount"] = $sellQuantity;
    $output['totals']["payedTotal"] = $sellbilltotalpayed;
    $output['totals']["remainTotal"] = $sellbillfinalbill;
    $output['totals']["totalBills"] = $sellbillaftertotalbill;

    //print_r($output);
    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}

function decreaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $requiredQuantity, $proSerials, $sellbillId, $sellbillclientId, $sellbilldetailid, $sellbilltype, $operation) {
    global $myProductserialDAO;
    global $myProductserialEx;
    global $soldSerialProductExt;
    global $mySellbilldetailEx;

    $doneQuantity = 0;
    $stillNeededQuantity = $requiredQuantity;
    $productSerials = '';

    if ($productId > 0 && isset($proSerials) && !empty($proSerials) && $requiredQuantity > 0) {
        $detailTableName = '';
        $detailTableColId = '';
        switch ($sellbilltype) {
            case 0:
                $detailTableName = 'sellbilldetail';
                $detailTableColId = 'sellbilldetailid';
                break;
            case 1:
            case 4:
                $detailTableName = 'sellandruternbilldetail';
                $detailTableColId = 'sellbilldetailid';
                break;
            case 3:
                $detailTableName = 'returnsellbilldetail';
                $detailTableColId = 'returnsellbilldetailid';
                break;
        }
        //
        foreach (explode(',', $proSerials) as $productserailId) {
            if ($stillNeededQuantity > 0) {
                $serialData = $myProductserialDAO->load($productserailId);
                $don = $serialData->don;
                if ($don > 0) {
                    //know quantity to reduce form this serial
                    $quantityForThisSerial = 0;
                    if ($don >= $stillNeededQuantity) {
                        $quantityForThisSerial = $stillNeededQuantity;
                    } elseif ($don < $stillNeededQuantity) {
                        $quantityForThisSerial = $don;
                    }

                    updateSerailQty($serialData->productserailid, $quantityForThisSerial);
                    if ($operation == 'add') {
                        insertIntoSoldSerialProduct($productserailId, $quantityForThisSerial, $sellbillId, $sellbilltype, $sellbillclientId);
                    } elseif ($operation == 'del') {
                        $parcode = $serialData->serialnumber;
                        $issold = $myProductserialEx->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");

                        if (count($issold) > 0) {

                            $soldSerialProduct->quantity = $finalquantity;
                            $soldSerialProduct->sellbilltype = $sellbilltype;
                            $soldSerialProduct->sellbillid = $sellbillId;
                            $soldSerialProduct->del = 1;
                            $soldSerialProduct->productserailid = $issold->productserailid;

                            //$mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial($soldSerialProduct);
                            $mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial2($soldSerialProduct);
                            //print_r($mysoldSerialProduct);
                            if (count($mysoldSerialProduct) > 0) {

                                //$soldSerialProductExt->updatedel($soldSerialProduct);
                                $soldSerialProductExt->updatedel2($soldSerialProduct);
                                $productserailid = $mysoldSerialProduct->productserailid;
                            }
                        }
                    }

                    $doneQuantity += $quantityForThisSerial;
                    $stillNeededQuantity -= $quantityForThisSerial;
                    $productSerials .= $serialData->productserailid . ','; //$serialData->serialnumber . ',';
                }
            }
        }

        if ($sellbilldetailid > 0 && $doneQuantity == $requiredQuantity && $productSerials != ',') {
            $productSerials = rtrim($productSerials, ',');
            $mySellbilldetailEx->updateSoldSerialsInDetails($detailTableName, $detailTableColId, $sellbilldetailid, $productSerials);
        }
    }
}

function increaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $requiredQuantity, $proSerials, $sellbillId, $sellbillclientId, $sellbilldetailid, $sellbilltype, $operation) {
    global $myProductserialDAO;
    global $myProductserialEx;
    global $soldSerialProductExt;
    global $mySellbilldetailEx;

    $doneQuantity = 0;
    $stillNeededQuantity = $requiredQuantity;
    $productSerials = '';
    if ($productId > 0 && isset($proSerials) && !empty($proSerials) && $requiredQuantity > 0) {
        $detailTableName = '';
        $detailTableColId = '';
        switch ($sellbilltype) {
            case 0:
                $detailTableName = 'sellbilldetail';
                $detailTableColId = 'sellbilldetailid';
                break;
            case 1:
            case 4:
                $detailTableName = 'sellandruternbilldetail';
                $detailTableColId = 'sellbilldetailid';
                break;
            case 3:
                $detailTableName = 'returnsellbilldetail';
                $detailTableColId = 'returnsellbilldetailid';
                break;
        }
        //
        foreach (explode(',', $proSerials) as $productserailId) {
            if ($stillNeededQuantity > 0) {
                $serialData = $myProductserialDAO->load($productserailId);
                $don = $serialData->don;
                //if ($don > 0) {
                //know quantity to reduce form this serial
                $quantityForThisSerial = 0;
                if ($don >= $stillNeededQuantity) {
                    $quantityForThisSerial = $stillNeededQuantity;
                } elseif ($don < $stillNeededQuantity) {
                    $quantityForThisSerial = $don;
                }

                updateSerailQty_ForReturn($serialData->productserailid, $quantityForThisSerial);
                if ($operation == 'add') {
                    insertIntoSoldSerialProduct($productserailId, $quantityForThisSerial, $sellbillId, $sellbilltype, $sellbillclientId);
                } elseif ($operation == 'del') {
                    $parcode = $serialData->serialnumber;
                    $issold = $myProductserialEx->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");

                    if (count($issold) > 0) {

                        $soldSerialProduct->quantity = $finalquantity;
                        $soldSerialProduct->sellbilltype = $sellbilltype;
                        $soldSerialProduct->sellbillid = $sellbillId;
                        $soldSerialProduct->del = 1;
                        $soldSerialProduct->productserailid = $issold->productserailid;

                        //$mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial($soldSerialProduct);
                        $mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial2($soldSerialProduct);
                        //print_r($mysoldSerialProduct);
                        if (count($mysoldSerialProduct) > 0) {

                            //$soldSerialProductExt->updatedel($soldSerialProduct);
                            $soldSerialProductExt->updatedel2($soldSerialProduct);
                            $productserailid = $mysoldSerialProduct->productserailid;
                        }
                    }
                }
                $doneQuantity += $quantityForThisSerial;
                $stillNeededQuantity -= $quantityForThisSerial;
                $productSerials .= $serialData->productserailid . ',';
                //}
            }
        }

        if ($sellbilldetailid > 0 && $doneQuantity == $requiredQuantity /* && $productSerials != ',' */) {
            $productSerials = rtrim($productSerials, ',');
            $mySellbilldetailEx->updateSoldSerialsInDetails($detailTableName, $detailTableColId, $sellbilldetailid, $productSerials);
        }
    }
}

function doBillDailyEntry($billtype, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $saveid, $visa, $visaAccount, $gen4totalinput, $clientTreeId, $taxOfDiscountVal, $billDiscountVal, $sellbilltotalBill, $sellbillAftertotalBill, $taxVal, $sellCostsArray, $sellbillstoreId, $firstProductId, $billoperationid) {
    global $mySaveRecord;
    global $bankAccountDAO;
    global $myStoreRecord;
    global $mySellbillEx;
    global $Programsettingdata;
    //liveBackupComment('make daily entry = ' . $Programsettingdata->makeDailyEntry);
    if ($Programsettingdata->makeDailyEntry == 1) {
        ## step zero perpare variables
        $taxOfDiscountTreeId = 0;
        $vatTreeId = 0;
        $sellTreeId = 0;
        $billComment = '';
        $table = '';
        $billIdColumn = '';
        $billId = 0;
        $detailsURL = '';
        if ($billtype == 1) { //sell
            $taxOfDiscountTreeId = 77; ##ضريبة الخصم من المنبع - مدينة
            $vatTreeId = 106; ##ضريبة القيمة المضافة - دائنة
            $sellTreeId = 143; ## ايرادات المبيعات
            $billComment = 'اضافة فاتورة مبيعات رقم ' . $sellbillId;
            $table = 'sellbill';
            $billIdColumn = 'sellbillid';
            $billId = $sellbillId;
            $detailsURL = "sellbillController.php?do=showDetail&sellbillid=" . $billId;
        } elseif ($billtype == 2) { //ret
            $taxOfDiscountTreeId = 107; ##ضريبة الخصم من المنبع - دائنة
            $vatTreeId = 76; ##ضريبة القيمة المضافة - مدينة
            $sellTreeId = 143; ## ايرادات المبيعات
            $billComment = 'اضافة فاتورة مردود مبيعات رقم ' . $returnsellbillId;
            $table = 'returnsellbill';
            $billIdColumn = 'returnsellbillid';
            $billId = $returnsellbillId;
            $detailsURL = "returnsellbillController.php?do=showDetail&returnsellbillid=" . $billId;
        } elseif ($billtype == 3) { //sell&ret
            $billComment = 'اضافة فاتورة مبيعات و مردود رقم ' . $sellbillId;
            $table = 'sellbillandrutern';
            $billIdColumn = 'sellbillid';
            $billId = $sellbillId;
            $detailsURL = "sellbillandruternController.php?do=showDetail&sellbillid=" . $billId;
        }

        $clientid = R::getCell('select clientid from client where treeId=' . $clientTreeId);
        ##setp For Royal getting $sellTreeId = 143; ## ايرادات المبيعات
        $sellTreeId = getsellTreeIdAccontId($firstProductId, $billoperationid); ## ايرادات المبيعات
        ##1 main bill entry
        // start المبيعات
        $dailyEntryIdOfMainSellEntry = 0;
        if ($sellbilltotalBill) { //$sellbillPrice || $returnsellbillPrice
            ###########################
            ##from
            $dailyEntry->entryComment = $billComment;
            $dailyEntry->fromFlag = 1;
            $dailyEntryDebtorArray = array();
            $dailyEntryCreditorArray = array();

            //المدفوع  من البنك او الخزنة
            if ($clientid == 1 && ($sellbilltotalPayed != 0 || ($visa != 0 && $visaAccount > 0))) {
                // start   من حساب الخزنة
                if ($sellbilltotalPayed != 0) {
                    $dailyEntryDebtor = new stdClass();
                    $dailyEntryDebtor->value = abs($sellbilltotalPayed);
                    $dataSave = $mySaveRecord->load($saveid);
                    $idTreeSave = $dataSave->treeId;
                    $dailyEntryDebtor->accountstreeid = $idTreeSave;

                    if ($billtype == 1) {
                        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                    } else {
                        array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
                    }
                }
                //من حساب البنك
                if ($visa != 0 && $visaAccount > 0) {
                    $dailyEntryDebtor = new stdClass();
                    $visaAccountData = $bankAccountDAO->load($visaAccount);
                    $dailyEntryDebtor->value = abs($visa);
                    $dailyEntryDebtor->accountstreeid = $visaAccountData->treeId;
                    if ($billtype == 1) {
                        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                    } else {
                        array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
                    }
                }
            }
            //المتبقى من العميل    noooooo stopped, now it is bill total before discount ,,, as we make payment as separated dailyentry
            $valForClient = $sellbillAftertotalBill;
            if ($clientid == 1) {
                $valForClient = $gen4totalinput;
            }
            if ($valForClient != 0) {
                $dailyEntryDebtor = new stdClass();
                $dailyEntryDebtor->value = abs($valForClient); //abs($gen4totalinput);
                $dailyEntryDebtor->accountstreeid = $clientTreeId;
                if ($billtype == 1) {
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                } else {
                    array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
                }
            }

            //من خصم مسموح به
            if (!empty($billDiscountVal) && $billDiscountVal != 0) {
                $dailyEntryDebtor = new stdClass();
                $dailyEntryDebtor->value = abs($billDiscountVal);
                $dailyEntryDebtor->accountstreeid = 398; //خصم مسموح به
                if ($billtype == 1) {
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                } else {
                    array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
                }
            }
            //من ضريبة الخصم
            if (!empty($taxOfDiscountVal) && $taxOfDiscountVal != 0) {
                $dailyEntryDebtor = new stdClass();
                $dailyEntryDebtor->value = abs($taxOfDiscountVal);
                $dailyEntryDebtor->accountstreeid = $taxOfDiscountTreeId; //ضريبة الخصم
                if ($billtype == 1) {
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                } else {
                    array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
                }
            }

            ########################
            ##to
            //الى ايرادات المبيعات
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = abs($sellbilltotalBill);
            $dailyEntryCreditor->accountstreeid = $sellTreeId; // ايرادات المبيعات
            if ($billtype == 1) {
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            } else {
                array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
            }


            if (!empty($taxVal) && $taxVal != 0) {
                $dailyEntryCreditor = new stdClass();
                $dailyEntryCreditor->value = abs($taxVal);
                $dailyEntryCreditor->accountstreeid = $vatTreeId; //ضريبة القيمة المضافة

                if ($billtype == 1) {
                    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
                } else {
                    array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
                }
            }
            //            var_dump($dailyEntryDebtorArray);
            //            var_dump($dailyEntryCreditorArray);
            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $billId, $detailsURL);
            $dailyEntryIdOfMainSellEntry = $returnDailyId[1];
        }


        ##2 client Payment entry ## cancelled by eng.sherif, it is done @Ta7seel
        $dailyEntryIdOfClientPay = 0;
        if ($clientid > 1 && ($sellbilltotalPayed != 0 || ($visa != 0 && $visaAccount > 0))) {
            $dailyEntry->entryComment = $billComment . ' - تحصيل الفاتورة من العميل';
            $dailyEntry->fromFlag = 1;
            $dailyEntryDebtorArray = array();
            $dailyEntryCreditorArray = array();

            //من البنك او الخزنة
            // start   من حساب الخزنة
            if ($sellbilltotalPayed != 0) {
                $dailyEntryDebtor = new stdClass();
                $dailyEntryDebtor->value = abs($sellbilltotalPayed);
                $dataSave = $mySaveRecord->load($saveid);
                $idTreeSave = $dataSave->treeId;
                $dailyEntryDebtor->accountstreeid = $idTreeSave;
                if ($billtype == 1) {
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                } else {
                    array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
                }
            }
            //من حساب البنك
            if ($visa != 0 && $visaAccount > 0) {
                $dailyEntryDebtor = new stdClass();
                $visaAccountData = $bankAccountDAO->load($visaAccount);
                $dailyEntryDebtor->value = abs($visa);
                $dailyEntryDebtor->accountstreeid = $visaAccountData->treeId;
                if ($billtype == 1) {
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                } else {
                    array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
                }
            }
            //الى حساب العميل
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = abs($sellbilltotalPayed) + abs($visa);
            $dailyEntryCreditor->accountstreeid = $clientTreeId;
            if ($billtype == 1) {
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            } else {
                array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
            }

            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $billId, $detailsURL);
            $dailyEntryIdOfClientPay = $returnDailyId[1];
        }



        ##3 store cost entry
        $dailyEntryIdOfStoreCost = 0;

        ##get price according to setting
        $sellCostsArrayLastBuyPrice = 0;
        $sellCostsArrayLastBuyPriceRet = 0;
        switch ($Programsettingdata->dailyEntryCostprice) {
            case "first":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostBuyPrice"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostBuyPrice"];
                break;
            case "last":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostLastBuyPrice"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostLastBuyPrice"];
                break;
            case "mean":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostMeanBuyPrice"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostMeanBuyPrice"];
                break;
            case "last_discount":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostLastBuyPricewithDiscount"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostLastBuyPricewithDiscount"];
                break;
            case "mean_discount":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostMeanBuyPricewithDiscount"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostMeanBuyPricewithDiscount"];
                break;
            case "generalPrice":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostOverAllAveragePrice"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostOverAllAveragePrice"];
                break;
            case "tax":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostLastBuyPricewithTax"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostLastBuyPricewithTax"];
                break;
            case "mean_tax":
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostMeanBuyPricewithTax"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostMeanBuyPricewithTax"];
                break;
            default:
                $sellCostsArrayLastBuyPrice = $sellCostsArray["sellCostLastBuyPrice"];
                $sellCostsArrayLastBuyPriceRet = $sellCostsArray["returnSellCostLastBuyPrice"];
                break;
        }

        if (!empty($sellCostsArrayLastBuyPrice) || !empty($sellCostsArrayLastBuyPriceRet)) {
            $dailyEntry->entryComment = $billComment . ' - صرف البضاعة من المخزن';
            $dailyEntry->fromFlag = 1;
            $dailyEntryDebtorArray = array();
            $dailyEntryCreditorArray = array();

            //من تكلفة البضاعة المباعة
            $dailyEntryDebtor = new stdClass();
            $dailyEntryDebtor->value = $sellCostsArrayLastBuyPrice + $sellCostsArrayLastBuyPriceRet;
            $dailyEntryDebtor->accountstreeid = 402;
            if ($billtype == 1) {
                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            } else {
                array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
            }

            //الى مخزون الانتاج التام
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = $sellCostsArrayLastBuyPrice + $sellCostsArrayLastBuyPriceRet;
            $storeData = $myStoreRecord->load($sellbillstoreId);
            $dailyEntryCreditor->accountstreeid = $storeData->treeId;
            if ($billtype == 1) {
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            } else {
                array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
            }

            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $billId, $detailsURL);
            $dailyEntryIdOfStoreCost = $returnDailyId[1];
        }

        $dailyentryidS = "$dailyEntryIdOfMainSellEntry,$dailyEntryIdOfClientPay,$dailyEntryIdOfStoreCost";
        $mySellbillEx->executeSQLQuery("update $table set dailyentryid='" . $dailyentryidS . "' where $billIdColumn=$billId");
    }
}

function doOfferDailyEntry($offerId, $mySellbill, $detailsArr) {
    global $myStoreRecord;
    global $mySellbillEx;
    global $Programsettingdata;
    //liveBackupComment('make daily entry = ' . $Programsettingdata->makeDailyEntry);
    if ($Programsettingdata->makeDailyEntry == 1 && $Programsettingdata->preparingStore != $mySellbill->sellbillstoreid) {
        ## step zero perpare variables
        ## get price according to setting
        $offerCost = 0;
        foreach ($detailsArr as $mySellbilldetail) {
            $productId = $mySellbilldetail->sellbilldetailproductid;
            $productunitId = $mySellbilldetail->productunitid;
            //            $price = $mySellbilldetail->sellbilldetailprice;
            $quantity = $mySellbilldetail->sellbilldetailquantity;
            //            $totalPrice = $mySellbilldetail->sellbilldetailtotalprice;
            $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
            $productnumber = $productunitData->productnumber;
            $finalQuantity = $quantity * $productnumber;


            $myproduct = (object) R::getRow('SELECT * FROM product WHERE productId =' . $productId);
            if ($myproduct->meanbuyprice == NULL || $myproduct->meanbuyprice == 0)
                $myproduct->meanbuyprice = $myproduct->productBuyPrice;
            if ($myproduct->lastbuyprice == NULL || $myproduct->lastbuyprice == 0)
                $myproduct->lastbuyprice = $myproduct->productBuyPrice;
            if ($myproduct->lastbuyprice_withDiscount == NULL || $myproduct->lastbuyprice_withDiscount == 0)
                $myproduct->lastbuyprice_withDiscount = $myproduct->productBuyPrice;
            if ($myproduct->meanbuyprice_withDiscount == NULL || $myproduct->meanbuyprice_withDiscount == 0)
                $myproduct->meanbuyprice_withDiscount = $myproduct->productBuyPrice;
            if (empty($myproduct->overAllAveragePrice) || $myproduct->overAllAveragePrice === NULL)
                $myproduct->overAllAveragePrice = $myproduct->productBuyPrice;
            $myproduct = ifCollectiveProductReCalculateCost($myproduct);
            //
            switch ($Programsettingdata->dailyEntryCostprice) {
                case "first":
                    $offerCost += $myproduct->productBuyPrice * $finalQuantity;
                    break;
                case "last":
                    $offerCost += $myproduct->lastbuyprice * $finalQuantity;
                    break;
                case "mean":
                    $offerCost += $myproduct->meanbuyprice * $finalQuantity;
                    break;
                case "last_discount":
                    $offerCost += $myproduct->lastbuyprice_withDiscount * $finalQuantity;
                    break;
                case "mean_discount":
                    $offerCost += $myproduct->meanbuyprice_withDiscount * $finalQuantity;
                    break;
                case "generalPrice":
                    $offerCost += $myproduct->overAllAveragePrice * $finalQuantity;
                    break;
                case "tax":
                    $offerCost += $myproduct->lastbuyprice_withTax * $finalQuantity;
                    break;
                case "mean_tax":
                    $offerCost += $myproduct->meanbuyprice_withTax * $finalQuantity;
                    break;
                default:
                    $offerCost += $myproduct->lastbuyprice * $finalQuantity;
                    break;
            }
        }


        ##3 store cost entry


        $dailyEntry->entryComment = 'تحويل بضاعة امر البيع رقم ' . $offerId . ' الى مخزن تحت التجهيز';
        $dailyEntry->fromFlag = 1;
        $dailyEntryDebtorArray = array();
        $dailyEntryCreditorArray = array();

        //from store of ##preparingStore
        $dailyEntryDebtor = new stdClass();
        $dailyEntryDebtor->value = $offerCost;
        $dailyEntryDebtor->accountstreeid = R::getCell('select treeId from store where storeId=' . $Programsettingdata->preparingStore);
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        //to store of ##bill
        $dailyEntryCreditor = new stdClass();
        $dailyEntryCreditor->value = $offerCost;
        $dailyEntryCreditor->accountstreeid = R::getCell('select treeId from store where storeId=' . $mySellbill->sellbillstoreid);
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

        $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $offerId, 'sellbillController.php?do=showoffers&sellbillid=' . $offerId);
        $dailyentryid = $returnDailyId[1];
        $mySellbillEx->executeSQLQuery("update sellbilloffer set dailyentryid='" . $dailyentryid . "' where sellbillid=$offerId");
    }
}

function reverseOfferStoreMovement($offerId) {
    global $sizeColorStoreDetailEX;

    /* -- reverse store operations on stores ------------------------ */
    $storeMovesData = R::getAll('select * from storereport where storereportmodelid =' . $offerId . ' and tablename="sellbillController.php?do=showoffers"');
    foreach ($storeMovesData as $move) {
        $storeid = $move['storeid'];
        $productId = $move['productid'];
        $sizeId = $move['sizeid'];
        $colorId = $move['colorid'];
        $billDiscountVal = $detailId = $billTotalBeforeDiscount = $totalPrice = 0;

        $sizeColorStoreDetailId = 0;
        if ($move['sizeid'] > 0 && $move['colorid'] > 0) {
            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeid, $sizeId, $colorId);
        }

        $storedetailData = getStoreDetails($storeid, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);
        $allStoredetailData = $storedetailData[0];
        $storedetailId = $storedetailData[1];
        $productquantityBefore = $storedetailData[2];
        $finalquantity = $move['productquantity'];
        if ($move['storereporttype'] == 1) { //it was decrease,so now increase
            increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else if ($move['storereporttype'] == 0) { //it was increase,so now decrease
            decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
        }
        R::exec('DELETE FROM storereport where storereportid=' . $move['storereportid']);
    }
    $dailyentryid = R::getCell('select dailyentryid from sellbilloffer where sellbillid=' . $offerId);
    //قيود اليومية
    foreach (explode(',', $dailyentryid) as $entryid) {
        reverseEntryWithItsID($entryid, 1);
    }
}

function getsellTreeIdAccontId($firstProductId, $billoperationid) {
    ## from bill operation or from service product in bill

    $sellTreeId = 0;
    if ($billoperationid > 0) {
        $sellTreeId = (int) R::getCell('select treeId from billoperation where id=' . (int) $billoperationid); ## ايرادات المبيعات
    } else {
        $pData = R::getRow('select isService,treeId from product where productId=' . (int) $firstProductId);
        if ($pData['isService'] == 1) {
            $sellTreeId = $pData['treeId']; ## ايرادات المبيعات
        }
    }

    if ($sellTreeId < 1) {
        $sellTreeId = 143; ## ايرادات المبيعات
    }

    return $sellTreeId;
}

//this function if for operations from erp to affect royal
function writePaymentToRoyalFinancialReport($sellbillclientId, $sellbillId, $returnsellbillId, $sellbilltotalPayed, $visa, $saveId, $bankAccountId, $obgyBillType, $billtype, $operation) {
    global $clientDAO;
    global $userDAO;
    global $do;
    global $Programsettingdata;

    if ($do != "addObgyVisit" && $do != "delObgyVisit" && $do != "updateObgyVisit") {
        $allDataObygyArray = array();
        if ($Programsettingdata->obygyFolder != "") {
            $bill_pay = array();
            $client = $clientDAO->load($sellbillclientId);
            $bill_pay["patient_id"] = $client->obygyPatientId; //royal

            $userData = $userDAO->load($_SESSION['userid']);
            $bill_pay["discount"] = 0; //0
            $bill_pay["user_id"] = $userData->obygyDoctorId;
            $bill_pay["user_name"] = $userData->employeename;

            $bill_pay["paymentfrom"] = 1; //erp or royal
            $bill_pay["obgyBillType"] = $obgyBillType;
            $bill_pay["billtype"] = $billtype;
            switch ($billtype) {
                case 1:
                case 3:
                    $bill_pay["bill_id"] = $sellbillId; //erp
                    $bill_pay["note"] = ''; //'erp sellbill id = ' . $sellbillId; //empty or username
                    $bill_pay["cahngeType"] = ($operation == 'add') ? 0 : 1; //0 to decrease patient balance @ royal,1 to increase it
                    break;
                case 2:
                    $bill_pay["bill_id"] = $returnsellbillId; //erp
                    $bill_pay["note"] = ''; //'erp retsellbill id = ' . $returnsellbillId; //empty or username
                    $bill_pay["cahngeType"] = ($operation == 'add') ? 1 : 0; //0 to decrease patient balance @ royal,1 to increase it
                    break;
            }



            if (!empty($sellbilltotalPayed)) { //save
                $bill_pay["detectionvalue_cash"] = $sellbilltotalPayed;
                $bill_pay["detectionvalue_visa"] = 0;
                $bill_pay["saveOrBankAccountid"] = $saveId;
                array_push($allDataObygyArray, $bill_pay);
            } else { //$paytype == "bank"
                $bill_pay["detectionvalue_cash"] = 0;
                $bill_pay["detectionvalue_visa"] = $visa;
                $bill_pay["saveOrBankAccountid"] = $bankAccountId;
                array_push($allDataObygyArray, $bill_pay);
            }
        }
        if ($Programsettingdata->obygyFolder != "" && count($allDataObygyArray) > 0) {
            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $Programsettingdata->obygyFolder . '/core/controllers/visits.php?ac=payERPBills';
            $ret = CURL_Request($allDataObygyArray, $url, 1);
            //print_r($ret);
        }
    }
}

function useSpecializedParcodeDigits($parcode, $productId, $specializedParcodeDigits) {
    $preDigits = '';
    if (strlen($productId) != $specializedParcodeDigits) {
        $noDigitsLeft = $specializedParcodeDigits - strlen($productId);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits .= '0';
        }
    }
    $newParcode = 'i' . $preDigits . $productId;
    return $newParcode;
}

function buyTheSellBill($sellbillid, $operation = 0) {
    global $Programsettingdata;

    $billData = R::getRow('select * from sellbill where sellbillid=' . $sellbillid);
    if ($billData['sellToSupplier'] > 0) {
        $detailData = R::getAll('select * from sellbilldetail where sellbillid=' . $sellbillid);

        $supplierbuybillid = 0;
        if ($billData['deletedsellid'] > 0) {
            $supplierbuybillid = (float) R::getCell('select supplierbuybillid from sellbill where sellbillid=' . $billData['deletedsellid']);
        }

        $shippingDiscountPer = (float) $_POST['supplierRatio']; //(float) R::getCell('select shippingDiscountPer from supplier where supplierid=' . $billData['sellToSupplier']);
        $shippingDiscountPer = (1 - ($shippingDiscountPer / 100));
        $allDataArray = array(
            'useERPIDs' => 1,
            'id' => $supplierbuybillid,
            'ordertype' => 0,
            'billnameid' => 1,
            'bn' => $billData['sellbilldate'],
            'supplier' => $billData['sellToSupplier'],
            'storeId' => $billData['sellbillstoreid'],
            'comment' => $billData['comment'],
            'discount_type' => ($billData['sellbilldiscounttype'] - 1),
            'gendis' => ($billData['sellbilldiscounttype'] == 1) ? ($billData['sellbilldiscount'] * $shippingDiscountPer) : $billData['sellbilldiscount'],
            //'payedtax' => $billData['tax'],
            'paymethodshipping' => $billData['paymethodshipping'],
        );

        $hidden_itr = 0;
        $total = 0;
        foreach ($detailData as $value) {
            $productnumber = R::getCell('select productnumber from productunit where productunitid=' . $value['productunitid']);
            if ($billData['whatShippingCost'] == 0) {
                $pro_price = $value['sellbilldetailtotalprice'] / ($value['sellbilldetailquantity'] * $productnumber);
            } else {
                $proData = R::getRow('select productBuyPrice,lastbuyprice,meanbuyprice,lastbuyprice_withDiscount,meanbuyprice_withDiscount,overAllAveragePrice,lastbuyprice_withTax,meanbuyprice_withTax from product where productId=' . $value['sellbilldetailproductid']);
                switch ($Programsettingdata->Inventoryevaluation) {
                    case "first":
                        $pro_price = (float) $proData['productBuyPrice'];
                        break;
                    case "last":
                        $pro_price = (float) $proData['lastbuyprice'];
                        break;
                    case "mean":
                        $pro_price = (float) $proData['meanbuyprice'];
                        break;
                    case "last_discount":
                        $pro_price = (float) $proData['lastbuyprice_withDiscount'];
                        break;
                    case "mean_discount":
                        $pro_price = (float) $proData['meanbuyprice_withDiscount'];
                        break;
                    case "generalPrice":
                        $pro_price = (float) $proData['overAllAveragePrice'];
                        break;
                    case "tax":
                        $pro_price = (float) $proData['lastbuyprice_withTax'];
                        break;
                    case "mean_tax":
                        $pro_price = (float) $proData['meanbuyprice_withTax'];
                        break;
                }
            }
            $pro_price = $shippingDiscountPer * $pro_price;
            R::exec("update sellbilldetail set lastbuyprice=$pro_price,meanbuyprice=$pro_price,lastbuyprice_withDiscount=$pro_price,meanbuyprice_withDiscount=$pro_price,lastbuyprice_withTax=$pro_price,meanbuyprice_withTax=$pro_price,lastbuyprice_withDiscountAndTax=$pro_price
               where sellbilldetailid=" . $value['sellbilldetailid']);
            ##
            $hidden_itr++;
            $allDataArray['parcode' . $hidden_itr] = $value['parcode'];
            $allDataArray['product' . $hidden_itr] = $value['sellbilldetailproductid'];
            $allDataArray['unitId' . $hidden_itr] = $value['productunitid'];
            $allDataArray['proprice' . $hidden_itr] = $pro_price;
            $allDataArray['pronum' . $hidden_itr] = $value['sellbilldetailquantity'];
            $allDataArray['hidden_prototal' . $hidden_itr] = $productnumber * $value['sellbilldetailquantity'] * $pro_price;
            $allDataArray['note' . $hidden_itr] = $value['note'];
            $allDataArray['prodis' . $hidden_itr] = 0;
            $allDataArray['discounttype' . $hidden_itr] = 0;
            $total += $allDataArray['hidden_prototal' . $hidden_itr];
        }

        $allDataArray['hidden_itr'] = $hidden_itr;
        $allDataArray['totalbeforediscount'] = $total;
        $billDiscountVal = 0;
        if ($allDataArray['discount_type'] == 0) {//direct
            $billDiscountVal = $allDataArray['gendis'];
        } else {
            $discountPer = (1 - ($allDataArray['gendis'] / 100));
            $billDiscountVal = $discountPer * $total;
        }
        //$allDataArray['taxVal'] = ($total - $billDiscountVal) * ($billData['tax'] / 100);
        $allDataArray['totalafterdiscount'] = $allDataArray['buybillaftertotalbill'] = $total - $billDiscountVal; //+ $allDataArray['taxVal']

        $paymethodshipping = (isset($billData['paymethodshipping']) && !empty($billData['paymethodshipping'])) ? $billData['paymethodshipping'] : 1;
        if ($paymethodshipping == 1) {//1 online to us buybill pay =0
            $allDataArray['genpay'] = 0;
        } elseif ($paymethodshipping == 2) {//2 cash to shipping company  buybill pay
            $allDataArray['genpay'] = $billData['sellbilltotalpayed'];
        }
        #$operation 0 => add , 1=>update
        if ($operation == 0) {
            $url = 'api_web.php?do=buybilladd';
        } elseif ($operation == 1) {
            $url = 'api_web.php?do=buybillupdate';
        }
        $ret = CURL_Request($allDataArray, $url, 0, 1, getenv('erpToken'), 'POST');
        //print_r($ret);
        $ret = json_decode($ret);
        if ($ret->status == 1 && $ret->id > 0) {
            R::exec('update sellbill set supplierbuybillid=' . $ret->id . ' where sellbillid=' . $sellbillid);
        } else {
            //echo $ret->message;
        }
        ########################################################################
    }
}

function delbuyTheSellBill($sellbillData, $ordertype) {
    if ($ordertype == 0 && $sellbillData->sellToSupplier > 0 && $sellbillData->supplierbuybillid > 0) {
        $url = 'api_web.php?do=buybilldel&ordertype=0&useERPIDs=1&id=' . $sellbillData->supplierbuybillid;
        $ret = CURL_Request(array('useERPIDs' => 1), $url, 0, 1, getenv('erpToken'), 'GET');
//        print_r($ret);
//            $ret = json_decode($ret);
        $url = 'api_web.php?do=supplierPayedDeptDel&id=' . $sellbillData->supplierDeptChangeId;
        $ret = CURL_Request(array(), $url, 0, 1, getenv('erpToken'), 'GET');
    }
}

function delSellBillPayments($sellbillid, $ordertype = 0) {
    if ($ordertype == 0) {//bill
        $allPayments = R::getAll('SELECT * FROM clientdebtchange WHERE `billid` = ? and tablename = ?', [$sellbillid, 'clientPayedDeptSellBillsController.php']);
        foreach ($allPayments as $payment) {
            $paytype = $payment['paytype'];
            $paytype = trim(explode('-', $paytype)[0]);
            if ($paytype == "خزنة") {
                $paytype = "save";
            } else if ($paytype == "بنك") {
                $paytype = "bank";
            }
            $data_arr = array(
                'clientdebtchangeId' => $payment['clientdebtchangeid'],
                'curlpost' => 1,
                'comment' => '',
                'paytype' => $paytype,
                'userId' => $_SESSION['userid'],
            );
            CURL_Request($data_arr, 'sellbillAjaxController.php?do=delMakeSellBillPayment', 0, 1, '', 'POST');
        }
    }
}

function etabill($sellbillid) {
    $responsedata = CURL_IT2(array('sellbillid' => $sellbillid), 'eBillRequests.php?do=etsellbill');
}

function qrerp($sellbillid) {

    $qrerpid = 'sellbill' . $_SESSION["qrusername"] . $sellbillid . $_SESSION["auserqrid"] . $_SESSION["qrpassword"];
    $programsettings = R::getRow("SELECT * FROM `programsettings`");

    $sellbill = R::getRow("SELECT * FROM `sellbill` LEFT JOIN store ON sellbill.sellbillstoreid = store.storeId LEFT JOIN user ON sellbill.userid = user.userid WHERE sellbillid = $sellbillid ");
    $sellbilldetail = R::getAll("SELECT * FROM `sellbilldetail` LEFT JOIN product ON sellbilldetail.sellbilldetailproductid = product.productId  WHERE sellbillid = $sellbillid ");
    $send_data = array(
        'sellbill' => json_encode($sellbill),
        'sellbilldetail' => json_encode($sellbilldetail),
        'qrusername' => $_SESSION["qrusername"],
        'qrpassword' => $_SESSION["qrpassword"],
        'auserqrid' => $_SESSION["auserqrid"],
        'qrerpid' => $qrerpid,
        'kind' => 1,
    );

    $responsedata = CURL_IT($send_data, 'http://shop.gt4host.com/qrerp/full/api/erpinsert');
    $receivedata = json_decode($responsedata);
    if ($receivedata->status != 1) {
        $qrerseilbil = R::dispense('qrerseilbil');
        $qrerseilbil->senddata = $responsedata;
        R::store($qrerseilbil);
    }
    $sellbilldate = $sellbill['sellbilldate'];
    $sellbilltotal = $sellbill['sellbillaftertotalbill'];
    $sellbilltax = round(($sellbill['sellbillaftertotalbill'] * $programsettings['vatvalueqr']), 3);
    $qrerps = qrerps($sellbilldate, $sellbilltotal, $sellbilltax);
    R::exec("UPDATE `sellbill` SET `qrerpid`='$qrerpid', `qrerpids`='$qrerps' WHERE sellbillid = $sellbillid ");
}

function qrerps($sellbilldate, $sellbilltotal, $sellbilltax) {
    $programsettings = R::getRow("SELECT * FROM `programsettings`");
    $tag[0] = checkDigit(dechex(1));
    $tag[1] = checkDigit(dechex(2));
    $tag[2] = checkDigit(dechex(3));
    $tag[3] = checkDigit(dechex(4));
    $tag[4] = checkDigit(dechex(5));

    $value[0] = $programsettings['companyname'];
    $value[1] = $programsettings['taxcard'];
    $value[2] = $sellbilldate;
    $value[3] = $sellbilltotal;
    $value[4] = $sellbilltax;

    $length[0] = checkDigit(dechex(strlen($value[0])));
    $length[1] = checkDigit(dechex(strlen($value[1])));
    $length[2] = checkDigit(dechex(strlen($value[2])));
    $length[3] = checkDigit(dechex(strlen($value[3])));
    $length[4] = checkDigit(dechex(strlen($value[4])));

    $value[0] = bin2hex($value[0]);
    $value[1] = bin2hex($value[1]);
    $value[2] = bin2hex($value[2]);
    $value[3] = bin2hex($value[3]);
    $value[4] = bin2hex($value[4]);

    $string = $tag[0] . $length[0] . $value[0] . $tag[1] . $length[1] . $value[1] . $tag[2] . $length[2] . $value[2] . $tag[3] . $length[3] . $value[3] . $tag[4] . $length[4] . $value[4];

    $qr = base64_encode(pack('H*', $string));
    return $qr;
}

function checkDigit($value) {
    if (strlen($value) === 1) {
        return "0" . $value;
    }
    return $value;
}

//from royal\core\controllers\invsdept_common.php
function sellBillAsPDF($outputMethod = "save") {
    ob_start();
    global $smarty;
    global $billsettingsData;

    require_once("../library/tcpdf/tcpdf.php");

    //$programesetting = R::findOne('programesetting');
    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Nicola Asuni');
    $pdf->SetTitle('TCPDF Example 002');
    $pdf->SetSubject('TCPDF Tutorial');
    $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    // set margins
    //    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetMargins(PDF_MARGIN_LEFT, 0, PDF_MARGIN_LEFT, true);
    $pdf->SetHeaderMargin(0);
    $pdf->SetFooterMargin(0);

    $pdf->SetPrintHeader(false);
    $pdf->SetPrintFooter(false);
    // set auto page breaks
    //    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    $pdf->SetAutoPageBreak(TRUE, 0);


    // set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
        require_once(dirname(__FILE__) . '/lang/eng.php');
        $pdf->setLanguageArray($l);
    }

    // ---------------------------------------------------------
    //    define('K_PATH_FONTS', dirname(__FILE__) . '/../library/tcpdf/');
    // Set the font for Arabic text
    $pdf->SetFont('dejavusans', '', 12, '', true);
    // Set the font encoding for Arabic text
    $pdf->SetFont('dejavusans', '', 12, '', false, 'UTF-8');

    $pdf->setRTL(true);
    // add a page
    $pdf->AddPage();


    ###########################################################################
    ## get bill data
    $sellbillId = $_GET['id'];
    //here the smarty templates
    $html = CURL_Request(array(), "sellbillprintController.php?do=showDetail2&id=$sellbillId&ordertype=0&fetchhtmlonly=1");
    ############################################################################
    //output the HTML content
    $pdf->writeHTML($html, true, false, true, false, '');


    //Close and output PDF document
    $fileName = "sellbill$sellbillId.pdf";
    if ($outputMethod == "save") {
        $pdf->Output(__DIR__ . '/../upload/billPDF/' . $fileName, 'F');
    } elseif ($outputMethod == "download") {
        $pdf->Output($fileName, 'D');
    }

    //    $invRes = R::load('investigationresults', $dataArray['invResId']);
    //    $invRes->pdf = $fileName;
    //    r::store($invRes);
    //    $res = sendPdf($fileName, $dataArray, $reDeliver);

    return $res;
}

function markStoreDetailNotInUse($storeDetailIds, $sizeColorStoreDetailIds) {
    global $myStoredetailEx;
    global $myStoredetailRecord;
    //mark storedetail as not InUSe
    if ($storeDetailIds) {
        foreach ($storeDetailIds as $id) {
            R::exec('update storedetail set inUse = 0 where storedetailid = ' . $id);
        }
    }
    if ($sizeColorStoreDetailIds) {
        foreach ($storeDetailIds as $id) {
            R::exec('update sizecolorstoredetail set inUse = 0 where id = ' . $id);
        }
    }
}

function getNetSellStatistics($client, $productsData) {
    global $myReturnsellbillEx;

    $productStatistics = array();

    $productIdsNoSizeColor = '';
    $queryString = '';
    $retQueryString = '';
    foreach ($productsData as $pro) {
        if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
            $queryString .= " and (sellbilldetailproductid=$pro->productId and sizeid=$pro->sizeid and colorid=$pro->colorid)";
            $retQueryString .= " and (returnsellbilldetailproductid=$pro->productId and sizeid=$pro->sizeid and colorid=$pro->colorid)";
            $productStatistics["hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid] = 0;
        } else { //without size and color
            $productIdsNoSizeColor .= "$pro->productId,";
            $productStatistics[$pro->productId] = 0;
        }
    }
    $productIdsNoSizeColor = trim($productIdsNoSizeColor, ",");

    if (!empty($productIdsNoSizeColor)) {
        $queryString .= " and sellbilldetailproductid in($productIdsNoSizeColor) ";
        $retQueryString .= " and returnsellbilldetailproductid in($productIdsNoSizeColor) ";
    }
    //get statistics
    $sellSumPro = R::getAll('SELECT sellbilldetailproductid AS productid,sizeid,colorid,SUM(sellbilldetail.sellbilldetailquantity) as sellbilldetailquantity
                FROM sellbill
                JOIN sellbilldetail ON (sellbill.sellbillid = sellbilldetail.sellbillid and sellbill.conditions = 0 and sellbillclientid = ' . $client . ')
                where 1
                    ' . $queryString . '
                group by sellbilldetailproductid,sizeid,colorid');
    $sellRetSumPro = R::getAll('SELECT sellbilldetailproductid AS productid,sizeid,colorid,SUM(sellandruternbilldetail.sellbilldetailquantity) as sellbilldetailquantity
                FROM sellbillandrutern
                JOIN sellandruternbilldetail ON (sellandruternbilldetail.sellbillid = sellbillandrutern.sellbillid and sellbillandrutern.conditions = 0 AND sellandruternbilldetail.selltype = 0 and sellbillandrutern.sellbillclientid =' . $client . ')
                where 1
                ' . $queryString . '
                group by sellbilldetailproductid,sizeid,colorid');
    $retSellSumPro = R::getAll('SELECT returnsellbilldetailproductid AS productid,sizeid,colorid,SUM(returnsellbilldetail.returnsellbilldetailquantity) as returnsellbilldetailquantity
                FROM returnsellbill
                JOIN returnsellbilldetail ON (returnsellbill.returnsellbillid = returnsellbilldetail.returnsellbillid and returnsellbill.conditions = 0 and returnsellbillclientid = ' . $client . ')
                where 1
                ' . $retQueryString . '
                group by returnsellbilldetailproductid,sizeid,colorid');
    foreach ($sellSumPro as $pro) {
        if ($pro['sizeid'] > 0 && $pro['colorid'] > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro['productid'] . "-" . $pro['sizeid'] . "-" . $pro['colorid']] += $pro['sellbilldetailquantity'];
        } else {
            $productStatistics[$pro['productid']] += $pro['sellbilldetailquantity'];
        }
    }

    foreach ($sellRetSumPro as $pro) {
        if ($pro['sizeid'] > 0 && $pro['colorid'] > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro['productid'] . "-" . $pro['sizeid'] . "-" . $pro['colorid']] += $pro['sellbilldetailquantity'];
        } else {
            $productStatistics[$pro['productid']] += $pro['sellbilldetailquantity'];
        }
    }

    foreach ($retSellSumPro as $pro) {
        if ($pro['sizeid'] > 0 && $pro['colorid'] > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro['productid'] . "-" . $pro['sizeid'] . "-" . $pro['colorid']] -= $pro['returnsellbilldetailquantity'];
        } else {
            $productStatistics[$pro['productid']] -= $pro['returnsellbilldetailquantity'];
        }
    }
    return $productStatistics;
}

function delLaterNakdiPayed() {
    $laterNakdiClientId = R::getCell('SELECT laterNakdiClientId from programsettings where programsettingsid = 1');
    $sellbills = R::getAll('select * from sellbill where conditions = 0 and sellbilltotalpayed = 0 and sellbillClientid = ' . $laterNakdiClientId);
    foreach ($sellbills as $bill) {
        $paymentData = R::getRow('SELECT billid, sum(clientdebtchangeamount) as clientdebtchangeamount
                FROM clientdebtchange where tablename = "clientPayedDeptSellBillsController.php" and billid  = ' . $bill['sellbillid']);
        if (!$paymentData || $paymentData['clientdebtchangeamount'] == 0) {
            delete($bill['sellbillid']);
        }
    }
}

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);
    if ($response === false) {
        echo 'Error : ' . curl_error($ch);
    }

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

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