<?php

//the global file operation
$do = $_GET['do'];
//the global file operation
if ($do != "showallajax") {
    include("../public/impOpreation.php");
}

//global varable
global $showoutside;

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

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

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


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

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

////
//get the do the action
$do = $_GET['do'];
$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");
/* ======================

  Controller Name :- propertiesCTRL

  OPERTATION in Controller

  1-display add form
  2- add in properity tbl
  3- select data from usergroup tbl
  4-add in relusergroupproperties tbl
  5-display sucess or error

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

if ($do != "showallajax") {
    //here the global templates
    $smarty->display("header.html");
}

//here goes the instances and general variables
//Sellbillandrutern
$mySellbillandrutern = new Sellbillandrutern();
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
//Sellandruternbilldetail
$mySellandruternbilldetail = new Sellandruternbilldetail();
$mySellandruternbilldetailRecord = new SellandruternbilldetailMySqlDAO();
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();
//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();
//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();
//Store
$myStoreRecord = new StoreMySqlDAO();
//Product
$myProductRecord = new ProductMySqlDAO();
$myProductEx = new ProductMySqlExtDAO();
//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Client
$myClientRecord = new ClientMySqlDAO();
$myClient = new Client();
$myClientEx = $clientEX = new ClientMySqlExtDAO();
//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();
//Billname
$myBillnameRecord = new BillnameMySqlDAO();
//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();
//User
$myUserEx = new UserMySqlExtDAO();
//Sellbilldetail
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();

$UserDAO = new UserMySqlDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//Productserial
$myProductserial = new Productserial();
$myProductserialDAO = new ProductserialMySqlDAO();
$myProductserialEx = new ProductserialMySqlExtDAO();


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

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

//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();
////
$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();
//Soldserialproduct
$soldSerialProduct = new Soldserialproduct();
$soldSerialProductDAO = new SoldserialproductMySqlDAO();
$soldSerialProductExt = new SoldserialproductMySqlExtDAO();
//
$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;
//
$bankAccount = new Bankaccount();
$bankAccountDAO = new BankaccountMySqlDAO();
$bankAccountEX = new BankaccountMySqlExtDAO();
//Buypriceshistorybook
$buyPricesHistoryBook = new Buypriceshistorybook();
$buyPricesHistoryBookDAO = new BuypriceshistorybookMySqlDAO();
$buyPricesHistoryBookEX = new BuypriceshistorybookMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//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();
////
//
$Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
$smarty->assign("Usergroupdata", $Usergroupdata);
//used for quick profit
$sellCostsArray = array();
$sellbillId = 0; //nedded for collective product##fatma
$sellbillDate = '';
//check and use the condetion that suite this action
if ($do == "editprint") {
    //here the permssion check
    include_once("../public/authentication.php");

    $sellbillId = $_GET['id'];

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


    $showDetailData = showDetail($sellbillId);
    $smarty->assign('sellbillandruternData', $showDetailData[0]);

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


    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign('ruternbilldetailData', $showDetailData[2]);
    $smarty->assign('sellQuantity', $showDetailData[3]);
    $smarty->assign('returnQuantity', $showDetailData[4]);

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

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

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

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

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

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


    $showDetailData = showDetail($sellbillId);

    //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($showDetailData[0]->visaAccountId);
    $smarty->assign('bankAccount', $bankAccount);

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

    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign('ruternbilldetailData', $showDetailData[2]);
    $smarty->assign('sellQuantity', $showDetailData[3]);
    $smarty->assign('returnQuantity', $showDetailData[4]);

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

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

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

    //here the smarty templates
    $smarty->display("sellbillandruternview/showdetail.html");
} elseif ($do == "updateReservation") {
    if (isset($_GET["reservation"]) && (int) $_GET["reservation"] == 3 && isset($_GET["sellbillid"]) && (int) $_GET["sellbillid"] > 0) {
        $sellbillid = (int) $_GET["sellbillid"];
        $bill = $mySellbillandruternRecord->load($sellbillid);
        $bill->billReservation = 3;
        $mySellbillandruternRecord->update($bill);
    }
    header('Location:' . $hosturl . '/controllers/salesreportbills.php?do=billReservation');
} elseif ($do == "delete") {
    include_once("../public/authentication.php");

    $sellbillId = $_GET['sellbillid']; //$sellbillId; //nedded for collective product##fatma
    $billReservation = (int) $_GET['reservation'];
    $note;
    try {
        $deleteData = delete($sellbillId);

        $saveValuebeforeValid = $deleteData[0];
        $productsBeforeValid = $deleteData[1];
        if ($billReservation == 4) {
            header('Location:' . $hosturl . '/controllers/salesreportbills.php?do=billReservation');
        } elseif ($saveValuebeforeValid == 1 && $productsBeforeValid == 1) {
            header("location:?do=sucess");
        } elseif ($saveValuebeforeValid == 0 && $productsBeforeValid == 1) {
            $note = "لا يوجد  بالخزنة المبلغ الكافى لحذف الفاتورة";
        } elseif ($saveValuebeforeValid == 1 && $productsBeforeValid == 0) {
            $note = "لا يوجد بالمخزن الكمية الكافية لحذف الفاتورة";
        } elseif ($saveValuebeforeValid == 0 && $productsBeforeValid == 0) {
            $note = "لا يوجد بالخزنة والمخزن الكمية الكافية لحذف الفاتورة";
        }

        $url = "sellbillandruternController.php?do=show";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $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);
    //$sellbillandruternSearchData=loadAllSellAndReturnBill();
    //$smarty->assign("sellbillandruternSearchData",$sellbillandruternSearchData);


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


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

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

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

    /* 	$startDate=$_REQUEST['from'];
      $endDate=$_REQUEST['to'];
      $sellbillSerial=$_REQUEST['sellbillserial'];
      $sellbillId=$_REQUEST['sellbillid'];
      $clientId=$_REQUEST['clientid'];

      if(isset($clientId) && $clientId != "-1")
      {
      showByClient($clientId);
      $messageData =  $myClientRecord->load($clientId);
      $message = "إسم العميل: ".$messageData->clientname;
      $smarty->assign("message",$message);
      }
      elseif(isset($sellbillSerial) && $sellbillSerial != "")
      {
      showBySriral($sellbillSerial);
      $message = "رقم الفاتورة: ".$sellbillSerial;
      $smarty->assign("message",$message);
      }
      elseif(isset($sellbillId) && $sellbillId != "")
      {
      showBySellbillId($sellbillId);

      $message = "رقم الفاتورة: ".$sellbillSerial;
      $smarty->assign("message",$message);
      }
      elseif(isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "")
      {
      showByDate($startDate,$endDate);

      $message = "من تاريخ : ".$startDate." إلى تاريخ : ".$endDate."";
      $smarty->assign("message",$message);
      }
      else
      {
      showAll(date("Y-m-d"), date("Y-m-d"));

      $message = "من تاريخ : ".date("Y-m-d")." إلى تاريخ : ".date("Y-m-d")."";
      $smarty->assign("message",$message);
      } */
    showAll();
    $smarty->display("sellbillandruternview/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "executeOperation") {
    include_once("../public/authentication.php");

    executeOperation();

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

    $sellbillandruternSearchData = loadAllSellAndReturnBill();
    $smarty->assign("sellbillandruternSearchData", $sellbillandruternSearchData);

    //showAll();

    $smarty->display("sellbillandruternview/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "showallajax") {
    showallajax();
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}

//here the global templates
if ($do != "showallajax") {
    $smarty->display("footer.html");
}

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

// select from Billname tbl
function loadBillProperty($billnameid) {
    //to use the variable out side the funcion
    global $myBillsettingEx;

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

//load sellbill detail
function showDetail($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);

    ##use currency values
    if (isset($billCurrData) && !empty($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;
        }
    }

    $returnQuantity = 0;
    foreach ($ruternbilldetailData as $ruternbilldetail) {
        $returnQuantity = $returnQuantity + $ruternbilldetail->sellbilldetailquantity;
    }

    return array($sellbillandruternData, $sellbilldetailData, $ruternbilldetailData, $sellQuantity, $returnQuantity);
}

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

    // select all data from client tbl
    $clientData = $myClientRecord->queryAll();
    return $clientData;
}

