<?php

//the global file operation
$do = $_GET['do'];
if ($do != "showallajax" && (!isset($_POST['curlpost']) || empty($_POST['curlpost']))) {
    include("../public/impOpreation.php");
}
include_once("initiateStaticSessionCommingWithCurl.php");
//global varable
global $showoutside;

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


//here the db files that include in the file
include("../public/include_dao.php");
//Returnsellbill
require_once('../models/dao/ReturnsellbillDAO.class.php');
require_once('../models/dto/Returnsellbill.class.php');
require_once('../models/mysql/ReturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillMySqlExtDAO.class.php');

//Returnsellbilldetail
require_once('../models/dao/ReturnsellbilldetailDAO.class.php');
require_once('../models/dto/Returnsellbilldetail.class.php');
require_once('../models/mysql/ReturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbilldetailMySqlExtDAO.class.php');


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

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


//here the global templates
if ($do != "showallajax" && (!isset($_POST['curlpost']) || empty($_POST['curlpost']))) {
    $smarty->display("header.html");
}


//here goes the instances and general variables
//Returnsellbill
$myReturnsellbill = new Returnsellbill();
$myReturnsellbillRecord = new ReturnsellbillMySqlDAO();
$myReturnsellbillEx = new ReturnsellbillMySqlExtDAO();

//Returnsellbilldetail
$myReturnsellbilldetail = new Returnsellbilldetail();
$myReturnsellbilldetailRecord = new ReturnsellbilldetailMySqlDAO();
$myReturnsellbilldetailEx = new ReturnsellbilldetailMySqlExtDAO();

//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();

//Store
$myStoreRecord = new StoreMySqlDAO();

//Sellbilldetail
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();

//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();
$UserDAO = new UserMySqlDAO();

//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//Productserial
$myProductserial = new Productserial();
$myProductserialDAO = new ProductserialMySqlDAO();
$myProductserialEx = new ProductserialMySqlExtDAO();
//Soldserialproduct
$soldSerialProduct = new Soldserialproduct();
$soldSerialProductDAO = new SoldserialproductMySqlDAO();
$soldSerialProductExt = new SoldserialproductMySqlExtDAO();



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

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