//select data from client tbl
function loadAllSellAndReturnBill() {
    global $mySellbillandruternRecord;

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

//load client by Id tbl
function loadClientDataById($clientId) {
    global $myClientRecord;

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

function showAll() {
    global $mySellbillandruternEx;
    global $myClientRecord;
    global $UserDAO;
    global $ProgramsettingDAO;
    global $smarty;
    global $myStoreRecord;
    global $mySaveRecord;


    $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'];
    $storeid = $_REQUEST['storeid'];
    $saveid = $_REQUEST['saveid'];
    $hideDel = (int) $_REQUEST['hideDel'];

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


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


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

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


        $messageData = $UserDAO->load($sellerid);
        $message .= "<br> إسم {if $Programsettingdata->delegate_seller eq 0} بائع {elseif $Programsettingdata->delegate_seller == 1}مندوب {elseif $Programsettingdata->delegate_seller == 2}طبيب {/if}: " . $messageData->employeename;


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



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


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


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

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

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


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


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

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

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

        $queryString .= ' sellbillandrutern.sellbillsaveid = ' . $saveid . ' AND';
    }
    if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        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 .= ' sellbillandrutern.sellbilldate >= "' . $startDate . '" and sellbillandrutern.sellbilldate <=  "' . $endDate . '" AND';
    }
    if (isset($hideDel) && $hideDel == 1) {
        $message .= "<br> اخفاء المحذوف ";
        $queryString .= ' sellbillandrutern.conditions = 0 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');
    //var_dump($getTodayBills);
    //if ($queryString == "") {
    if ($getTodayBills == 1) {
        $queryString = "";
        $today = date("Y-m-d");
        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        ################
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $startDate = $startYesterday;
            $endDate = $endYesterday;
        } else {
            $startDate = $startToday;
            $endDate = $endToday;
        }
        ##############

        $queryString .= ' where  sellbillandrutern.sellbilldate >= "' . $startDate . '" and sellbillandrutern.sellbilldate <=  "' . $endDate . '" ';
    }

    //hide old edit or deleted bills
    //$queryString .= ' and  sellbillandrutern.conditions = 0 ';

    $totalBills = 0;

    if ($queryString) {
        $sellbillandruternData = $mySellbillandruternEx->queryallWithqueryString($queryString);
    }

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

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

    $totalBills = 0;

    $sellbillandruternData = $mySellbillandruternEx->queryWithClientId($clientId);

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

function showBySriral($serial) {
    global $mySellbillandruternEx;
    global $smarty;

    $totalBills = 0;

    $sellbillandruternData = $mySellbillandruternEx->queryWithSerail($serial);

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

function showBySellbillId($sellbillId) {
    global $mySellbillandruternEx;
    global $smarty;

    $totalBills = 0;

    $sellbillandruternData = $mySellbillandruternEx->queryWithSellbillid($sellbillId);

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

function showByDate($startDate, $endDate) {
    global $mySellbillandruternEx;
    global $smarty;

    $totalBills = 0;

    $sellbillandruternData = $mySellbillandruternEx->queryWithDate($startDate, $endDate);

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

function delete($sellbillid) {
    global $mySellbillandrutern;
    global $mySellbillandruternRecord;
    global $mySellbillandruternEx;
    global $mySellandruternbilldetail;
    global $mySellandruternbilldetailRecord;
    global $mySellandruternbilldetailEx;
    global $myProductserialEx;


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

    global $CostcenterdetailDAO;
    global $Costcenterdetail;
    global $CostcenterdetailEX;

    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $soldSerialProductExt;

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

    createClientInUseSP(2);
    liveBackupComment("-- bill delete start - sellbillandreturn with id = $sellbillid");
    //Transaction
    $mytransactions = new Transaction();

    try {
        $sellbillandruternData = $mySellbillandruternRecord->load($sellbillid);
        if ($sellbillandruternData->conditions == 0) {
            $CostcenterdetailEX->updatedellbytypeandmodelid(2, $sellbillid, 1);





            $dailyentryid = $sellbillandruternData->dailyentryid;
            $sellbilltotalPayed = $sellbillandruternData->sellbilltotalpayed;
            $sellbillstoreId = $sellbillandruternData->sellbillstoreid;
            $sellbilltotaldeptAfter = $sellbillandruternData->sellbilltotaldeptafter;
            $sellbilltotaldeptBefor = $sellbillandruternData->sellbilltotaldeptbefor;
            $sellbillclientId = $sellbillandruternData->sellbillclientid;
            $sellbillFinalbill = $sellbillandruternData->sellbillfinalbill;
            $sellbillsaveId = $sellbillandruternData->sellbillsaveid;
            $sellbilltotalBill = $sellbillandruternData->sellbilltotalbill;
            $sellbillprice = $sellbillandruternData->sellbillprice;
            $returnsellbillprice = $sellbillandruternData->returnsellbillprice;
            $sellbillDiscount = $sellbillandruternData->sellbilldiscount;
            $sellbillDiscountType = $sellbillandruternData->sellbilldiscounttype;
            $sellbillDate = $sellbillandruternData->sellbilldate;

            $visa = $sellbillandruternData->visaPayed;
            $visaAccount = $sellbillandruternData->visaAccountId;
            if (empty($visaAccount)) {
                $visa = 0;
            }
            $isBankAccountTransfer = $sellbillandruternData->isBankAccountTransfer;

            ##get $billTotalBeforeDiscount
            $billTotalBeforeDiscount = $sellbilltotalBill;
            ##get $billDiscountVal
            $billDiscountVal = $sellbillDiscount;
            if ($sellbillDiscountType == "2") {
                $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
                $billDiscountVal = round($billDiscountVal, 2);
            }
            ########################################################################
            $totalOperationCost = $sellbillAftertotalBill = $sellbillandruternData->sellbillaftertotalbill;


            $saveValuebeforeValid = 1;
            $productsBeforeValid = 1;
            $note;

            /////////////////check save value before //////////////
            //get save value
            $saveValueBefore = getSaveValueBefore($sellbillsaveId);
            $saveValueafterValid = $saveValueBefore - $sellbilltotalPayed - $visa;


            if ($saveValueafterValid >= 0) {
                $saveValuebeforeValid = 1;

                $note = "success";
            } else {
                $saveValuebeforeValid = 0;

                $note = "لا يوجد بالخزنة المبلغ الكافى لحذف الفاتورة <br/>";
                //return $saveValuebeforeValid;
            }



            /////////////////check store product quantity before //////////////

            $returnsellbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 1);

            foreach ($returnsellbilldetailData as $returnsellbilldetail) {
                $productId = $returnsellbilldetail->sellbilldetailproductid;
                $productQuantity = $returnsellbilldetail->sellbilldetailquantity;
                $sizeId = $returnsellbilldetail->sizeid;
                $colorId = $returnsellbilldetail->colorid;

                $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                $isService = isService($productId);
                if ($isService == 0) {//if product
                    //get storefrom productquantity before change
                    $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId);

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

                    if ($productquantityBefore > 0 && count($allStoredetailData) > 0) {
                        $productsAfterValid = $productquantityBefore - $productQuantity;

                        if ($productsAfterValid >= 0) {
                            $productsBeforeValid = 1;

                            $note = "success";
                        } else {
                            $productsBeforeValid = 0;

                            $note .= "لا يوجد بالمخزن الكمية الكافية لحذف الفاتورة";

                            //return $productsBeforeValid;
                        }
                    } else {
                        $productsBeforeValid = 0;

                        $note .= "لا يوجد بالمخزن الكمية الكافية لحذف الفاتورة";

                        //return $productsBeforeValid;
                    }
                }
            }




            //update conditions in sellbillandreturn tbl
            $mySellbillandrutern->conditions = 1;
            $mySellbillandrutern->sellbillsysdate = date("Y-m-d H:i:s");
            //$mySellbillandrutern->userid = $_SESSION['userid'];
            $mySellbillandrutern->userid = $sellbillandruternData->userid;
            $mySellbillandrutern->delbyuserid = $_SESSION['userid'];
            $mySellbillandrutern->sellbillid = $sellbillid;

            $billReservation = $sellbillandruternData->billReservation;
            if (isset($_GET["reservation"]) && (int) $_GET["reservation"] == 4) {
                $billReservation = 4;
            }


            foreach (explode(',', $dailyentryid) as $entryid) {
                reverseEntryWithItsID($entryid, 1);
            }


            $mySellbillandruternEx->updateConditions($mySellbillandrutern, " ,billReservation= $billReservation,billReservationDate='0000-00-00' ");



            //مبيعات
            $sellbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 0);


            foreach ($sellbilldetailData as $sellbilldetail) {

                $productId = $sellbilldetail->sellbilldetailproductid;
                $quantity = $sellbilldetail->sellbilldetailquantity;
                $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);

                //print_r('<br>scunitname' . $scunitname);
                $productunitId = $sellbilldetail->productunitid;
                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, 1, '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 = 1; //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, $totlPrice, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId);


                            //insert in storereport
                            insertStorereport($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillid, "حذف فاتورة مبيعات ومردودات", "sellbillandruternController.php", $sizeId, $colorId);
                        } else {
                            //insert in storedetail tbl
                            insertStoredetail($sellbillstoreId, $productId, $finalquantity, $totlPrice, $billDiscountVal, $billTotalBeforeDiscount);


                            //insert in storereport
                            insertStorereport($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillid, "حذف فاتورة مبيعات ومردودات", "sellbillandruternController.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, "حذف  فاتورة مبيعات ومردودات", "sellbillandruternController.php", $mydate, 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", $mydate, 1);
                                }
                            }
                        }
                    }
                }
            }



            //مردودات
            foreach ($returnsellbilldetailData as $returnsellbilldetail) {
                $productId = $returnsellbilldetail->sellbilldetailproductid;
                $quantity = $returnsellbilldetail->sellbilldetailquantity;
                $productunitId = $returnsellbilldetail->productunitid;
                $scunitname = $returnsellbilldetail->otherdetailquantity;
                $detailId = $returnsellbilldetail->sellbilldetailid;
                $totlPrice = $returnsellbilldetail->returnsellbilldetailtotalprice;

                $sizeId = $returnsellbilldetail->sizeid;
                $colorId = $returnsellbilldetail->colorid;
                $proSerials = $returnsellbilldetail->soldSerialsInDetails;

                $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);

                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;




                if (!empty($proSerials)) {
                    decreaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $sellbillid, $sellbillclientId, $detailId, 4, 'del');
                } else {


                    $parcode = $returnsellbilldetail->parcode;
                    $issold = $myProductserialEx->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");


                    if (count($issold) > 0) {


                        $soldSerialProduct->quantity = $finalquantity;
                        $soldSerialProduct->sellbilltype = 4; //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($productserailid, $finalquantity);
                            //insertIntoSoldSerialProduct($productserailid, $finalquantity, $sellbillid, 4,$sellbillclientId);
                        }
                    }
                }


                if (isset($productId) && $productId != '-1') {
                    $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, $totlPrice, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId);



                            //insert in storereport
                            insertStorereport($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillid, "حذف فاتورة مبيعات ومردودات", "sellbillandruternController.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, 1, $sellbillid, "تعديل فاتورة مردودات  ومبيعات", "sellbillandruternController.php", $mydate, 1);
                            } 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", $mydate, 1);
                                }
                            }
                        }
                    }
                }
            }



            $sellbilltotalPayed = $sellbilltotalPayed - $visa;
            if ($sellbillclientId != 0) {
                //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                {
                    $clientData = getClientDataFromClientInUseSP($sellbillclientId);
                    //$clientData = loadClientDataById($sellbillclientId);
                    $clientdeptBefor = $clientData->clientdebt;

                    if ($sellbilltotalBill < 0) {
                        $sellbillFinalbill = $sellbillFinalbill * -1;
                        $clientdeptAfter = ($clientData->clientdebt) + $sellbillFinalbill;
                        insertClientdebtchange($sellbillclientId, $clientdeptBefor, $sellbillFinalbill, 0, "حذف فاتورة مبيعات ومردودات", $sellbillid, $clientdeptAfter, "sellbillandruternController.php", "حذف فاتورة  مبيعات ومردودات", $totalOperationCost, $visa, $visaAccount, $sellbilltotalPayed);
                    } else {
                        $clientdeptAfter = ($clientData->clientdebt) - $sellbillFinalbill;
                        insertClientdebtchange($sellbillclientId, $clientdeptBefor, $sellbillFinalbill, 1, "حذف فاتورة مبيعات ومردودات", $sellbillid, $clientdeptAfter, "sellbillandruternController.php", "حذف فاتورة  مبيعات ومردودات", $totalOperationCost, $visa, $visaAccount, $sellbilltotalPayed);
                    }

                    //update rawmaterialssupplierdebt
                    updateClientDebt($sellbillclientId, $clientdeptAfter);
                    markClientAsNOTInUse($sellbillclientId);
                }
            }


            //check if payed or not to change save value
            if ($sellbilltotalPayed != 0) {
                if ($sellbillAftertotalBill > 0) {
                    //get saveValue before and saveValue after mins sellbilltotalPayed
                    $saveData = getSaveValueAndMins($sellbillsaveId, $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
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedaily($saveValuebefore, $sellbilltotalPayed, 1, $saveId, "حذف فاتورة مبيعات ومردودات", $sellbillid, $saveValueafter, "sellbillandruternController.php");
                    unset($_SESSION['client_id']);
                } else {
                    //get saveValue before and saveValue after mins sellbilltotalPayed
                    $saveData = getSaveValueAndPlus($sellbillsaveId, 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
                    $_SESSION['client_id'] = $sellbillclientId;
                    insertSavedaily($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "حذف فاتورة مبيعات ومردودات", $sellbillid, $saveValueafter, "sellbillandruternController.php");
                    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, 1, "الغاء سداد فاتورة", "sellbillandruternController.php", $sellbillid);

                    //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);
                    }
                } 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, 0, "الغاء سداد فاتورة", "sellbillandruternController.php", $sellbillid);

                    //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);
                    }
                }
            }
            quickProfitBill($sellbillprice, $returnsellbillprice, $billDiscountVal, $sellbillclientId, 0);
        }

        $mytransactions->commit();
    } catch (Exception $e) {
        $note = "حدث خطأ اثناء حذف الفاتورة";
        $mytransactions->rollback();
        $sellbillandruternData = $mySellbillandruternRecord->load($sellbillid);
        $sellbillclientId = $sellbillandruternData->sellbillclientid;
        markClientAsNOTInUse($sellbillclientId);
    }

    liveBackupComment("-- bill delete end - sellbillandreturn with id = $sellbillid");
    return array($saveValuebeforeValid, $productsBeforeValid, $note);
}