$myUserRecord = new UserMySqlDAO();
//
$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 condition that suite this action
if ($do == "editprint") {
    include_once("../public/authentication.php");

    $returnsellbillId = $_GET['id'];

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


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

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

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

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

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

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

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

    $returnsellbillid = $_GET['returnsellbillid'];

    $mysellbilldata = $myReturnsellbillRecord->load($returnsellbillid);
    $smarty->assign("returnmysellbilldata", $mysellbilldata);


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


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


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


    //get  sell bill detales data
    $mysellbildetales = $myReturnsellbilldetailEx->queryWithReturnsellbillId($returnsellbillid);
    $i = 1;
    foreach ($mysellbildetales as $mydetales) {

        $myunitdata = $myProductunitEx->queryWithProductId($mydetales->returnsellbilldetailproductid);
        $smarty->assign("myunitdata" . $i, $myunitdata);
        $i++;
    }
    $smarty->assign("returnmysellbildetales", $mysellbildetales);

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




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

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

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

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

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

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

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




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

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

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

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

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


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


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

        $smarty->assign("customeditsellbill", 1);
        $smarty->assign("customsellbill", 1);
        //$smarty->assign("customreturnsellbill",1);
        $smarty->assign("customsellbillModel", 1);
        $smarty->assign("customSellProductModel", 1);
    } else {
        header("location:sellbillController.php");
    }
} elseif ($do == "updateReservation") {
    if (isset($_GET["reservation"]) && (int) $_GET["reservation"] == 3 && isset($_GET["returnsellbillid"]) && (int) $_GET["returnsellbillid"] > 0) {
        $sellbillid = (int) $_GET["returnsellbillid"];
        $bill = $myReturnsellbillRecord->load($sellbillid);
        $bill->billReservation = 3;
        $myReturnsellbillRecord->update($bill);
    }
    header('Location:' . $hosturl . '/controllers/salesreportbills.php?do=billReservation');
} elseif ($do == "showDetail") {
    include_once("../public/authentication.php");

    $returnsellbillId = $_GET['returnsellbillid'];
    $smarty->assign('billId', $returnsellbillId);
    $showDetailData = showDetail($returnsellbillId);

    //getalldiscount
    $taxvalue = 0;
    $sellbilldiscount = $showDetailData[0]->returnsellbilldiscount;
    $sellbilldiscounttype = $showDetailData[0]->returnsellbilldiscounttype; //1 مباشر
    $sellbilltotalbill = $showDetailData[0]->returnsellbilltotalbill;
    $sellbillaftertotalbill = $showDetailData[0]->returnsellbillaftertotalbill;
    $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("taxvalue", $taxvalue);
    $smarty->assign("discountvalue", $discountvalue);


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

    $smarty->assign('returnsellbillData', $showDetailData[0]);

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


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

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

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

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

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

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

    $sellbillId = $returnsellbillId = $_REQUEST['returnsellbillid']; //$sellbillId//nedded for collective product##fatma
    $billReservation = (int) $_GET['reservation'];

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

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

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


    try {
        $savePaymentDateWithBillDate = (int) $_POST['savePaymentDateWithBillDate'];
        $productsBeforeValid = delete($returnsellbillId, $savePaymentDateWithBillDate);
        if ($billReservation == 4) {
            header('Location:' . $hosturl . '/controllers/salesreportbills.php?do=billReservation');
        } elseif ($productsBeforeValid[0] == 1) {
            header("location:?do=sucess");
        } else {
            $url = "returnsellbillController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = "لا يوجد بالمخزن الكمية الكافية لحذف الفاتورة";
            $smarty->assign('msgnote', $note);
            $smarty->display("notes2.html");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    //here the permssion check
    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);

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

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


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

    if ($Programsettingdata->billid != 1) {
        $allbills = $myReturnsellbillRecord->queryAll();
        $smarty->assign("returnsellbillSerialData", $allbills);
    }

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

    //here the smarty templates
    showAll();
    $smarty->display("returnsellbillview/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "executeOperation") {

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

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

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

    $returnsellbillSearchData = loadAllReturnSellBil();
    $smarty->assign("returnsellbillSearchData", $returnsellbillSearchData);




    //showAll();

    $smarty->display("returnsellbillview/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" && (!isset($_POST['curlpost']) || empty($_POST['curlpost']))) {
    $smarty->display("footer.html");
}

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

//load sellbill detail
function showDetail($returnsellbillId)
{

    global $myReturnsellbillEx;
    global $myReturnsellbilldetailEx;
    global $returnSellBillCurrEX;


    //load purchasebillreturn data by id
    $returnsellbillData = $myReturnsellbillEx->loadReturnsellbillById($returnsellbillId);
    $billCurrData = $returnSellBillCurrEX->queryOneByReturnsellbillid($returnsellbillId);
    $returnsellbilldetailData = $myReturnsellbilldetailEx->queryWithReturnsellbillId($returnsellbillId);

    $quantity = 0;
    foreach ($returnsellbilldetailData as $returnsellbilldetail) {
        $quantity = $quantity + ($returnsellbilldetail->returnsellbilldetailquantity);
    }
    ##use currency values
    if (isset($billCurrData)) {
        $returnsellbillData->returnsellbilldiscount = $billCurrData->returnsellbilldiscountC;
        $returnsellbillData->returnsellbilltotalbill = $billCurrData->returnsellbilltotalbillC;
        $returnsellbillData->returnsellbillaftertotalbill = $billCurrData->returnsellbillaftertotalbillC;
        $returnsellbillData->returnsellbilltotalpayed = $billCurrData->returnsellbilltotalpayedC;
        $returnsellbillData->returnsellbillfinalbill = $billCurrData->returnsellbillfinalbillC;
        $returnsellbillData->returnsellbildirectpayment = $billCurrData->returnsellbildirectpaymentC;
        $returnsellbillData->cashPayed = $billCurrData->cashPayedC;
        $returnsellbillData->visaPayed = $billCurrData->visaPayedC;
        $returnsellbillData->extraDiscountVal = $billCurrData->extraDiscountValC;
        $returnsellbillData->taxOfDiscountVal = $billCurrData->taxOfDiscountValC;
        ##
        $returnsellbillData->returnsellbilltotaldeptbefor = $returnsellbillData->returnsellbilltotaldeptbefor * $billCurrData->conversionFactor;
        $returnsellbillData->returnsellbilltotaldeptafter = $returnsellbillData->returnsellbilltotaldeptafter * $billCurrData->conversionFactor;
        foreach ($returnsellbilldetailData as $value) {
            $value->returnsellbilldetailprice = $value->returnsellbilldetailpriceC;
            $value->returnsellbilldetailtotalprice = $value->returnsellbilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
    }

    return array($returnsellbillData, $returnsellbilldetailData, $quantity);
}

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


    global $myBillsettingEx;

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

    return $billsettingsData;
}

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

    global $myReturnsellbillRecord;

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

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

    $queryString = ' WHERE';
    $queryStringDetails = '';
    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['returnsellbillid'];
    $clientId = (int) $_REQUEST['clientid'];
    $sellerid = $_REQUEST['sellerid'];
    $selleruserid = $_REQUEST['selleruserid'];
    $storeid = $_REQUEST['storeid'];
    $saveid = $_REQUEST['saveid'];
    $hideDel = (int) $_REQUEST['hideDel'];
    $proSellTrackingSerial = $_REQUEST['proSellTrackingSerial'];
    $userData = $myUserRecord->load($_SESSION['userid']);
    $pricetype = (isset($_REQUEST['pricetype'])) ? (int) $_REQUEST['pricetype'] : -1;

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


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


        $queryString .= ' returnsellbill.returnsellbillclientid = "' . $clientId . '" AND';
    }




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


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

            default:
                $message .= " بائع ";
                break;
        }
        $message .= ": " . $messageData->employeename;

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



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


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


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

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

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


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


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

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

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

        $queryString .= ' returnsellbill.returnsellbillsaveid = ' . $saveid . ' AND';
    }
    if (isset($pricetype) && $pricetype >= 0 && $pricetype <= 2) {
        switch ($pricetype) {
            case 0:
                $message .= "<br> نوع السعر: " . "جملة";
                break;
            case 1:
                $message .= "<br> نوع السعر: " . "تجزئة";
                break;
            case 2:
                $message .= "<br> نوع السعر: " . "نصف جمملة";
                break;
        }

        $queryString .= ' returnsellbill.pricetype = ' . $pricetype . ' AND';
    }
    if (!empty($proSellTrackingSerial)) {
        $message .= "<br> Serial : " . $proSellTrackingSerial;
        $queryStringDetails = ' and proSellTrackingSerial="' . $proSellTrackingSerial . '" ';
    }
    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 .= ' returnsellbill.returnsellbilldate >= "' . $startDate . '" and  returnsellbill.returnsellbilldate <= "' . $endDate . '" AND';
    }
    if (isset($hideDel) && $hideDel == 1) {
        $message .= "<br> اخفاء المحذوف ";
        $queryString .= ' returnsellbill.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');
    //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  returnsellbill.returnsellbilldate >= "' . $startDate . '" and  returnsellbill.returnsellbilldate <= "' . $endDate . '" ';
        if ($userData->viewbills == 0) {
            $queryString .= ' AND returnsellbill.userid =' . $_SESSION['userid'];
        } elseif ($userData->viewbills == 2) {
            $queryString .= ' AND user2.usergroupid =' . $_SESSION['usergroupid'];
        }
    }



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


    $totalBills = 0;

    if ($queryString || $queryStringDetails) {
        ##search details
        if (!empty($queryStringDetails)) {
            $detailsData = R::getAll('SELECT distinct returnsellbillid FROM returnsellbilldetail where 1 ' . $queryStringDetails);
            $sellbillidS = '';
            foreach ($detailsData as $value) {
                $sellbillidS .= $value['returnsellbillid'] . ",";
            }
            $sellbillidS = trim($sellbillidS, ",");
            $sellbillidS = empty($sellbillidS) ? 0 : $sellbillidS;
            if (empty($queryString)) {
                $queryString .= ' where 1 ';
            }
            $queryString .= " and returnsellbillid in (" . $sellbillidS . ")";
        }
        ##getting bills
        $returnsellbillData = R::getAll('SELECT *
                                   FROM returnsellbill ' . $queryString);
        list($billIDs, $userIDs, $sellerAndDelByIDs, $clientIDs, $storeIDs, $saveIDs) = [[], [], [], [], [], []];
        foreach ($returnsellbillData as $value) {
            $billIDs[] = $value['returnsellbillid'];
            $userIDs[] = $value['userid'];
            $sellerAndDelByIDs[] = $value['sellerid'];
            $sellerAndDelByIDs[] = $value['delbyuserid'];
            $clientIDs[] = $value['returnsellbillclientid'];
            $storeIDs[] = $value['returnsellbillstoreid'];
            $saveIDs[] = $value['returnsellbillsaveid'];
        }
        $billIDs = !empty($billIDs) ? array_unique($billIDs) : [0];
        $userIDs = !empty($userIDs) ? array_unique($userIDs) : [0];
        $sellerAndDelByIDs = !empty($sellerAndDelByIDs) ? array_unique($sellerAndDelByIDs) : [0];
        $clientIDs = !empty($clientIDs) ? array_unique($clientIDs) : [0];
        $storeIDs = !empty($storeIDs) ? array_unique($storeIDs) : [0];
        $saveIDs = !empty($saveIDs) ? array_unique($saveIDs) : [0];

        ##2- getting user data while applying viewbills conditions
        $userQueryString = '';
        if ($userData->viewbills == 0) {
            $userQueryString = ' AND userid =' . $_SESSION['userid'] . ' ';
        } elseif ($userData->viewbills == 2) {
            $userQueryString = ' AND user.usergroupid =' . $_SESSION['usergroupid'] . ' ';
        }
        //////$returnsellbillData = $myReturnsellbillEx->queryallWithqueryString($queryString);
        $userDataArr = R::getAll('select userid,employeename from user where userid in(' . implode(',', $userIDs) . ') ' . $userQueryString);
        $userDataArr = customArrayIndexOne($userDataArr, 'userid');
        $sellBillDataTemp = array();
        foreach ($returnsellbillData as $value) {
            if ($userDataArr[$value['userid']] !== null) {
                $value['useremployeename'] = $userDataArr[$value['userid']]['employeename'];
                $sellBillDataTemp[] = $value;
            }
        }
        $returnsellbillData = $sellBillDataTemp;
        ##3-seller, delby data
        $userDataArr = R::getAll('select userid,employeename from user where userid in(' . implode(',', $sellerAndDelByIDs) . ') ');
        $userDataArr = customArrayIndexOne($userDataArr, 'userid');
        ##4-client
        $clientDataArr = R::getAll('select clientid,clientname from client where clientid in(' . implode(',', $clientIDs) . ') ');
        $clientDataArr = customArrayIndexOne($clientDataArr, 'clientid');
        ##5- store
        $storeDataArr = R::getAll('select storeId,storeName from store where storeId in(' . implode(',', $storeIDs) . ') ');
        $storeDataArr = customArrayIndexOne($storeDataArr, 'storeId');
        ##6- save
        $saveDataArr = R::getAll('select saveid,savename from save where saveid in(' . implode(',', $saveIDs) . ') ');
        $saveDataArr = customArrayIndexOne($saveDataArr, 'saveid');
        ##7- editedbill
        $editedBillDataArr = R::getAll('select returnsellbillid,deletedsellid from returnsellbill where deletedsellid in(' . implode(',', $billIDs) . ') ');
        $editedBillDataArr = customArrayIndexOne($editedBillDataArr, 'deletedsellid');

        $sellBillDataTemp = array();
        foreach ($returnsellbillData as $value) {
            $value['employeename'] = $userDataArr[$value['sellerid']]['employeename'];
            $value['delbyusername'] = $userDataArr[$value['delbyuserid']]['employeename'];
            $value['clientname'] = $clientDataArr[$value['returnsellbillclientid']]['clientname'];
            $value['storeName'] = $storeDataArr[$value['returnsellbillstoreid']]['storeName'];
            $value['savename'] = $saveDataArr[$value['returnsellbillsaveid']]['savename'];
            $value['newSellbillidAfterEdit'] = $editedBillDataArr[$value['returnsellbillid']]['returnsellbillid'];

            $value['sellbilltotalpayed'] = (float) $value['returnsellbilltotalpayed'];
            if ($value['conditions'] == 0) {
                $totalBills += $value['returnsellbillaftertotalbill'];
            }


            ##make it obj
            $obj = new stdClass();
            foreach ($value as $key1 => $value1) {
                $obj->$key1 = $value1;
            }
            $sellBillDataTemp[] = $obj;
        }
        $returnsellbillData = $sellBillDataTemp;
    }

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


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

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

    $totalBills = 0;

    $returnsellbillData = $myReturnsellbillEx->queryWithClientId($clientId);
    if (count($returnsellbillData) > 0) {
        foreach ($returnsellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->returnsellbillaftertotalbill;
            }
        }
    }

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

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

    $totalBills = 0;

    $returnsellbillData = $myReturnsellbillEx->queryWithSerail($serial);
    if (count($returnsellbillData) > 0) {
        foreach ($returnsellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->returnsellbillaftertotalbill;
            }
        }
    }

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

function showByReturnsellbillId($returnsellbillId)
{
    global $myReturnsellbillEx;
    global $smarty;

    $totalBills = 0;

    $returnsellbillData = $myReturnsellbillEx->queryWithReturnsellbillid($returnsellbillId);
    if (count($returnsellbillData) > 0) {
        foreach ($returnsellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->returnsellbillaftertotalbill;
            }
        }
    }

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

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

    $totalBills = 0;

    $returnsellbillData = $myReturnsellbillEx->queryWithDate($startDate, $endDate);
    if (count($returnsellbillData) > 0) {
        foreach ($returnsellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->returnsellbillaftertotalbill;
            }
        }
    }

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

function delete($returnsellbillid, $savePaymentDateWithBillDate)
{


    global $myReturnsellbill;
    global $myReturnsellbillRecord;
    global $myReturnsellbillEx;
    global $myReturnsellbilldetailRecord;
    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;
    $dailyentryid = $_GET['action'];

    $note;
    liveBackupComment("-- bill delete start - returnsellbill with id = $returnsellbillid");
    //Transaction
    $mytransactions = new Transaction();
    try {
        $returnsellbillData = $myReturnsellbillRecord->load($returnsellbillid);
        if ($returnsellbillData->conditions == 0) {
            $CostcenterdetailEX->updatedellbytypeandmodelid(1, $returnsellbillid, 1);

            $returnsellbilltotalPayed = $returnsellbillData->returnsellbilltotalpayed;
            $returnsellbillStoreId = $returnsellbillData->returnsellbillstoreid;
            $returnsellbilltotaldeptAfter = $returnsellbillData->returnsellbilltotaldeptafter;
            $returnsellbilltotaldeptBefor = $returnsellbillData->returnsellbilltotaldeptbefor;
            $returnsellbillClientId = $returnsellbillData->returnsellbillclientid;
            $returnsellbillFinalBill = $returnsellbillData->returnsellbillfinalbill;
            $totalOperationCost = $returnsellbillData->returnsellbillaftertotalbill;
            $returnsellbillSaveId = $returnsellbillData->returnsellbillsaveid;
            $sellbilltotalBill = $returnsellbillData->returnsellbilltotalbill;
            $sellbillDiscount = $returnsellbillData->returnsellbilldiscount;
            $sellbillDiscountType = $returnsellbillData->returnsellbilldiscounttype;
            $sellbillaftertotalbill = $returnsellbillData->returnsellbillaftertotalbill;
            $sellbillDate = $returnsellbillData->returnsellbilldate;

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

            ##get $billTotalBeforeDiscount
            $billTotalBeforeDiscount = $sellbilltotalBill;
            ##get $billDiscountVal
            $billDiscountVal = $sellbillDiscount;
            if ($sellbillDiscountType == "2") {
                $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
                $billDiscountVal = round($billDiscountVal, 2);
            }

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

            $returnsellbilldetailData = $myReturnsellbilldetailRecord->queryByReturnsellbillid($returnsellbillid);

            foreach ($returnsellbilldetailData as $returnsellbilldetail) {
                $productId = $returnsellbilldetail->returnsellbilldetailproductid;
                $productQuantity = $returnsellbilldetail->returnsellbilldetailquantity;
                $scunitname = $returnsellbilldetail->otherdetailquantity;

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

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


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

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

                if ($isService == 0) { //product
                    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;
                    }
                } else {
                    //service
                    $productsBeforeValid = 1;
                }
            }



            $myReturnsellbill->conditions = 1;
            $myReturnsellbill->returnsellbillsysdate = date("Y-m-d");
            //$myReturnsellbill->userid = $_SESSION['userid'];
            $myReturnsellbill->userid = $returnsellbillData->userid;
            $myReturnsellbill->delbyuserid = $_SESSION['userid'];
            $myReturnsellbill->returnsellbillid = $returnsellbillid;

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

            $myReturnsellbillEx->updateConditions($myReturnsellbill, " ,billReservation= $billReservation,billReservationDate='0000-00-00' ");


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

                $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $returnsellbillStoreId, $sizeId, $colorId);
                if ($productId != '') {

                    $productunitId = $returnsellbilldetail->productunitid;



                    $quantity = $returnsellbilldetail->returnsellbilldetailquantity;
                    $detailId = $returnsellbilldetail->returnsellbilldetailid;
                    $totlPrice = $returnsellbilldetail->returnsellbilldetailtotalprice;
                    $proSerials = $returnsellbilldetail->soldSerialsInDetails;

                    $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);


                    $productnumber = $productunitData->productnumber;

                    $finalquantity = $quantity * $productnumber;


                    if (!empty($proSerials)) {
                        decreaseProductParcodeSerialQuantity($productId, $sizeId, $colorId, $finalquantity, $proSerials, $returnsellbillid, $returnsellbillClientId, $detailId, 3, '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 = 3;
                            $soldSerialProduct->sellbillid = $returnsellbillid;
                            $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, $returnsellbillid, 3, $returnsellbillClientId);
                            } else {

                                $soldSerialProduct->quantity = $finalquantity;
                                $soldSerialProduct->sellbilltype = 3;
                                $soldSerialProduct->sellbillid = $returnsellbillid;
                                $soldSerialProduct->del = 1;
                                $soldSerialProduct->productserailid = $issold->productserailid;

                                //$mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial($soldSerialProduct);
                                $mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial2($soldSerialProduct);
                                if (count($mysoldSerialProduct) > 0) {


                                    //$soldSerialProductExt->updatedel($soldSerialProduct);
                                    $soldSerialProductExt->updatedel2($soldSerialProduct);
                                    $productserailid = $mysoldSerialProduct->productserailid;

                                    updateSerailQty($productserailid, $finalquantity);
                                    //insertIntoSoldSerialProduct($productserailid, $finalquantity, $returnsellbillid, 3, $returnsellbillClientId);
                                }
                            }
                        }
                    }

                    $isService = isService($productId);
                    if ($isService == 0) { //if product
                        //get store productquantity before change
                        $storedetailData = getStoreDetails($returnsellbillStoreId, $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, $returnsellbillStoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $returnsellbillid, "حذف فاتورة مردودات مبيعات", "returnsellbillController.php", $sizeId, $colorId);
                        }

                        //other unit
                        if ($scunitname > 0) {
                            $allStoredetailData2 = getStoreDetails($returnsellbillStoreId, $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, $returnsellbillStoreId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $returnsellbillid, "تعديل فاتورة مردودات ", "returnsellbillController.php", $mydate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($returnsellbillStoreId, $productId, ($scunitname) * -1, $sellbillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $returnsellbillStoreId, $scunitname, 0, ($scunitname) * -1, 1, $returnsellbillid, "تعديل فاتورة مردودات ", "returnsellbillController.php", $mydate, 1);
                                }
                            }
                        }
                    }
                }
            }




            $returnsellbilltotalPayed = $returnsellbilltotalPayed - $visa;
            if ($returnsellbillClientId != 0) {
                //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                //if($returnsellbilltotaldeptAfter != $returnsellbilltotaldeptBefor)
                {
                    $clientData = getClientDataFromClientInUseSP($returnsellbillClientId);
                    //$clientData = loadClientDataById($returnsellbillClientId);

                    $clientdeptBefor = $clientData->clientdebt;
                    $clientdeptAfter = ($clientData->clientdebt) + ($returnsellbillFinalBill * -1);

                    //update rawmaterialssupplierdebt
                    updateClientDebt($returnsellbillClientId, $clientdeptAfter);

                    insertClientdebtchange($returnsellbillClientId, $clientdeptBefor, abs($returnsellbillFinalBill), 0, "حذف فاتورة مردودات مبيعات", $returnsellbillid, $clientdeptAfter, "returnsellbillController.php", "حذف فاتورة مردودات مبيعات", $totalOperationCost, 0, $visa, $visaAccount, $returnsellbilltotalPayed);
                    markClientAsNOTInUse($returnsellbillClientId);
                }
            }



            //check if payed or not to change save value
            $payDateToRecord = date('Y-m-d H:i:s');
            if ($savePaymentDateWithBillDate == 1) {
                $payDateToRecord = $sellbillDate;
            }
            //check if payed or not to change save value
            if ($returnsellbilltotalPayed != 0) {

                //get saveValue before and saveValue after mins sellbilltotalPayed
                $saveData = getSaveValueAndPlus($returnsellbillSaveId, abs($returnsellbilltotalPayed));
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

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

                //insert into savedaily tbl from save
                insertSavedaily($saveValuebefore, $returnsellbilltotalPayed, 0, $saveId, "حذف فاتورة مردودات مبيعات", $returnsellbillid, $saveValueafter, "returnsellbillController.php", $payDateToRecord);
            }

            quickProfitBill(0, $sellbilltotalBill, $billDiscountVal, $returnsellbillClientId, 0);

            if ($visa != 0 && $visaAccount > 0) {
                $visaAccountData = $bankAccountDAO->load($visaAccount);
                if ($isBankAccountTransfer == 1) {
                    $visaDisPerVal = 0;
                } else {
                    $visaDisPerVal = $visaAccountData->visaDisPer * .01 * $visa;
                }
                $accountBefore = $visaAccountData->accountbeginingbalance;
                $visaAccountData->accountbeginingbalance = $accountBefore + $visa - $visaDisPerVal;
                $visaAccountData->accountdate = date('Y-m-d');
                $visaAccountData->accountid = $visaAccount;
                $bankAccountEX->updateacount($visaAccountData);


                //Insert in accountmovement table the payment
                $afterVal = $accountBefore + $visa;
                insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $accountBefore, $visa, $afterVal, 0, "الغاء سداد فاتورة", "returnsellbillController.php", $returnsellbillid, $payDateToRecord, $returnsellbillClientId);

                //Insert in accountmovement table the disount per
                if ($isBankAccountTransfer != 1) {
                    $afterVal_AfterDisc = $afterVal - $visaDisPerVal;
                    insertBankAccountMovement($visaAccount, $visaAccountData->bankid, $afterVal, $visaDisPerVal, $afterVal_AfterDisc, 1, "الغاء نسبة خصم الفيزا من تحصيل فاتورة", "returnsellbillController.php", $returnsellbillid, $payDateToRecord, $returnsellbillClientId);
                }
            }
        }

        $mytransactions->commit();
    } catch (Exception $e) {
        $note = "حدث خطأ اثناء حذف الفاتورة";
        $mytransactions->rollback();
        $returnsellbillData = $myReturnsellbillRecord->load($returnsellbillid);
        $returnsellbillClientId = $returnsellbillData->returnsellbillclientid;
        markClientAsNOTInUse($returnsellbillClientId);
    }
    liveBackupComment("-- bill delete end - returnsellbill with id = $returnsellbillid");
    return array($productsBeforeValid, $note);
}