function executeOperation() {
    //to use the variable out side the funcion
    global $mySellbillandruternRecord;
    global $smarty;

    $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
            $sellbillandruternData = $mySellbillandruternRecord->load($sellbillId);
            $sellbillSerial = $sellbillandruternData->sellbillserial;

            if ($operationType == '1') {
                //tempdelete
                $note = delete($sellbillId);
                if ($note[2] != "success") {
                    $outputString .= $sellbillSerial . ": " . $note[2] . "<br/>";
                } else {
                    $outputString .= $sellbillSerial . ": تمت العملية بنجاح <br/>";
                }
            }
        }

        $smarty->assign("outputString", $outputString);
    }
}

////////////////////////////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) {

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

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged) {

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

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

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

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = date("Y-m-d H:i:s");
    $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;

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

    return array($storedetailData, $storedetailId, $productquantityBefore);
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId) {

    //to use the variable out side the funcion
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $myProductRecord;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    global $productIngredientsEX;
    global $sellbillId; //nedded for collective product##fatma
    //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);
        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);

        $myStoredetail->productid = $sizecolorstoredetail->productid;
        $myStoredetail->storeid = $sizecolorstoredetail->storeid;


        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, abs($productChangeAmount), 1);
        //affect product to make it have total quantity
        $storeDetailData = $myStoredetailEx->queryWithStoreAndProductandunit($sizecolorstoredetail->productid, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $productChangeAmount, date("Y-m-d"));
        } 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 {
        $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($myStoredetail->productid);
        //update productquantity in storedetail tbl
        if (count($ingridients) == 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");
            $myStoredetail->productquantity = $productquantityAfter;

            $myStoredetailEx->updateProductquantity($myStoredetail);
            onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, abs($productChangeAmount), 1);
        }
    }
    $buyProduct = $myProductRecord->load($myStoredetail->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);
    quickProfitRow($buyProduct, $productChangeAmount, 0, 0, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $myStoredetail->storeid);
    //sell delete - increse
    $isCollectiveFlag = ifCollectiveIncreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $myStoredetail->storeid);
    return $productquantityAfter;
}