function executeOperation()
{

    global $myReturnsellbillRecord;
    global $smarty;

    $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $returnsellbillId) {

            //get store name
            $returnsellbillData = $myReturnsellbillRecord->load($returnsellbillId);

            $returnsellbillSerial = $returnsellbillData->returnsellbillserial;

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

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

function loadClientDataById($clientId)
{

    global $myClientRecord;

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

    return $clientData;
}

////////////////////////////save///////////////////////////
// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid)
{


    global $mySave;
    global $mySaveRecord;

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

    return $saveValuebefore;
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged)
{


    global $mySave;
    global $mySaveRecord;

    $saveData = getSaveDataFromSaveInUseSP($saveid); //$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)
{


    global $mySave;
    global $mySaveRecord;

    $saveData = getSaveDataFromSaveInUseSP($saveid); //$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)
{


    global $mySave;
    global $mySaveEx;

    //update initialvalue in Save tbl
    $mySave->savecurrentvalue = $savevalueafter;
    $mySave->userid = $_SESSION['userid'];
    $mySave->saveid = $saveid;

    $mySaveEx->updateSaveValue($mySave);
    markSaveAsNOTInUse($saveid);
}

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


    global $mySavedaily;
    global $mySavedailyRecord;

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = $date; //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;

    $mySavedailyRecord->insert($mySavedaily);
}

/////////////////////supplier///////////////////////
// update in rawmaterialssuppliers tbl
function updateSupplierDebt($supplierid, $supplierdebtAfter)
{


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


    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;

    $isService = 0;
    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) { //sizecolor product
        $storedetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $storedetailId = $storedetailData->id;
        $productquantityBefore = $storedetailData->quantity;
    } else {
        //select data from storerawmaterialdetails by storeid and rawmaterialid
        $storedetailData = $myStoredetailEx->queryWithStoreAndProduct($productid, $storeid);

        $storedetailId = $storedetailData->storedetailid;
        $productquantityBefore = $storedetailData->productquantity;
        $isService = $storedetailData->isService;
    }

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

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId)
{
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    ##
    $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);
    }

    //increase productquantity
    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);
        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, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //            $myStoredetailEx->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 0);
            $myStoredetailEx->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        //update productquantity in storedetail tbl
        $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);
    }

    return $productquantityAfter;
}

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


    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, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //$myStoredetailEx->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 1);
            $myStoredetailEx->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        //update productquantity in storedetail tbl
        $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($myStoredetail->productid);
        if ($isCollectiveFlag == 0) { //not collective affect its store deetail as collective affect ingridients only
            $myStoredetail->storedetailid = $storedetailId;
            $myStoredetail->userid = $_SESSION['userid'];
            $myStoredetail->storedetaildate = date("Y-m-d");
            $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);
    //retsell delete - decrease
    $isCollectiveFlag = ifCollectiveDecreaseItsIngriedientsInStore($buyProduct, $productChangeAmount, $sellbillId, $myStoredetail->storeid);
    return $productquantityAfter;
}

//add in storerawmaterialdetails tbl
function insertStoredetail($storeid, $productid, $productChangeAmount, $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);
    }
}

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


    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, $dailyentryid = 0, $visa = 0, $visaAccount = 0, $cash = 0)
{


    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 = $dailyentryid;
    $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->sellCostLastBuyPricewithDiscountAndTax = $myproduct->lastbuyprice_withDiscountAndTax * $finalQuantity;
        $obj->returnSellVal = 0;
        $obj->returnSellCostBuyPrice = 0;
        $obj->returnSellCostLastBuyPrice = 0;
        $obj->returnSellCostMeanBuyPrice = 0;
        $obj->returnSellCostLastBuyPricewithDiscount = 0;
        $obj->returnSellCostMeanBuyPricewithDiscount = 0;
        $obj->returnSellCostOverAllAveragePrice = 0;
        $obj->returnSellCostLastBuyPricewithTax = 0;
        $obj->returnSellCostLastBuyPricewithDiscountAndTax = 0;
        $obj->returnSellCostMeanBuyPricewithTax = 0;
        $obj->netQuantity = $finalQuantity;
        $obj->netQuantityRet = 0;
    } elseif ($isreturn == 1) {
        $obj->sellVal = 0;
        $obj->sellCostBuyPrice = 0;
        $obj->sellCostLastBuyPrice = 0;
        $obj->sellCostMeanBuyPrice = 0;
        $obj->sellCostLastBuyPricewithDiscount = 0;
        $obj->sellCostMeanBuyPricewithDiscount = 0;
        $obj->sellCostOverAllAveragePrice = 0;
        $obj->sellCostLastBuyPricewithTax = 0;
        $obj->sellCostLastBuyPricewithDiscountAndTax = 0;
        $obj->sellCostMeanBuyPricewithTax = 0;
        $obj->returnSellVal = $prototalWithDiscount;
        $obj->returnSellCostBuyPrice = $myproduct->productBuyPrice * $finalQuantity;
        $obj->returnSellCostLastBuyPrice = $myproduct->lastbuyprice * $finalQuantity;
        $obj->returnSellCostMeanBuyPrice = $myproduct->meanbuyprice * $finalQuantity;
        $obj->returnSellCostLastBuyPricewithDiscount = $myproduct->lastbuyprice_withDiscount * $finalQuantity;
        $obj->returnSellCostMeanBuyPricewithDiscount = $myproduct->meanbuyprice_withDiscount * $finalQuantity;
        $obj->returnSellCostOverAllAveragePrice = $myproduct->overAllAveragePrice * $finalQuantity;
        $obj->returnSellCostLastBuyPricewithTax = $myproduct->lastbuyprice_withTax * $finalQuantity;
        $obj->returnSellCostMeanBuyPricewithTax = $myproduct->meanbuyprice_withTax * $finalQuantity;
        $obj->returnSellCostLastBuyPricewithDiscountAndTax = $myproduct->lastbuyprice_withDiscountAndTax * $finalQuantity;
        $obj->netQuantity = 0;
        $obj->netQuantityRet = $finalQuantity;
    }

    $obj->storeId = $storeId;
    if ($isadd == 1) {
        $quickProfitProductEX->insertOrUpdatePlusEX($obj);
        $quickProfitStoreEX->insertOrUpdatePlusEX($obj);
    } else {
        $quickProfitProductEX->insertOrUpdateMinusEX($obj);
        $quickProfitStoreEX->insertOrUpdateMinusEX($obj);
    }
    //for totals
    $sellCostsArray["sellCostBuyPrice"] += $obj->sellCostBuyPrice;
    $sellCostsArray["sellCostLastBuyPrice"] += $obj->sellCostLastBuyPrice;
    $sellCostsArray["sellCostMeanBuyPrice"] += $obj->sellCostMeanBuyPrice;
    $sellCostsArray["sellCostLastBuyPricewithDiscount"] += $obj->sellCostLastBuyPricewithDiscount;
    $sellCostsArray["sellCostMeanBuyPricewithDiscount"] += $obj->sellCostMeanBuyPricewithDiscount;
    $sellCostsArray["sellCostOverAllAveragePrice"] += $obj->sellCostOverAllAveragePrice;
    $sellCostsArray["sellCostLastBuyPricewithTax"] += $obj->sellCostLastBuyPricewithTax;
    $sellCostsArray["sellCostMeanBuyPricewithTax"] += $obj->sellCostMeanBuyPricewithTax;
    $sellCostsArray["returnSellCostBuyPrice"] += $obj->returnSellCostBuyPrice;
    $sellCostsArray["returnSellCostLastBuyPrice"] += $obj->returnSellCostLastBuyPrice;
    $sellCostsArray["returnSellCostMeanBuyPrice"] += $obj->returnSellCostMeanBuyPrice;
    $sellCostsArray["returnSellCostLastBuyPricewithDiscount"] += $obj->returnSellCostLastBuyPricewithDiscount;
    $sellCostsArray["returnSellCostMeanBuyPricewithDiscount"] += $obj->returnSellCostMeanBuyPricewithDiscount;
    $sellCostsArray["returnSellCostOverAllAveragePrice"] += $obj->returnSellCostOverAllAveragePrice;
    $sellCostsArray["returnSellCostLastBuyPricewithTax"] += $obj->returnSellCostLastBuyPricewithTax;
    $sellCostsArray["returnSellCostMeanBuyPricewithTax"] += $obj->returnSellCostMeanBuyPricewithTax;
    $sellCostsArray["sellCostLastBuyPricewithDiscountAndTax"] += $obj->sellCostLastBuyPricewithDiscountAndTax;
    $sellCostsArray["returnSellCostLastBuyPricewithDiscountAndTax"] += $obj->returnSellCostLastBuyPricewithDiscountAndTax;
}

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 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 = "returnsellbillController.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 getClientDataFromClientInUseSP($clientid)
{
    global $clientEX;
    global $myClientRecord;
    if ($clientid == 1) {
        $client_data = $myClientRecord->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $clientEX->callClientInUseSP($clientid);
        while ($client_data->clientdebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $clientEX->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

function markClientAsNOTInUse($clientid)
{ //mark as not in use "free him to be able to change debt again"
    global $clientEX;
    if ($clientid == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $clientEX->markClientAsNOTInUse($clientid);
    }
}

function getSaveDataFromSaveInUseSP($saveid)
{
    global $mySaveEx;

    $noOfTries = 0;
    $save_data = $mySaveEx->callSaveInUseSP($saveid);

    while ($save_data->saveid < 0) {
        sleep(1);
        $noOfTries++;
        if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
            //markSaveAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
            liveBackupComment("-- force free save=$saveid with redbean");
            R::exec('UPDATE save SET  inUse = 0 where saveid = ' . $saveid);
        }
        $save_data = $mySaveEx->callSaveInUseSP($saveid);
    }
    return $save_data;
}

function markSaveAsNOTInUse($saveid)
{ //mark as not in use "free him to be able to change debt again"
    global $mySaveEx;
    $mySaveEx->markSaveAsNOTInUse($saveid);
}

function updateSerailQty($productserailId, $soldQuantity)
{
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);
    //    if ($productQuantity > 0) {
    $availableQty = $productQuantity - $soldQuantity;
    //if(isset($availableQty) && $availableQty < 0)
    //			{
    //				//في حالة بيع منتج بكمية أكبر من عدد السريالات
    //			}
    //			else
    //			{
    //
    //			}

    $myProductserial->productserailid = $productserailId;
    $myProductserial->don = $availableQty;
    //print_r($myProductserial);
    $myProductserialEx->updateDon($myProductserial);
    //    }
}

function updateSerailQty_ForReturn($productserailId, $returnedQuantity)
{
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);

    //print_r('<br>returnedQuantity'.$returnedQuantity);
    //print_r('<br>productQuantity'.$productQuantity);
    //    if ($productQuantity > 0) {
    $availableQty = $productQuantity + $returnedQuantity;

    //print_r('<br>availableQty'.$availableQty);
    $myProductserial->productserailid = $productserailId;
    $myProductserial->don = $availableQty;
    //print_r('<br>cccccccccccccccccccc'.$productserailId);
    $myProductserialEx->updateDon($myProductserial);
    //    }
}