//update and decrease Rawmaterialamount in storerawmaterialdetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId) {

    //to use the variable out side the funcion
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $myProductRecord;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    global $productIngredientsEX;
    global $sellbillId; //nedded for collective product##fatma
    //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);
        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);

        $myStoredetail->productid = $sizecolorstoredetail->productid;
        $myStoredetail->storeid = $sizecolorstoredetail->storeid;


        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, (abs($productChangeAmount) * -1), 1);
        //affect product to make it have total quantity
        $storeDetailData = $myStoredetailEx->queryWithStoreAndProductandunit($sizecolorstoredetail->productid, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $productChangeAmount, date("Y-m-d"));
        } 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 {
        $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($myStoredetail->productid);

        //update productquantity in storedetail tbl
        if (count($ingridients) == 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");
            $myStoredetail->productquantity = $productquantityAfter;

            $myStoredetailEx->updateProductquantity($myStoredetail);
            onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, (abs($productChangeAmount) * -1), 1);
        }
    }
    $buyProduct = $myProductRecord->load($myStoredetail->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);
    quickProfitRow($buyProduct, $productChangeAmount, 1, 0, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $myStoredetail->storeid);
    //ret sell delete - decrease
    $isCollectiveFlag = ifCollectiveDecreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $myStoredetail->storeid);
    return $productquantityAfter;
}

//add in storerawmaterialdetails tbl
function insertStoredetail($storeid, $productid, $productChangeAmount, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId) {

    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $myProductRecord;
    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");
        $myStoredetail->productquantity = $productChangeAmount;
        $myStoredetail->storeid = $storeid;
        $myStoredetail->productid = $productid;

        $myStoredetailRecord->insert($myStoredetail);
    } else {
        $myStoredetailEx->updateQuantityWithSumChild($row->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $storeid, $productid);
    }




    ##
    $buyProduct = $myProductRecord->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;
    }
    quickProfitRow($buyProduct, $productChangeAmount, 0, 0, $prototal, $billDiscountVal, $billTotalBeforeDiscount, $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");
    $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);
}

// 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 = $totalOperationCost;
    $myClientdebtchange->dailyentryid = 0;
    $myClientdebtchange->userSelectedDate = $sellbillDate;

    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

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

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

function getStoreDetails($storeId, $productId, $unittype, $sizeColorStoreDetailId, $sizeId, $colorId) {
    // get productquantity from storedetail tbl
    global $myStoredetailEx;
    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 = $myStoredetailEx->queryWithStoreAndProductandunit($productId, $storeId, $unittype);

        $storeDetailId = $storeDetailData->storedetailid;
        $productQuantityBefore = $storeDetailData->productquantity;
    }
    return array($storeDetailData, $storeDetailId, $productQuantityBefore);
}