function insertIntoSoldSerialProduct($productserailId, $soldQuantity, $sellbillId, $sellbilltype, $clientid)
{
    global $soldSerialProduct;
    global $soldSerialProductDAO;

    $soldSerialProduct->productserailid = $productserailId;
    $soldSerialProduct->quantity = $soldQuantity;
    $soldSerialProduct->sellbilltype = $sellbilltype;
    $soldSerialProduct->sellbillid = $sellbillId;
    $soldSerialProduct->del = 0;
    $soldSerialProduct->clientid = $clientid;
    //print("<br>");
    //print_r($soldSerialProduct);
    $soldSerialProductDAO->insert(
        $soldSerialProduct
    );
}

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

//-- show AJAX -----------------------------------------------------------//
/* function Name : showallajax .
  Description :send data using json to datatable.
 */
function showallajax()
{
    global $myReturnsellbillEx;
    global $ProgramsettingDAO;
    global $UsergroupDAO;
    $sIndexColumn = "returnsellbillid";

    /* DB table to use */
    $sTable = "returnsellbillview";
    $aColumns = array(
        'returnsellbillid', 'returnsellbillserial', 'returnsellbillaftertotalbill', 'returnsellbilldate', 'clientname', 'returnsellbilltotalpayed', 'returnsellbillfinalbill', '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] == "returnsellbilldate") {
                //to get numbers and english chars only
                ##only alpha numeric is allowed . space not allowed
                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
                if (!empty($search)) {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
                }
            } else {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
            }
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }
    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE';
    } else {
        $queryString = ' AND';
    }
    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['returnsellbillid'];
    $clientId = $_REQUEST['clientid'];
    $sellerid = $_REQUEST['sellerid'];
    $selleruserid = $_REQUEST['selleruserid'];
    $storeid = $_REQUEST['storeid'];
    $saveid = $_REQUEST['saveid'];
    //    $pricetype = $_REQUEST['pricetype'];

    $search = $_REQUEST['searchDate'];
    if (empty($search)) {
        $search = "dateOnly";
    }
    ##needed Data
    $Programsetting = $ProgramsettingDAO->load(1);
    $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
    $billsettingsData = loadBillProperty(4); //3 is for ret sell bill
    ############
    if (isset($clientId) && $clientId != "-1") {
        $queryString .= ' returnsellbillclientid = "' . $clientId . '" AND';
    }
    if (isset($sellerid) && $sellerid != "-1") {
        $queryString .= ' sellerid = ' . $sellerid . ' AND';
    }
    if (isset($selleruserid) && $selleruserid != "-1") {
        $queryString .= ' userid = ' . $selleruserid . ' AND';
    }
    if (isset($sellbillSerial) && $sellbillSerial != "" && $sellbillSerial != '-1') {
        $queryString .= ' returnsellbillserial = "' . $sellbillSerial . '" AND';
    }
    if (isset($sellbillId) && $sellbillId != "") {
        $queryString .= ' returnsellbillid = ' . $sellbillId . ' AND';
    }
    if (isset($storeid) && $storeid != "-1") {
        $queryString .= ' returnsellbillstoreid = ' . $storeid . ' AND';
    }
    if (isset($saveid) && $saveid != "-1") {
        $queryString .= ' returnsellbillsaveid = ' . $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";
        }
        $queryString .= ' returnsellbilldate >= "' . $startDate . '" and  returnsellbilldate <= "' . $endDate . '" AND';
    }
    //    if (isset($pricetype) && $pricetype != "-1") {
    //        $queryString .= ' pricetype = ' . $pricetype . ' AND';
    //    }
    ##############
    ##fatma

    $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 .= ' returnsellbilldate >= "' . $startDate . '" and  returnsellbilldate <= "' . $endDate . '" ';
    }
    $sWhere .= $queryString;
    //----------------------------------------------------------------------


    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
    $rResult = $myReturnsellbillEx->runSelectQuery($sQuery);

    /* Data set length after filtering */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as returnsellbillid  FROM  $sTable $sWhere "; //$sOrder
    $rResultFilterTotal = $myReturnsellbillEx->runSelectQuery($sQuery);
    foreach ($rResultFilterTotal as $oneis) {
        $countis = $oneis->returnsellbillid;
    }
    $iFilteredTotal = $countis;
    /* Total data set length */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as returnsellbillid FROM  $sTable";
    $rResultTotal = $myReturnsellbillEx->runSelectQuery($sQuery);


    foreach ($rResultTotal as $oneis) {
        $countit = $oneis->returnsellbillid;
    }
    //$aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $countit;

    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
    $sellQuantity = 0; //$piecesCount
    $sellbilltotalpayed = 0; //payedTotal
    $sellbillfinalbill = 0; //remainTotal
    $sellbillaftertotalbill = 0; //totalBills//totalBills2
    foreach ($rResult as $aRow) {
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            switch ($aColumns[$i]) {
                case "returnsellbillid":
                    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[$i];
                    break;
                case "returnsellbillserial":
                    //if ($Programsetting->billid == 0)
                    break;
                case "returnsellbillaftertotalbill":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "returnsellbilldate":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "clientname":
                    if ($aRow->$aColumns[$i] == "")
                        $aRow->$aColumns[$i] = "نقدى";
                    //
                    $row[] = $aRow->$aColumns[$i];
                    break;
                default:
                    break;
            }
        }

        $row[] = '<a href="returnsellbillController.php?do=showDetail&returnsellbillid=' . $aRow->returnsellbillid . '" type="button" class="btn btn-default btn-lg editicon"></a>';
        if ($usergroup->allowEditDelInBills == 0) {
            if ($aRow->conditions == 0) {
                $row[] = '<a href="sellbillController.php?do=editreturnsellBill&returnsellbillid=' . $aRow->returnsellbillid . '" type="button" class="btn btn-default btn-lg editicon"></a>';
                $row[] = '<a href="returnsellbillController.php?do=delete&returnsellbillid=' . $aRow->returnsellbillid . '&action=' . $aRow->dailyentryid . '" type="button" class="btn btn-default btn-lg removeicon"></a>';
            } else {
                if (isset($aRow->newSellbillidAfterEdit) && $aRow->newSellbillidAfterEdit > 0) { //<!--this bill is deleted for editing-->
                    $row[] = 'حذف للتعديل';
                    $row[] = 'حذف للتعديل';
                } else {
                    $row[] = 'تم حذف الفاتورة';
                    $row[] = 'تم حذف الفاتورة';
                }
            }
        }


        // '10 returnsellQuantity', '11 returnsellbilltotalpayed', '12 returnsellbillfinalbill', '13 newSellbillidAfterEdit', '14 conditions', '15 dailyentryid');
        if ($aRow->conditions == 0) { //not del not the old edit of bill
            $sellQuantity += $aRow->returnsellQuantity;
            $sellbilltotalpayed += $aRow->returnsellbilltotalpayed;
            $sellbillfinalbill += $aRow->returnsellbillfinalbill;
            $sellbillaftertotalbill += $aRow->returnsellbillaftertotalbill;
        }
        $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);
        }
    }
}