function insertStorereportupdate2($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $mydate, $unittype) {
    global $myStorereport;
    global $myStorereportEx;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = $mydate; //date("Y-m-d");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];
    $myStorereport->unittype = $unittype;

    // print_r($myStorereport);

    $myStorereportEx->insertEX($myStorereport);
}

//add in storedetails tbl
function insertStoredetailupdate2($storeid, $productid, $productChangeAmount, $mydate, $unittype) {
    global $myStoredetail;
    global $myStoredetailEx;

    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = $mydate; //date("Y-m-d");
    $myStoredetail->productquantity = $productChangeAmount;
    $myStoredetail->storeid = $storeid;
    $myStoredetail->productid = $productid;
    $myStoredetail->unittype = $unittype;
    /*  print_r("<pre>");
      print_r($storeDetail);
      print_r("<pre>"); */

    $myStoredetailEx->insertEX($myStoredetail);
}

function updateProductQuantitotherunit2($storedetailId, $productquantityAfter, $unittype) {
    global $myStoredetail;
    global $myStoredetailEx;


    //update productquantity in storedetail tbl


    $myStoredetailEx->updateProductquantity2($storedetailId, $_SESSION['userid'], date("Y-m-d"), $productquantityAfter, $unittype);

    return $productquantityAfter;
}

function isService($id) {

    global $myProductRecord;

    $pro = $myProductRecord->load($id);
    return $pro->isService;
}

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->returnSellVal = 0;
        $obj->returnSellCostBuyPrice = 0;
        $obj->returnSellCostLastBuyPrice = 0;
        $obj->returnSellCostMeanBuyPrice = 0;
        $obj->returnSellCostLastBuyPricewithDiscount = 0;
        $obj->returnSellCostMeanBuyPricewithDiscount = 0;
        $obj->returnSellCostOverAllAveragePrice = 0;
        $obj->returnSellCostLastBuyPricewithTax = 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->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->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["returnSellCostBuyPrice"] += $obj->returnSellCostBuyPrice;
    $sellCostsArray["returnSellCostLastBuyPrice"] += $obj->returnSellCostLastBuyPrice;
    $sellCostsArray["returnSellCostMeanBuyPrice"] += $obj->returnSellCostMeanBuyPrice;
    $sellCostsArray["returnSellCostLastBuyPricewithDiscount"] += $obj->returnSellCostLastBuyPricewithDiscount;
    $sellCostsArray["returnSellCostMeanBuyPricewithDiscount"] += $obj->returnSellCostMeanBuyPricewithDiscount;
    $sellCostsArray["returnSellCostOverAllAveragePrice"] += $obj->returnSellCostOverAllAveragePrice;
}

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 ifCollectiveProductReCalculateCost($buyProduct) {
    global $productIngredients;
    global $productIngredientsEX;
    global $productDAO;

    //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;
        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->productBuyPrice = round($buyProduct->productBuyPrice, 1);
        $buyProduct->lastbuyprice = round($buyProduct->lastbuyprice, 1);
        $buyProduct->lastbuyprice_withDiscount = round($buyProduct->lastbuyprice_withDiscount, 1);
        $buyProduct->meanbuyprice = round($buyProduct->meanbuyprice, 1);
        $buyProduct->meanbuyprice_withDiscount = round($buyProduct->meanbuyprice_withDiscount, 1);
        $buyProduct->overAllAveragePrice = round($buyProduct->overAllAveragePrice, 1);
        $productDAO->update($buyProduct);
    } else {
        //make no change to prices
    }
    return $buyProduct;
}

function ifCollectiveIncreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $sellbillstoreId) {
    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 = "فاتورة مبيعات ومردودات بها منتج تجميعى - $buyProduct->productName";
        $controllerLink = "sellbillandruternController.php";

        $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
            insertStorereport($productId, $sellbillstoreId, $ingridientChangeAmount, $productquantityBefore, $productquantityAfter, 0, $sellbillId, $commentCollective, $controllerLink);
        } 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
            insertStorereport($productId, $sellbillstoreId, $ingridientChangeAmount, 0, $ingridientChangeAmount, 0, $sellbillId, $commentCollective, $controllerLink);
        }
    }
    return count($ingridients); //as flag if collective pro
}

function ifCollectiveDecreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $sellbillstoreId) {
    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 = "فاتورة مبيعات ومردودات بها منتج تجميعى - $buyProduct->productName";
        $controllerLink = "sellbillandruternController.php";

        $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
            insertStorereport($productId, $sellbillstoreId, $ingridientChangeAmount, $productquantityBefore, $productquantityAfter, 1, $sellbillId, $commentCollective, $controllerLink);
        } 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
            insertStorereport($productId, $sellbillstoreId, $ingridientChangeAmount, 0, $ingridientChangeAmount, 1, $sellbillId, $commentCollective, $controllerLink);
        }
    }
    return count($ingridients); //as flag if collective pro
}

function createClientInUseSP($clientid) {
    global $clientEX;
    if ((int) $clientid > 1) {
        $clientEX->createClientInUseSP();
    }
}

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 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 insertBankAccountMovement($accountId, $bankId, $beforeVal, $amount, $afterVal, $type, $comment, $tablename, $modelId) {
    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 = date('Y-m-d H:i:s');
        $accountMove->userid = $_SESSION['userid'];
        $accountMoveDAO->insert($accountMove);
    }
}

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 $mySellbillandruternEx;
    global $ProgramsettingDAO;
    global $UsergroupDAO;
    $sIndexColumn = "sellbillid";

    /* DB table to use */
    $sTable = "sellbillandruternview";
    $aColumns = array('sellbillid', '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 = "";

    //$pricetype = $_REQUEST['pricetype'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['sellbillid'];
    $clientId = $_REQUEST['clientid'];
    $sellerid = $_REQUEST['sellerid'];
    $selleruserid = $_REQUEST['selleruserid'];
    $storeid = $_REQUEST['storeid'];
    $saveid = $_REQUEST['saveid'];

    ##fatma
    $search = $_REQUEST['searchDate'];
    if (empty($search)) {
        $search = "dateOnly";
    }




    //    if (isset($pricetype) && $pricetype != "-1") {
    //        $queryString .= ' pricetype = ' . $pricetype . ' AND';
    //    }
    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($saveid) && $saveid != "-1") {
        $queryString .= ' sellbillsaveid = ' . $saveid . ' AND';
    }
    ##needed Data
    $Programsetting = $ProgramsettingDAO->load(1);
    $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
    $billsettingsData = loadBillProperty(5); //3 is for sell bill and return
    ##############
    if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        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 == "") {
        $today = date("Y-m-d");
        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        ################
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $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 = $mySellbillandruternEx->runSelectQuery($sQuery);

    /* Data set length after filtering */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as sellbillid  FROM  $sTable $sWhere "; //$sOrder
    $rResultFilterTotal = $mySellbillandruternEx->runSelectQuery($sQuery);
    foreach ($rResultFilterTotal as $oneis) {
        $countis = $oneis->sellbillid;
    }
    $iFilteredTotal = $countis;
    /* Total data set length */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as sellbillid FROM  $sTable";
    $rResultTotal = $mySellbillandruternEx->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();
        // '8 sellQuantity', '9 returnsellQuantity', '10 sellbilltotalpayed', '11 sellbillfinalbill', '12 newSellbillidAfterEdit', '13 conditions', '14 dailyentryid');
        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 "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="sellbillandruternController.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=editsellandrutrnBill&sellbillid=' . $aRow->sellbillid . '" type="button" class="btn btn-default btn-lg editicon"></a>';
                $row[] = '<a href="sellbillandruternController.php?do=delete&sellbillid=' . $aRow->sellbillid . '" 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) {//not del not the old edit of bill
            $sellQuantity += $aRow->sellQuantity - $aRow->returnsellQuantity;
            $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 liveBackupComment($txt) {
    $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
    $toWrite = "\r\n-- ----------------------------------------------------------------------------------------------------\r\n";
    $toWrite .= $txt;
    $toWrite .= "\r\n-- ----------------------------------------------------------------------------------------------------\r\n\r\n";
    fwrite($myfile, $toWrite);
}

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

?>